blob: 8376b9f8a30b39ca5f3a88c27c39890c5150b556 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +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//
14// Options to support:
15// -H - Print the name of each header file used.
16// -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//
26//===----------------------------------------------------------------------===//
27
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Lex/HeaderSearch.h"
30#include "clang/Lex/MacroInfo.h"
31#include "clang/Lex/PPCallbacks.h"
32#include "clang/Lex/Pragma.h"
33#include "clang/Lex/ScratchBuffer.h"
34#include "clang/Basic/Diagnostic.h"
35#include "clang/Basic/FileManager.h"
36#include "clang/Basic/SourceManager.h"
37#include "clang/Basic/TargetInfo.h"
38#include "llvm/ADT/SmallVector.h"
39#include <iostream>
Reid Spencer5f016e22007-07-11 17:01:13 +000040using namespace clang;
41
42//===----------------------------------------------------------------------===//
43
44Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
45 TargetInfo &target, SourceManager &SM,
46 HeaderSearch &Headers)
47 : Diags(diags), Features(opts), Target(target), FileMgr(Headers.getFileMgr()),
48 SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts),
49 CurLexer(0), CurDirLookup(0), CurMacroExpander(0), Callbacks(0) {
50 ScratchBuf = new ScratchBuffer(SourceMgr);
Chris Lattner9594acf2007-07-15 00:25:26 +000051
Reid Spencer5f016e22007-07-11 17:01:13 +000052 // Clear stats.
53 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
54 NumIf = NumElse = NumEndif = 0;
55 NumEnteredSourceFiles = 0;
56 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
57 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
58 MaxIncludeStackDepth = 0;
59 NumSkipped = 0;
60
61 // Default to discarding comments.
62 KeepComments = false;
63 KeepMacroComments = false;
64
65 // Macro expansion is enabled.
66 DisableMacroExpansion = false;
67 InMacroArgs = false;
Chris Lattner9594acf2007-07-15 00:25:26 +000068 NumCachedMacroExpanders = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000069
70 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
71 // This gets unpoisoned where it is allowed.
72 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
73
74 // Initialize the pragma handlers.
75 PragmaHandlers = new PragmaNamespace(0);
76 RegisterBuiltinPragmas();
77
78 // Initialize builtin macros like __LINE__ and friends.
79 RegisterBuiltinMacros();
80}
81
82Preprocessor::~Preprocessor() {
83 // Free any active lexers.
84 delete CurLexer;
85
86 while (!IncludeMacroStack.empty()) {
87 delete IncludeMacroStack.back().TheLexer;
88 delete IncludeMacroStack.back().TheMacroExpander;
89 IncludeMacroStack.pop_back();
90 }
91
Chris Lattner9594acf2007-07-15 00:25:26 +000092 // Free any cached macro expanders.
93 for (unsigned i = 0, e = NumCachedMacroExpanders; i != e; ++i)
94 delete MacroExpanderCache[i];
95
Reid Spencer5f016e22007-07-11 17:01:13 +000096 // Release pragma information.
97 delete PragmaHandlers;
98
99 // Delete the scratch buffer info.
100 delete ScratchBuf;
101}
102
103PPCallbacks::~PPCallbacks() {
104}
105
106/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
107/// the specified LexerToken's location, translating the token's start
108/// position in the current buffer into a SourcePosition object for rendering.
109void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID) {
110 Diags.Report(Loc, DiagID);
111}
112
113void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
114 const std::string &Msg) {
115 Diags.Report(Loc, DiagID, &Msg, 1);
116}
117
118void Preprocessor::DumpToken(const LexerToken &Tok, bool DumpFlags) const {
119 std::cerr << tok::getTokenName(Tok.getKind()) << " '"
120 << getSpelling(Tok) << "'";
121
122 if (!DumpFlags) return;
123 std::cerr << "\t";
124 if (Tok.isAtStartOfLine())
125 std::cerr << " [StartOfLine]";
126 if (Tok.hasLeadingSpace())
127 std::cerr << " [LeadingSpace]";
128 if (Tok.isExpandDisabled())
129 std::cerr << " [ExpandDisabled]";
130 if (Tok.needsCleaning()) {
131 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
132 std::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
133 << "']";
134 }
135}
136
137void Preprocessor::DumpMacro(const MacroInfo &MI) const {
138 std::cerr << "MACRO: ";
139 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
140 DumpToken(MI.getReplacementToken(i));
141 std::cerr << " ";
142 }
143 std::cerr << "\n";
144}
145
146void Preprocessor::PrintStats() {
147 std::cerr << "\n*** Preprocessor Stats:\n";
148 std::cerr << NumDirectives << " directives found:\n";
149 std::cerr << " " << NumDefined << " #define.\n";
150 std::cerr << " " << NumUndefined << " #undef.\n";
151 std::cerr << " #include/#include_next/#import:\n";
152 std::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
153 std::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
154 std::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
155 std::cerr << " " << NumElse << " #else/#elif.\n";
156 std::cerr << " " << NumEndif << " #endif.\n";
157 std::cerr << " " << NumPragma << " #pragma.\n";
158 std::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
159
160 std::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
161 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
162 << NumFastMacroExpanded << " on the fast path.\n";
163 std::cerr << (NumFastTokenPaste+NumTokenPaste)
164 << " token paste (##) operations performed, "
165 << NumFastTokenPaste << " on the fast path.\n";
166}
167
168//===----------------------------------------------------------------------===//
169// Token Spelling
170//===----------------------------------------------------------------------===//
171
172
173/// getSpelling() - Return the 'spelling' of this token. The spelling of a
174/// token are the characters used to represent the token in the source file
175/// after trigraph expansion and escaped-newline folding. In particular, this
176/// wants to get the true, uncanonicalized, spelling of things like digraphs
177/// UCNs, etc.
178std::string Preprocessor::getSpelling(const LexerToken &Tok) const {
179 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
180
181 // If this token contains nothing interesting, return it directly.
182 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
183 if (!Tok.needsCleaning())
184 return std::string(TokStart, TokStart+Tok.getLength());
185
186 std::string Result;
187 Result.reserve(Tok.getLength());
188
189 // Otherwise, hard case, relex the characters into the string.
190 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
191 Ptr != End; ) {
192 unsigned CharSize;
193 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
194 Ptr += CharSize;
195 }
196 assert(Result.size() != unsigned(Tok.getLength()) &&
197 "NeedsCleaning flag set on something that didn't need cleaning!");
198 return Result;
199}
200
201/// getSpelling - This method is used to get the spelling of a token into a
202/// preallocated buffer, instead of as an std::string. The caller is required
203/// to allocate enough space for the token, which is guaranteed to be at least
204/// Tok.getLength() bytes long. The actual length of the token is returned.
205///
206/// Note that this method may do two possible things: it may either fill in
207/// the buffer specified with characters, or it may *change the input pointer*
208/// to point to a constant buffer with the data already in it (avoiding a
209/// copy). The caller is not allowed to modify the returned buffer pointer
210/// if an internal buffer is returned.
211unsigned Preprocessor::getSpelling(const LexerToken &Tok,
212 const char *&Buffer) const {
213 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
214
215 // If this token is an identifier, just return the string from the identifier
216 // table, which is very quick.
217 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
218 Buffer = II->getName();
219 return Tok.getLength();
220 }
221
222 // Otherwise, compute the start of the token in the input lexer buffer.
223 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
224
225 // If this token contains nothing interesting, return it directly.
226 if (!Tok.needsCleaning()) {
227 Buffer = TokStart;
228 return Tok.getLength();
229 }
230 // Otherwise, hard case, relex the characters into the string.
231 char *OutBuf = const_cast<char*>(Buffer);
232 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
233 Ptr != End; ) {
234 unsigned CharSize;
235 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
236 Ptr += CharSize;
237 }
238 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
239 "NeedsCleaning flag set on something that didn't need cleaning!");
240
241 return OutBuf-Buffer;
242}
243
244
245/// CreateString - Plop the specified string into a scratch buffer and return a
246/// location for it. If specified, the source location provides a source
247/// location for the token.
248SourceLocation Preprocessor::
249CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
250 if (SLoc.isValid())
251 return ScratchBuf->getToken(Buf, Len, SLoc);
252 return ScratchBuf->getToken(Buf, Len);
253}
254
255
256//===----------------------------------------------------------------------===//
257// Source File Location Methods.
258//===----------------------------------------------------------------------===//
259
260/// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
261/// return null on failure. isAngled indicates whether the file reference is
262/// for system #include's or not (i.e. using <> instead of "").
263const FileEntry *Preprocessor::LookupFile(const char *FilenameStart,
264 const char *FilenameEnd,
265 bool isAngled,
266 const DirectoryLookup *FromDir,
267 const DirectoryLookup *&CurDir) {
268 // If the header lookup mechanism may be relative to the current file, pass in
269 // info about where the current file is.
270 const FileEntry *CurFileEnt = 0;
271 if (!FromDir) {
272 unsigned TheFileID = getCurrentFileLexer()->getCurFileID();
273 CurFileEnt = SourceMgr.getFileEntryForFileID(TheFileID);
274 }
275
276 // Do a standard file entry lookup.
277 CurDir = CurDirLookup;
278 const FileEntry *FE =
279 HeaderInfo.LookupFile(FilenameStart, FilenameEnd,
280 isAngled, FromDir, CurDir, CurFileEnt);
281 if (FE) return FE;
282
283 // Otherwise, see if this is a subframework header. If so, this is relative
284 // to one of the headers on the #include stack. Walk the list of the current
285 // headers on the #include stack and pass them to HeaderInfo.
286 if (CurLexer && !CurLexer->Is_PragmaLexer) {
287 CurFileEnt = SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID());
288 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
289 CurFileEnt)))
290 return FE;
291 }
292
293 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
294 IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
295 if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) {
296 CurFileEnt =
297 SourceMgr.getFileEntryForFileID(ISEntry.TheLexer->getCurFileID());
298 if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd,
299 CurFileEnt)))
300 return FE;
301 }
302 }
303
304 // Otherwise, we really couldn't find the file.
305 return 0;
306}
307
308/// isInPrimaryFile - Return true if we're in the top-level file, not in a
309/// #include.
310bool Preprocessor::isInPrimaryFile() const {
311 if (CurLexer && !CurLexer->Is_PragmaLexer)
312 return CurLexer->isMainFile();
313
314 // If there are any stacked lexers, we're in a #include.
315 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i)
316 if (IncludeMacroStack[i].TheLexer &&
317 !IncludeMacroStack[i].TheLexer->Is_PragmaLexer)
318 return IncludeMacroStack[i].TheLexer->isMainFile();
319 return false;
320}
321
322/// getCurrentLexer - Return the current file lexer being lexed from. Note
323/// that this ignores any potentially active macro expansions and _Pragma
324/// expansions going on at the time.
325Lexer *Preprocessor::getCurrentFileLexer() const {
326 if (CurLexer && !CurLexer->Is_PragmaLexer) return CurLexer;
327
328 // Look for a stacked lexer.
329 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
330 Lexer *L = IncludeMacroStack[i-1].TheLexer;
331 if (L && !L->Is_PragmaLexer) // Ignore macro & _Pragma expansions.
332 return L;
333 }
334 return 0;
335}
336
337
338/// EnterSourceFile - Add a source file to the top of the include stack and
339/// start lexing tokens from it instead of the current buffer. Return true
340/// on failure.
341void Preprocessor::EnterSourceFile(unsigned FileID,
342 const DirectoryLookup *CurDir,
343 bool isMainFile) {
344 assert(CurMacroExpander == 0 && "Cannot #include a file inside a macro!");
345 ++NumEnteredSourceFiles;
346
347 if (MaxIncludeStackDepth < IncludeMacroStack.size())
348 MaxIncludeStackDepth = IncludeMacroStack.size();
349
350 const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(FileID);
351 Lexer *TheLexer = new Lexer(Buffer, FileID, *this);
352 if (isMainFile) TheLexer->setIsMainFile();
353 EnterSourceFileWithLexer(TheLexer, CurDir);
354}
355
356/// EnterSourceFile - Add a source file to the top of the include stack and
357/// start lexing tokens from it instead of the current buffer.
358void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
359 const DirectoryLookup *CurDir) {
360
361 // Add the current lexer to the include stack.
362 if (CurLexer || CurMacroExpander)
363 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
364 CurMacroExpander));
365
366 CurLexer = TheLexer;
367 CurDirLookup = CurDir;
368 CurMacroExpander = 0;
369
370 // Notify the client, if desired, that we are in a new source file.
371 if (Callbacks && !CurLexer->Is_PragmaLexer) {
372 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
373
374 // Get the file entry for the current file.
375 if (const FileEntry *FE =
376 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
377 FileType = HeaderInfo.getFileDirFlavor(FE);
378
379 Callbacks->FileChanged(SourceLocation(CurLexer->getCurFileID(), 0),
380 PPCallbacks::EnterFile, FileType);
381 }
382}
383
384
385
386/// EnterMacro - Add a Macro to the top of the include stack and start lexing
387/// tokens from it instead of the current buffer.
388void Preprocessor::EnterMacro(LexerToken &Tok, MacroArgs *Args) {
389 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
390 CurMacroExpander));
391 CurLexer = 0;
392 CurDirLookup = 0;
393
Chris Lattner9594acf2007-07-15 00:25:26 +0000394 if (NumCachedMacroExpanders == 0) {
395 CurMacroExpander = new MacroExpander(Tok, Args, *this);
396 } else {
397 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
398 CurMacroExpander->Init(Tok, Args);
399 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000400}
401
402/// EnterTokenStream - Add a "macro" context to the top of the include stack,
403/// which will cause the lexer to start returning the specified tokens. Note
404/// that these tokens will be re-macro-expanded when/if expansion is enabled.
405/// This method assumes that the specified stream of tokens has a permanent
406/// owner somewhere, so they do not need to be copied.
407void Preprocessor::EnterTokenStream(const LexerToken *Toks, unsigned NumToks) {
408 // Save our current state.
409 IncludeMacroStack.push_back(IncludeStackInfo(CurLexer, CurDirLookup,
410 CurMacroExpander));
411 CurLexer = 0;
412 CurDirLookup = 0;
413
414 // Create a macro expander to expand from the specified token stream.
Chris Lattner9594acf2007-07-15 00:25:26 +0000415 if (NumCachedMacroExpanders == 0) {
416 CurMacroExpander = new MacroExpander(Toks, NumToks, *this);
417 } else {
418 CurMacroExpander = MacroExpanderCache[--NumCachedMacroExpanders];
419 CurMacroExpander->Init(Toks, NumToks);
420 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000421}
422
423/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
424/// lexer stack. This should only be used in situations where the current
425/// state of the top-of-stack lexer is known.
426void Preprocessor::RemoveTopOfLexerStack() {
427 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Chris Lattner9594acf2007-07-15 00:25:26 +0000428
429 if (CurMacroExpander) {
430 // Delete or cache the now-dead macro expander.
431 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
432 delete CurMacroExpander;
433 else
434 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
435 } else {
436 delete CurLexer;
437 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000438 CurLexer = IncludeMacroStack.back().TheLexer;
439 CurDirLookup = IncludeMacroStack.back().TheDirLookup;
440 CurMacroExpander = IncludeMacroStack.back().TheMacroExpander;
441 IncludeMacroStack.pop_back();
442}
443
444//===----------------------------------------------------------------------===//
445// Macro Expansion Handling.
446//===----------------------------------------------------------------------===//
447
448/// RegisterBuiltinMacro - Register the specified identifier in the identifier
449/// table and mark it as a builtin macro to be expanded.
450IdentifierInfo *Preprocessor::RegisterBuiltinMacro(const char *Name) {
451 // Get the identifier.
452 IdentifierInfo *Id = getIdentifierInfo(Name);
453
454 // Mark it as being a macro that is builtin.
455 MacroInfo *MI = new MacroInfo(SourceLocation());
456 MI->setIsBuiltinMacro();
457 Id->setMacroInfo(MI);
458 return Id;
459}
460
461
462/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
463/// identifier table.
464void Preprocessor::RegisterBuiltinMacros() {
465 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
466 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
467 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
468 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
469 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
470
471 // GCC Extensions.
472 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
473 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
474 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
475}
476
477/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
478/// in its expansion, currently expands to that token literally.
479static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
480 const IdentifierInfo *MacroIdent) {
481 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
482
483 // If the token isn't an identifier, it's always literally expanded.
484 if (II == 0) return true;
485
486 // If the identifier is a macro, and if that macro is enabled, it may be
487 // expanded so it's not a trivial expansion.
488 if (II->getMacroInfo() && II->getMacroInfo()->isEnabled() &&
489 // Fast expanding "#define X X" is ok, because X would be disabled.
490 II != MacroIdent)
491 return false;
492
493 // If this is an object-like macro invocation, it is safe to trivially expand
494 // it.
495 if (MI->isObjectLike()) return true;
496
497 // If this is a function-like macro invocation, it's safe to trivially expand
498 // as long as the identifier is not a macro argument.
499 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
500 I != E; ++I)
501 if (*I == II)
502 return false; // Identifier is a macro argument.
503
504 return true;
505}
506
507
508/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
509/// lexed is a '('. If so, consume the token and return true, if not, this
510/// method should have no observable side-effect on the lexed tokens.
511bool Preprocessor::isNextPPTokenLParen() {
512 // Do some quick tests for rejection cases.
513 unsigned Val;
514 if (CurLexer)
515 Val = CurLexer->isNextPPTokenLParen();
516 else
517 Val = CurMacroExpander->isNextTokenLParen();
518
519 if (Val == 2) {
520 // If we ran off the end of the lexer or macro expander, walk the include
521 // stack, looking for whatever will return the next token.
522 for (unsigned i = IncludeMacroStack.size(); Val == 2 && i != 0; --i) {
523 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
524 if (Entry.TheLexer)
525 Val = Entry.TheLexer->isNextPPTokenLParen();
526 else
527 Val = Entry.TheMacroExpander->isNextTokenLParen();
528 }
529 }
530
531 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
532 // have found something that isn't a '(' or we found the end of the
533 // translation unit. In either case, return false.
534 if (Val != 1)
535 return false;
536
537 LexerToken Tok;
538 LexUnexpandedToken(Tok);
539 assert(Tok.getKind() == tok::l_paren && "Error computing l-paren-ness?");
540 return true;
541}
542
543/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
544/// expanded as a macro, handle it and return the next token as 'Identifier'.
545bool Preprocessor::HandleMacroExpandedIdentifier(LexerToken &Identifier,
546 MacroInfo *MI) {
547
548 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
549 if (MI->isBuiltinMacro()) {
550 ExpandBuiltinMacro(Identifier);
551 return false;
552 }
553
554 // If this is the first use of a target-specific macro, warn about it.
555 if (MI->isTargetSpecific()) {
556 MI->setIsTargetSpecific(false); // Don't warn on second use.
557 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
558 diag::port_target_macro_use);
559 }
560
561 /// Args - If this is a function-like macro expansion, this contains,
562 /// for each macro argument, the list of tokens that were provided to the
563 /// invocation.
564 MacroArgs *Args = 0;
565
566 // If this is a function-like macro, read the arguments.
567 if (MI->isFunctionLike()) {
568 // C99 6.10.3p10: If the preprocessing token immediately after the the macro
569 // name isn't a '(', this macro should not be expanded.
570 if (!isNextPPTokenLParen())
571 return true;
572
573 // Remember that we are now parsing the arguments to a macro invocation.
574 // Preprocessor directives used inside macro arguments are not portable, and
575 // this enables the warning.
576 InMacroArgs = true;
577 Args = ReadFunctionLikeMacroArgs(Identifier, MI);
578
579 // Finished parsing args.
580 InMacroArgs = false;
581
582 // If there was an error parsing the arguments, bail out.
583 if (Args == 0) return false;
584
585 ++NumFnMacroExpanded;
586 } else {
587 ++NumMacroExpanded;
588 }
589
590 // Notice that this macro has been used.
591 MI->setIsUsed(true);
592
593 // If we started lexing a macro, enter the macro expansion body.
594
595 // If this macro expands to no tokens, don't bother to push it onto the
596 // expansion stack, only to take it right back off.
597 if (MI->getNumTokens() == 0) {
598 // No need for arg info.
599 if (Args) Args->destroy();
600
601 // Ignore this macro use, just return the next token in the current
602 // buffer.
603 bool HadLeadingSpace = Identifier.hasLeadingSpace();
604 bool IsAtStartOfLine = Identifier.isAtStartOfLine();
605
606 Lex(Identifier);
607
608 // If the identifier isn't on some OTHER line, inherit the leading
609 // whitespace/first-on-a-line property of this token. This handles
610 // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is
611 // empty.
612 if (!Identifier.isAtStartOfLine()) {
613 if (IsAtStartOfLine) Identifier.setFlag(LexerToken::StartOfLine);
614 if (HadLeadingSpace) Identifier.setFlag(LexerToken::LeadingSpace);
615 }
616 ++NumFastMacroExpanded;
617 return false;
618
619 } else if (MI->getNumTokens() == 1 &&
620 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo())){
621 // Otherwise, if this macro expands into a single trivially-expanded
622 // token: expand it now. This handles common cases like
623 // "#define VAL 42".
624
625 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
626 // identifier to the expanded token.
627 bool isAtStartOfLine = Identifier.isAtStartOfLine();
628 bool hasLeadingSpace = Identifier.hasLeadingSpace();
629
630 // Remember where the token is instantiated.
631 SourceLocation InstantiateLoc = Identifier.getLocation();
632
633 // Replace the result token.
634 Identifier = MI->getReplacementToken(0);
635
636 // Restore the StartOfLine/LeadingSpace markers.
637 Identifier.setFlagValue(LexerToken::StartOfLine , isAtStartOfLine);
638 Identifier.setFlagValue(LexerToken::LeadingSpace, hasLeadingSpace);
639
640 // Update the tokens location to include both its logical and physical
641 // locations.
642 SourceLocation Loc =
643 SourceMgr.getInstantiationLoc(Identifier.getLocation(), InstantiateLoc);
644 Identifier.setLocation(Loc);
645
646 // If this is #define X X, we must mark the result as unexpandible.
647 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo())
648 if (NewII->getMacroInfo() == MI)
649 Identifier.setFlag(LexerToken::DisableExpand);
650
651 // Since this is not an identifier token, it can't be macro expanded, so
652 // we're done.
653 ++NumFastMacroExpanded;
654 return false;
655 }
656
657 // Start expanding the macro.
658 EnterMacro(Identifier, Args);
659
660 // Now that the macro is at the top of the include stack, ask the
661 // preprocessor to read the next token from it.
662 Lex(Identifier);
663 return false;
664}
665
666/// ReadFunctionLikeMacroArgs - After reading "MACRO(", this method is
667/// invoked to read all of the actual arguments specified for the macro
668/// invocation. This returns null on error.
669MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(LexerToken &MacroName,
670 MacroInfo *MI) {
671 // The number of fixed arguments to parse.
672 unsigned NumFixedArgsLeft = MI->getNumArgs();
673 bool isVariadic = MI->isVariadic();
674
675 // Outer loop, while there are more arguments, keep reading them.
676 LexerToken Tok;
677 Tok.setKind(tok::comma);
678 --NumFixedArgsLeft; // Start reading the first arg.
679
680 // ArgTokens - Build up a list of tokens that make up each argument. Each
681 // argument is separated by an EOF token. Use a SmallVector so we can avoid
682 // heap allocations in the common case.
683 llvm::SmallVector<LexerToken, 64> ArgTokens;
684
685 unsigned NumActuals = 0;
686 while (Tok.getKind() == tok::comma) {
687 // C99 6.10.3p11: Keep track of the number of l_parens we have seen.
688 unsigned NumParens = 0;
689
690 while (1) {
691 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
692 // an argument value in a macro could expand to ',' or '(' or ')'.
693 LexUnexpandedToken(Tok);
694
695 if (Tok.getKind() == tok::eof) {
696 Diag(MacroName, diag::err_unterm_macro_invoc);
697 // Do not lose the EOF. Return it to the client.
698 MacroName = Tok;
699 return 0;
700 } else if (Tok.getKind() == tok::r_paren) {
701 // If we found the ) token, the macro arg list is done.
702 if (NumParens-- == 0)
703 break;
704 } else if (Tok.getKind() == tok::l_paren) {
705 ++NumParens;
706 } else if (Tok.getKind() == tok::comma && NumParens == 0) {
707 // Comma ends this argument if there are more fixed arguments expected.
708 if (NumFixedArgsLeft)
709 break;
710
711 // If this is not a variadic macro, too many args were specified.
712 if (!isVariadic) {
713 // Emit the diagnostic at the macro name in case there is a missing ).
714 // Emitting it at the , could be far away from the macro name.
715 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
716 return 0;
717 }
718 // Otherwise, continue to add the tokens to this variable argument.
719 } else if (Tok.getKind() == tok::comment && !KeepMacroComments) {
720 // If this is a comment token in the argument list and we're just in
721 // -C mode (not -CC mode), discard the comment.
722 continue;
723 }
724
725 ArgTokens.push_back(Tok);
726 }
727
728 // Empty arguments are standard in C99 and supported as an extension in
729 // other modes.
730 if (ArgTokens.empty() && !Features.C99)
731 Diag(Tok, diag::ext_empty_fnmacro_arg);
732
733 // Add a marker EOF token to the end of the token list for this argument.
734 LexerToken EOFTok;
735 EOFTok.startToken();
736 EOFTok.setKind(tok::eof);
737 EOFTok.setLocation(Tok.getLocation());
738 EOFTok.setLength(0);
739 ArgTokens.push_back(EOFTok);
740 ++NumActuals;
741 --NumFixedArgsLeft;
742 };
743
744 // Okay, we either found the r_paren. Check to see if we parsed too few
745 // arguments.
746 unsigned MinArgsExpected = MI->getNumArgs();
747
748 // See MacroArgs instance var for description of this.
749 bool isVarargsElided = false;
750
751 if (NumActuals < MinArgsExpected) {
752 // There are several cases where too few arguments is ok, handle them now.
753 if (NumActuals+1 == MinArgsExpected && MI->isVariadic()) {
754 // Varargs where the named vararg parameter is missing: ok as extension.
755 // #define A(x, ...)
756 // A("blah")
757 Diag(Tok, diag::ext_missing_varargs_arg);
758
759 // Remember this occurred if this is a C99 macro invocation with at least
760 // one actual argument.
761 isVarargsElided = MI->isC99Varargs() && MI->getNumArgs() > 1;
762 } else if (MI->getNumArgs() == 1) {
763 // #define A(x)
764 // A()
765 // is ok because it is an empty argument.
766
767 // Empty arguments are standard in C99 and supported as an extension in
768 // other modes.
769 if (ArgTokens.empty() && !Features.C99)
770 Diag(Tok, diag::ext_empty_fnmacro_arg);
771 } else {
772 // Otherwise, emit the error.
773 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
774 return 0;
775 }
776
777 // Add a marker EOF token to the end of the token list for this argument.
778 SourceLocation EndLoc = Tok.getLocation();
779 Tok.startToken();
780 Tok.setKind(tok::eof);
781 Tok.setLocation(EndLoc);
782 Tok.setLength(0);
783 ArgTokens.push_back(Tok);
784 }
785
786 return MacroArgs::create(MI, &ArgTokens[0], ArgTokens.size(),isVarargsElided);
787}
788
789/// ComputeDATE_TIME - Compute the current time, enter it into the specified
790/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
791/// the identifier tokens inserted.
792static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
793 Preprocessor &PP) {
794 time_t TT = time(0);
795 struct tm *TM = localtime(&TT);
796
797 static const char * const Months[] = {
798 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
799 };
800
801 char TmpBuffer[100];
802 sprintf(TmpBuffer, "\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday,
803 TM->tm_year+1900);
804 DATELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
805
806 sprintf(TmpBuffer, "\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec);
807 TIMELoc = PP.CreateString(TmpBuffer, strlen(TmpBuffer));
808}
809
810/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
811/// as a builtin macro, handle it and return the next token as 'Tok'.
812void Preprocessor::ExpandBuiltinMacro(LexerToken &Tok) {
813 // Figure out which token this is.
814 IdentifierInfo *II = Tok.getIdentifierInfo();
815 assert(II && "Can't be a macro without id info!");
816
817 // If this is an _Pragma directive, expand it, invoke the pragma handler, then
818 // lex the token after it.
819 if (II == Ident_Pragma)
820 return Handle_Pragma(Tok);
821
822 ++NumBuiltinMacroExpanded;
823
824 char TmpBuffer[100];
825
826 // Set up the return result.
827 Tok.setIdentifierInfo(0);
828 Tok.clearFlag(LexerToken::NeedsCleaning);
829
830 if (II == Ident__LINE__) {
831 // __LINE__ expands to a simple numeric value.
832 sprintf(TmpBuffer, "%u", SourceMgr.getLineNumber(Tok.getLocation()));
833 unsigned Length = strlen(TmpBuffer);
834 Tok.setKind(tok::numeric_constant);
835 Tok.setLength(Length);
836 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
837 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
838 SourceLocation Loc = Tok.getLocation();
839 if (II == Ident__BASE_FILE__) {
840 Diag(Tok, diag::ext_pp_base_file);
841 SourceLocation NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
842 while (NextLoc.getFileID() != 0) {
843 Loc = NextLoc;
844 NextLoc = SourceMgr.getIncludeLoc(Loc.getFileID());
845 }
846 }
847
848 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
849 std::string FN = SourceMgr.getSourceName(Loc);
850 FN = '"' + Lexer::Stringify(FN) + '"';
851 Tok.setKind(tok::string_literal);
852 Tok.setLength(FN.size());
853 Tok.setLocation(CreateString(&FN[0], FN.size(), Tok.getLocation()));
854 } else if (II == Ident__DATE__) {
855 if (!DATELoc.isValid())
856 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
857 Tok.setKind(tok::string_literal);
858 Tok.setLength(strlen("\"Mmm dd yyyy\""));
859 Tok.setLocation(SourceMgr.getInstantiationLoc(DATELoc, Tok.getLocation()));
860 } else if (II == Ident__TIME__) {
861 if (!TIMELoc.isValid())
862 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
863 Tok.setKind(tok::string_literal);
864 Tok.setLength(strlen("\"hh:mm:ss\""));
865 Tok.setLocation(SourceMgr.getInstantiationLoc(TIMELoc, Tok.getLocation()));
866 } else if (II == Ident__INCLUDE_LEVEL__) {
867 Diag(Tok, diag::ext_pp_include_level);
868
869 // Compute the include depth of this token.
870 unsigned Depth = 0;
871 SourceLocation Loc = SourceMgr.getIncludeLoc(Tok.getLocation().getFileID());
872 for (; Loc.getFileID() != 0; ++Depth)
873 Loc = SourceMgr.getIncludeLoc(Loc.getFileID());
874
875 // __INCLUDE_LEVEL__ expands to a simple numeric value.
876 sprintf(TmpBuffer, "%u", Depth);
877 unsigned Length = strlen(TmpBuffer);
878 Tok.setKind(tok::numeric_constant);
879 Tok.setLength(Length);
880 Tok.setLocation(CreateString(TmpBuffer, Length, Tok.getLocation()));
881 } else if (II == Ident__TIMESTAMP__) {
882 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
883 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
884 Diag(Tok, diag::ext_pp_timestamp);
885
886 // Get the file that we are lexing out of. If we're currently lexing from
887 // a macro, dig into the include stack.
888 const FileEntry *CurFile = 0;
889 Lexer *TheLexer = getCurrentFileLexer();
890
891 if (TheLexer)
892 CurFile = SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
893
894 // If this file is older than the file it depends on, emit a diagnostic.
895 const char *Result;
896 if (CurFile) {
897 time_t TT = CurFile->getModificationTime();
898 struct tm *TM = localtime(&TT);
899 Result = asctime(TM);
900 } else {
901 Result = "??? ??? ?? ??:??:?? ????\n";
902 }
903 TmpBuffer[0] = '"';
904 strcpy(TmpBuffer+1, Result);
905 unsigned Len = strlen(TmpBuffer);
906 TmpBuffer[Len-1] = '"'; // Replace the newline with a quote.
907 Tok.setKind(tok::string_literal);
908 Tok.setLength(Len);
909 Tok.setLocation(CreateString(TmpBuffer, Len, Tok.getLocation()));
910 } else {
911 assert(0 && "Unknown identifier!");
912 }
913}
914
915//===----------------------------------------------------------------------===//
916// Lexer Event Handling.
917//===----------------------------------------------------------------------===//
918
919/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
920/// identifier information for the token and install it into the token.
921IdentifierInfo *Preprocessor::LookUpIdentifierInfo(LexerToken &Identifier,
922 const char *BufPtr) {
923 assert(Identifier.getKind() == tok::identifier && "Not an identifier!");
924 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
925
926 // Look up this token, see if it is a macro, or if it is a language keyword.
927 IdentifierInfo *II;
928 if (BufPtr && !Identifier.needsCleaning()) {
929 // No cleaning needed, just use the characters from the lexed buffer.
930 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
931 } else {
932 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattnerc35717a2007-07-13 17:10:38 +0000933 llvm::SmallVector<char, 64> IdentifierBuffer;
934 IdentifierBuffer.resize(Identifier.getLength());
935 const char *TmpBuf = &IdentifierBuffer[0];
Reid Spencer5f016e22007-07-11 17:01:13 +0000936 unsigned Size = getSpelling(Identifier, TmpBuf);
937 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
938 }
939 Identifier.setIdentifierInfo(II);
940 return II;
941}
942
943
944/// HandleIdentifier - This callback is invoked when the lexer reads an
945/// identifier. This callback looks up the identifier in the map and/or
946/// potentially macro expands it or turns it into a named token (like 'for').
947void Preprocessor::HandleIdentifier(LexerToken &Identifier) {
948 assert(Identifier.getIdentifierInfo() &&
949 "Can't handle identifiers without identifier info!");
950
951 IdentifierInfo &II = *Identifier.getIdentifierInfo();
952
953 // If this identifier was poisoned, and if it was not produced from a macro
954 // expansion, emit an error.
955 if (II.isPoisoned() && CurLexer) {
956 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
957 Diag(Identifier, diag::err_pp_used_poisoned_id);
958 else
959 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
960 }
961
962 // If this is a macro to be expanded, do it.
963 if (MacroInfo *MI = II.getMacroInfo()) {
964 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
965 if (MI->isEnabled()) {
966 if (!HandleMacroExpandedIdentifier(Identifier, MI))
967 return;
968 } else {
969 // C99 6.10.3.4p2 says that a disabled macro may never again be
970 // expanded, even if it's in a context where it could be expanded in the
971 // future.
972 Identifier.setFlag(LexerToken::DisableExpand);
973 }
974 }
975 } else if (II.isOtherTargetMacro() && !DisableMacroExpansion) {
976 // If this identifier is a macro on some other target, emit a diagnostic.
977 // This diagnosic is only emitted when macro expansion is enabled, because
978 // the macro would not have been expanded for the other target either.
979 II.setIsOtherTargetMacro(false); // Don't warn on second use.
980 getTargetInfo().DiagnoseNonPortability(Identifier.getLocation(),
981 diag::port_target_macro_use);
982
983 }
984
985 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
986 // then we act as if it is the actual operator and not the textual
987 // representation of it.
988 if (II.isCPlusPlusOperatorKeyword())
989 Identifier.setIdentifierInfo(0);
990
991 // Change the kind of this identifier to the appropriate token kind, e.g.
992 // turning "for" into a keyword.
993 Identifier.setKind(II.getTokenID());
994
995 // If this is an extension token, diagnose its use.
996 // FIXME: tried (unsuccesfully) to shut this up when compiling with gnu99
997 // For now, I'm just commenting it out (while I work on attributes).
998 if (II.isExtensionToken() && Features.C99)
999 Diag(Identifier, diag::ext_token_used);
1000}
1001
1002/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
1003/// the current file. This either returns the EOF token or pops a level off
1004/// the include stack and keeps going.
1005bool Preprocessor::HandleEndOfFile(LexerToken &Result, bool isEndOfMacro) {
1006 assert(!CurMacroExpander &&
1007 "Ending a file when currently in a macro!");
1008
1009 // See if this file had a controlling macro.
1010 if (CurLexer) { // Not ending a macro, ignore it.
1011 if (const IdentifierInfo *ControllingMacro =
1012 CurLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
1013 // Okay, this has a controlling macro, remember in PerFileInfo.
1014 if (const FileEntry *FE =
1015 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1016 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
1017 }
1018 }
1019
1020 // If this is a #include'd file, pop it off the include stack and continue
1021 // lexing the #includer file.
1022 if (!IncludeMacroStack.empty()) {
1023 // We're done with the #included file.
1024 RemoveTopOfLexerStack();
1025
1026 // Notify the client, if desired, that we are in a new source file.
1027 if (Callbacks && !isEndOfMacro && CurLexer) {
1028 DirectoryLookup::DirType FileType = DirectoryLookup::NormalHeaderDir;
1029
1030 // Get the file entry for the current file.
1031 if (const FileEntry *FE =
1032 SourceMgr.getFileEntryForFileID(CurLexer->getCurFileID()))
1033 FileType = HeaderInfo.getFileDirFlavor(FE);
1034
1035 Callbacks->FileChanged(CurLexer->getSourceLocation(CurLexer->BufferPtr),
1036 PPCallbacks::ExitFile, FileType);
1037 }
1038
1039 // Client should lex another token.
1040 return false;
1041 }
1042
1043 Result.startToken();
1044 CurLexer->BufferPtr = CurLexer->BufferEnd;
1045 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd);
1046 Result.setKind(tok::eof);
1047
1048 // We're done with the #included file.
1049 delete CurLexer;
1050 CurLexer = 0;
1051
1052 // This is the end of the top-level file. If the diag::pp_macro_not_used
1053 // diagnostic is enabled, walk all of the identifiers, looking for macros that
1054 // have not been used.
1055 if (Diags.getDiagnosticLevel(diag::pp_macro_not_used) != Diagnostic::Ignored){
1056 for (IdentifierTable::iterator I = Identifiers.begin(),
1057 E = Identifiers.end(); I != E; ++I) {
1058 const IdentifierInfo &II = I->getValue();
1059 if (II.getMacroInfo() && !II.getMacroInfo()->isUsed())
1060 Diag(II.getMacroInfo()->getDefinitionLoc(), diag::pp_macro_not_used);
1061 }
1062 }
1063
1064 return true;
1065}
1066
1067/// HandleEndOfMacro - This callback is invoked when the lexer hits the end of
1068/// the current macro expansion or token stream expansion.
1069bool Preprocessor::HandleEndOfMacro(LexerToken &Result) {
1070 assert(CurMacroExpander && !CurLexer &&
1071 "Ending a macro when currently in a #include file!");
1072
Chris Lattner9594acf2007-07-15 00:25:26 +00001073 // Delete or cache the now-dead macro expander.
1074 if (NumCachedMacroExpanders == MacroExpanderCacheSize)
1075 delete CurMacroExpander;
1076 else
1077 MacroExpanderCache[NumCachedMacroExpanders++] = CurMacroExpander;
Reid Spencer5f016e22007-07-11 17:01:13 +00001078
1079 // Handle this like a #include file being popped off the stack.
1080 CurMacroExpander = 0;
1081 return HandleEndOfFile(Result, true);
1082}
1083
1084
1085//===----------------------------------------------------------------------===//
1086// Utility Methods for Preprocessor Directive Handling.
1087//===----------------------------------------------------------------------===//
1088
1089/// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
1090/// current line until the tok::eom token is found.
1091void Preprocessor::DiscardUntilEndOfDirective() {
1092 LexerToken Tmp;
1093 do {
1094 LexUnexpandedToken(Tmp);
1095 } while (Tmp.getKind() != tok::eom);
1096}
1097
1098/// isCXXNamedOperator - Returns "true" if the token is a named operator in C++.
1099static bool isCXXNamedOperator(const std::string &Spelling) {
1100 return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" ||
1101 Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" ||
1102 Spelling == "or" || Spelling == "xor";
1103}
1104
1105/// ReadMacroName - Lex and validate a macro name, which occurs after a
1106/// #define or #undef. This sets the token kind to eom and discards the rest
1107/// of the macro line if the macro name is invalid. isDefineUndef is 1 if
1108/// this is due to a a #define, 2 if #undef directive, 0 if it is something
1109/// else (e.g. #ifdef).
1110void Preprocessor::ReadMacroName(LexerToken &MacroNameTok, char isDefineUndef) {
1111 // Read the token, don't allow macro expansion on it.
1112 LexUnexpandedToken(MacroNameTok);
1113
1114 // Missing macro name?
1115 if (MacroNameTok.getKind() == tok::eom)
1116 return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
1117
1118 IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1119 if (II == 0) {
1120 std::string Spelling = getSpelling(MacroNameTok);
1121 if (isCXXNamedOperator(Spelling))
1122 // C++ 2.5p2: Alternative tokens behave the same as its primary token
1123 // except for their spellings.
1124 Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name, Spelling);
1125 else
1126 Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
1127 // Fall through on error.
1128 } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
1129 // Error if defining "defined": C99 6.10.8.4.
1130 Diag(MacroNameTok, diag::err_defined_macro_name);
1131 } else if (isDefineUndef && II->getMacroInfo() &&
1132 II->getMacroInfo()->isBuiltinMacro()) {
1133 // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
1134 if (isDefineUndef == 1)
1135 Diag(MacroNameTok, diag::pp_redef_builtin_macro);
1136 else
1137 Diag(MacroNameTok, diag::pp_undef_builtin_macro);
1138 } else {
1139 // Okay, we got a good identifier node. Return it.
1140 return;
1141 }
1142
1143 // Invalid macro name, read and discard the rest of the line. Then set the
1144 // token kind to tok::eom.
1145 MacroNameTok.setKind(tok::eom);
1146 return DiscardUntilEndOfDirective();
1147}
1148
1149/// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If
1150/// not, emit a diagnostic and consume up until the eom.
1151void Preprocessor::CheckEndOfDirective(const char *DirType) {
1152 LexerToken Tmp;
1153 Lex(Tmp);
1154 // There should be no tokens after the directive, but we allow them as an
1155 // extension.
1156 while (Tmp.getKind() == tok::comment) // Skip comments in -C mode.
1157 Lex(Tmp);
1158
1159 if (Tmp.getKind() != tok::eom) {
1160 Diag(Tmp, diag::ext_pp_extra_tokens_at_eol, DirType);
1161 DiscardUntilEndOfDirective();
1162 }
1163}
1164
1165
1166
1167/// SkipExcludedConditionalBlock - We just read a #if or related directive and
1168/// decided that the subsequent tokens are in the #if'd out portion of the
1169/// file. Lex the rest of the file, until we see an #endif. If
1170/// FoundNonSkipPortion is true, then we have already emitted code for part of
1171/// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
1172/// is true, then #else directives are ok, if not, then we have already seen one
1173/// so a #else directive is a duplicate. When this returns, the caller can lex
1174/// the first valid token.
1175void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
1176 bool FoundNonSkipPortion,
1177 bool FoundElse) {
1178 ++NumSkipped;
1179 assert(CurMacroExpander == 0 && CurLexer &&
1180 "Lexing a macro, not a file?");
1181
1182 CurLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
1183 FoundNonSkipPortion, FoundElse);
1184
1185 // Enter raw mode to disable identifier lookup (and thus macro expansion),
1186 // disabling warnings, etc.
1187 CurLexer->LexingRawMode = true;
1188 LexerToken Tok;
1189 while (1) {
1190 CurLexer->Lex(Tok);
1191
1192 // If this is the end of the buffer, we have an error.
1193 if (Tok.getKind() == tok::eof) {
1194 // Emit errors for each unterminated conditional on the stack, including
1195 // the current one.
1196 while (!CurLexer->ConditionalStack.empty()) {
1197 Diag(CurLexer->ConditionalStack.back().IfLoc,
1198 diag::err_pp_unterminated_conditional);
1199 CurLexer->ConditionalStack.pop_back();
1200 }
1201
1202 // Just return and let the caller lex after this #include.
1203 break;
1204 }
1205
1206 // If this token is not a preprocessor directive, just skip it.
1207 if (Tok.getKind() != tok::hash || !Tok.isAtStartOfLine())
1208 continue;
1209
1210 // We just parsed a # character at the start of a line, so we're in
1211 // directive mode. Tell the lexer this so any newlines we see will be
1212 // converted into an EOM token (this terminates the macro).
1213 CurLexer->ParsingPreprocessorDirective = true;
1214 CurLexer->KeepCommentMode = false;
1215
1216
1217 // Read the next token, the directive flavor.
1218 LexUnexpandedToken(Tok);
1219
1220 // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
1221 // something bogus), skip it.
1222 if (Tok.getKind() != tok::identifier) {
1223 CurLexer->ParsingPreprocessorDirective = false;
1224 // Restore comment saving mode.
1225 CurLexer->KeepCommentMode = KeepComments;
1226 continue;
1227 }
1228
1229 // If the first letter isn't i or e, it isn't intesting to us. We know that
1230 // this is safe in the face of spelling differences, because there is no way
1231 // to spell an i/e in a strange way that is another letter. Skipping this
1232 // allows us to avoid looking up the identifier info for #define/#undef and
1233 // other common directives.
1234 const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation());
1235 char FirstChar = RawCharData[0];
1236 if (FirstChar >= 'a' && FirstChar <= 'z' &&
1237 FirstChar != 'i' && FirstChar != 'e') {
1238 CurLexer->ParsingPreprocessorDirective = false;
1239 // Restore comment saving mode.
1240 CurLexer->KeepCommentMode = KeepComments;
1241 continue;
1242 }
1243
1244 // Get the identifier name without trigraphs or embedded newlines. Note
1245 // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
1246 // when skipping.
1247 // TODO: could do this with zero copies in the no-clean case by using
1248 // strncmp below.
1249 char Directive[20];
1250 unsigned IdLen;
1251 if (!Tok.needsCleaning() && Tok.getLength() < 20) {
1252 IdLen = Tok.getLength();
1253 memcpy(Directive, RawCharData, IdLen);
1254 Directive[IdLen] = 0;
1255 } else {
1256 std::string DirectiveStr = getSpelling(Tok);
1257 IdLen = DirectiveStr.size();
1258 if (IdLen >= 20) {
1259 CurLexer->ParsingPreprocessorDirective = false;
1260 // Restore comment saving mode.
1261 CurLexer->KeepCommentMode = KeepComments;
1262 continue;
1263 }
1264 memcpy(Directive, &DirectiveStr[0], IdLen);
1265 Directive[IdLen] = 0;
1266 }
1267
1268 if (FirstChar == 'i' && Directive[1] == 'f') {
1269 if ((IdLen == 2) || // "if"
1270 (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef"
1271 (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef"
1272 // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
1273 // bother parsing the condition.
1274 DiscardUntilEndOfDirective();
1275 CurLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
1276 /*foundnonskip*/false,
1277 /*fnddelse*/false);
1278 }
1279 } else if (FirstChar == 'e') {
1280 if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif"
1281 CheckEndOfDirective("#endif");
1282 PPConditionalInfo CondInfo;
1283 CondInfo.WasSkipping = true; // Silence bogus warning.
1284 bool InCond = CurLexer->popConditionalLevel(CondInfo);
1285 InCond = InCond; // Silence warning in no-asserts mode.
1286 assert(!InCond && "Can't be skipping if not in a conditional!");
1287
1288 // If we popped the outermost skipping block, we're done skipping!
1289 if (!CondInfo.WasSkipping)
1290 break;
1291 } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else".
1292 // #else directive in a skipping conditional. If not in some other
1293 // skipping conditional, and if #else hasn't already been seen, enter it
1294 // as a non-skipping conditional.
1295 CheckEndOfDirective("#else");
1296 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1297
1298 // If this is a #else with a #else before it, report the error.
1299 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
1300
1301 // Note that we've seen a #else in this conditional.
1302 CondInfo.FoundElse = true;
1303
1304 // If the conditional is at the top level, and the #if block wasn't
1305 // entered, enter the #else block now.
1306 if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
1307 CondInfo.FoundNonSkip = true;
1308 break;
1309 }
1310 } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif".
1311 PPConditionalInfo &CondInfo = CurLexer->peekConditionalLevel();
1312
1313 bool ShouldEnter;
1314 // If this is in a skipping block or if we're already handled this #if
1315 // block, don't bother parsing the condition.
1316 if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
1317 DiscardUntilEndOfDirective();
1318 ShouldEnter = false;
1319 } else {
1320 // Restore the value of LexingRawMode so that identifiers are
1321 // looked up, etc, inside the #elif expression.
1322 assert(CurLexer->LexingRawMode && "We have to be skipping here!");
1323 CurLexer->LexingRawMode = false;
1324 IdentifierInfo *IfNDefMacro = 0;
1325 ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
1326 CurLexer->LexingRawMode = true;
1327 }
1328
1329 // If this is a #elif with a #else before it, report the error.
1330 if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
1331
1332 // If this condition is true, enter it!
1333 if (ShouldEnter) {
1334 CondInfo.FoundNonSkip = true;
1335 break;
1336 }
1337 }
1338 }
1339
1340 CurLexer->ParsingPreprocessorDirective = false;
1341 // Restore comment saving mode.
1342 CurLexer->KeepCommentMode = KeepComments;
1343 }
1344
1345 // Finally, if we are out of the conditional (saw an #endif or ran off the end
1346 // of the file, just stop skipping and return to lexing whatever came after
1347 // the #if block.
1348 CurLexer->LexingRawMode = false;
1349}
1350
1351//===----------------------------------------------------------------------===//
1352// Preprocessor Directive Handling.
1353//===----------------------------------------------------------------------===//
1354
1355/// HandleDirective - This callback is invoked when the lexer sees a # token
1356/// at the start of a line. This consumes the directive, modifies the
1357/// lexer/preprocessor state, and advances the lexer(s) so that the next token
1358/// read is the correct one.
1359void Preprocessor::HandleDirective(LexerToken &Result) {
1360 // FIXME: Traditional: # with whitespace before it not recognized by K&R?
1361
1362 // We just parsed a # character at the start of a line, so we're in directive
1363 // mode. Tell the lexer this so any newlines we see will be converted into an
1364 // EOM token (which terminates the directive).
1365 CurLexer->ParsingPreprocessorDirective = true;
1366
1367 ++NumDirectives;
1368
1369 // We are about to read a token. For the multiple-include optimization FA to
1370 // work, we have to remember if we had read any tokens *before* this
1371 // pp-directive.
1372 bool ReadAnyTokensBeforeDirective = CurLexer->MIOpt.getHasReadAnyTokensVal();
1373
1374 // Read the next token, the directive flavor. This isn't expanded due to
1375 // C99 6.10.3p8.
1376 LexUnexpandedToken(Result);
1377
1378 // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
1379 // #define A(x) #x
1380 // A(abc
1381 // #warning blah
1382 // def)
1383 // If so, the user is relying on non-portable behavior, emit a diagnostic.
1384 if (InMacroArgs)
1385 Diag(Result, diag::ext_embedded_directive);
1386
1387TryAgain:
1388 switch (Result.getKind()) {
1389 case tok::eom:
1390 return; // null directive.
1391 case tok::comment:
1392 // Handle stuff like "# /*foo*/ define X" in -E -C mode.
1393 LexUnexpandedToken(Result);
1394 goto TryAgain;
1395
1396 case tok::numeric_constant:
1397 // FIXME: implement # 7 line numbers!
1398 DiscardUntilEndOfDirective();
1399 return;
1400 default:
1401 IdentifierInfo *II = Result.getIdentifierInfo();
1402 if (II == 0) break; // Not an identifier.
1403
1404 // Ask what the preprocessor keyword ID is.
1405 switch (II->getPPKeywordID()) {
1406 default: break;
1407 // C99 6.10.1 - Conditional Inclusion.
1408 case tok::pp_if:
1409 return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
1410 case tok::pp_ifdef:
1411 return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
1412 case tok::pp_ifndef:
1413 return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
1414 case tok::pp_elif:
1415 return HandleElifDirective(Result);
1416 case tok::pp_else:
1417 return HandleElseDirective(Result);
1418 case tok::pp_endif:
1419 return HandleEndifDirective(Result);
1420
1421 // C99 6.10.2 - Source File Inclusion.
1422 case tok::pp_include:
1423 return HandleIncludeDirective(Result); // Handle #include.
1424
1425 // C99 6.10.3 - Macro Replacement.
1426 case tok::pp_define:
1427 return HandleDefineDirective(Result, false);
1428 case tok::pp_undef:
1429 return HandleUndefDirective(Result);
1430
1431 // C99 6.10.4 - Line Control.
1432 case tok::pp_line:
1433 // FIXME: implement #line
1434 DiscardUntilEndOfDirective();
1435 return;
1436
1437 // C99 6.10.5 - Error Directive.
1438 case tok::pp_error:
1439 return HandleUserDiagnosticDirective(Result, false);
1440
1441 // C99 6.10.6 - Pragma Directive.
1442 case tok::pp_pragma:
1443 return HandlePragmaDirective();
1444
1445 // GNU Extensions.
1446 case tok::pp_import:
1447 return HandleImportDirective(Result);
1448 case tok::pp_include_next:
1449 return HandleIncludeNextDirective(Result);
1450
1451 case tok::pp_warning:
1452 Diag(Result, diag::ext_pp_warning_directive);
1453 return HandleUserDiagnosticDirective(Result, true);
1454 case tok::pp_ident:
1455 return HandleIdentSCCSDirective(Result);
1456 case tok::pp_sccs:
1457 return HandleIdentSCCSDirective(Result);
1458 case tok::pp_assert:
1459 //isExtension = true; // FIXME: implement #assert
1460 break;
1461 case tok::pp_unassert:
1462 //isExtension = true; // FIXME: implement #unassert
1463 break;
1464
1465 // clang extensions.
1466 case tok::pp_define_target:
1467 return HandleDefineDirective(Result, true);
1468 case tok::pp_define_other_target:
1469 return HandleDefineOtherTargetDirective(Result);
1470 }
1471 break;
1472 }
1473
1474 // If we reached here, the preprocessing token is not valid!
1475 Diag(Result, diag::err_pp_invalid_directive);
1476
1477 // Read the rest of the PP line.
1478 DiscardUntilEndOfDirective();
1479
1480 // Okay, we're done parsing the directive.
1481}
1482
1483void Preprocessor::HandleUserDiagnosticDirective(LexerToken &Tok,
1484 bool isWarning) {
1485 // Read the rest of the line raw. We do this because we don't want macros
1486 // to be expanded and we don't require that the tokens be valid preprocessing
1487 // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
1488 // collapse multiple consequtive white space between tokens, but this isn't
1489 // specified by the standard.
1490 std::string Message = CurLexer->ReadToEndOfLine();
1491
1492 unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error;
1493 return Diag(Tok, DiagID, Message);
1494}
1495
1496/// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1497///
1498void Preprocessor::HandleIdentSCCSDirective(LexerToken &Tok) {
1499 // Yes, this directive is an extension.
1500 Diag(Tok, diag::ext_pp_ident_directive);
1501
1502 // Read the string argument.
1503 LexerToken StrTok;
1504 Lex(StrTok);
1505
1506 // If the token kind isn't a string, it's a malformed directive.
1507 if (StrTok.getKind() != tok::string_literal &&
1508 StrTok.getKind() != tok::wide_string_literal)
1509 return Diag(StrTok, diag::err_pp_malformed_ident);
1510
1511 // Verify that there is nothing after the string, other than EOM.
1512 CheckEndOfDirective("#ident");
1513
1514 if (Callbacks)
1515 Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok));
1516}
1517
1518//===----------------------------------------------------------------------===//
1519// Preprocessor Include Directive Handling.
1520//===----------------------------------------------------------------------===//
1521
1522/// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1523/// checked and spelled filename, e.g. as an operand of #include. This returns
1524/// true if the input filename was in <>'s or false if it were in ""'s. The
1525/// caller is expected to provide a buffer that is large enough to hold the
1526/// spelling of the filename, but is also expected to handle the case when
1527/// this method decides to use a different buffer.
1528bool Preprocessor::GetIncludeFilenameSpelling(const LexerToken &FilenameTok,
1529 const char *&BufStart,
1530 const char *&BufEnd) {
1531 // Get the text form of the filename.
1532 unsigned Len = getSpelling(FilenameTok, BufStart);
1533 BufEnd = BufStart+Len;
1534 assert(BufStart != BufEnd && "Can't have tokens with empty spellings!");
1535
1536 // Make sure the filename is <x> or "x".
1537 bool isAngled;
1538 if (BufStart[0] == '<') {
1539 if (BufEnd[-1] != '>') {
1540 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1541 BufStart = 0;
1542 return true;
1543 }
1544 isAngled = true;
1545 } else if (BufStart[0] == '"') {
1546 if (BufEnd[-1] != '"') {
1547 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1548 BufStart = 0;
1549 return true;
1550 }
1551 isAngled = false;
1552 } else {
1553 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1554 BufStart = 0;
1555 return true;
1556 }
1557
1558 // Diagnose #include "" as invalid.
1559 if (BufEnd-BufStart <= 2) {
1560 Diag(FilenameTok.getLocation(), diag::err_pp_empty_filename);
1561 BufStart = 0;
1562 return "";
1563 }
1564
1565 // Skip the brackets.
1566 ++BufStart;
1567 --BufEnd;
1568 return isAngled;
1569}
1570
1571/// HandleIncludeDirective - The "#include" tokens have just been read, read the
1572/// file to be included from the lexer, then include it! This is a common
1573/// routine with functionality shared between #include, #include_next and
1574/// #import.
1575void Preprocessor::HandleIncludeDirective(LexerToken &IncludeTok,
1576 const DirectoryLookup *LookupFrom,
1577 bool isImport) {
1578
1579 LexerToken FilenameTok;
1580 CurLexer->LexIncludeFilename(FilenameTok);
1581
1582 // If the token kind is EOM, the error has already been diagnosed.
1583 if (FilenameTok.getKind() == tok::eom)
1584 return;
1585
1586 // Reserve a buffer to get the spelling.
1587 llvm::SmallVector<char, 128> FilenameBuffer;
1588 FilenameBuffer.resize(FilenameTok.getLength());
1589
1590 const char *FilenameStart = &FilenameBuffer[0], *FilenameEnd;
1591 bool isAngled = GetIncludeFilenameSpelling(FilenameTok,
1592 FilenameStart, FilenameEnd);
1593 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1594 // error.
1595 if (FilenameStart == 0)
1596 return;
1597
1598 // Verify that there is nothing after the filename, other than EOM. Use the
1599 // preprocessor to lex this in case lexing the filename entered a macro.
1600 CheckEndOfDirective("#include");
1601
1602 // Check that we don't have infinite #include recursion.
1603 if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1)
1604 return Diag(FilenameTok, diag::err_pp_include_too_deep);
1605
1606 // Search include directories.
1607 const DirectoryLookup *CurDir;
1608 const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
1609 isAngled, LookupFrom, CurDir);
1610 if (File == 0)
1611 return Diag(FilenameTok, diag::err_pp_file_not_found,
1612 std::string(FilenameStart, FilenameEnd));
1613
1614 // Ask HeaderInfo if we should enter this #include file.
1615 if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
1616 // If it returns true, #including this file will have no effect.
1617 return;
1618 }
1619
1620 // Look up the file, create a File ID for it.
1621 unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation());
1622 if (FileID == 0)
1623 return Diag(FilenameTok, diag::err_pp_file_not_found,
1624 std::string(FilenameStart, FilenameEnd));
1625
1626 // Finally, if all is good, enter the new file!
1627 EnterSourceFile(FileID, CurDir);
1628}
1629
1630/// HandleIncludeNextDirective - Implements #include_next.
1631///
1632void Preprocessor::HandleIncludeNextDirective(LexerToken &IncludeNextTok) {
1633 Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
1634
1635 // #include_next is like #include, except that we start searching after
1636 // the current found directory. If we can't do this, issue a
1637 // diagnostic.
1638 const DirectoryLookup *Lookup = CurDirLookup;
1639 if (isInPrimaryFile()) {
1640 Lookup = 0;
1641 Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1642 } else if (Lookup == 0) {
1643 Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1644 } else {
1645 // Start looking up in the next directory.
1646 ++Lookup;
1647 }
1648
1649 return HandleIncludeDirective(IncludeNextTok, Lookup);
1650}
1651
1652/// HandleImportDirective - Implements #import.
1653///
1654void Preprocessor::HandleImportDirective(LexerToken &ImportTok) {
1655 Diag(ImportTok, diag::ext_pp_import_directive);
1656
1657 return HandleIncludeDirective(ImportTok, 0, true);
1658}
1659
1660//===----------------------------------------------------------------------===//
1661// Preprocessor Macro Directive Handling.
1662//===----------------------------------------------------------------------===//
1663
1664/// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
1665/// definition has just been read. Lex the rest of the arguments and the
1666/// closing ), updating MI with what we learn. Return true if an error occurs
1667/// parsing the arg list.
1668bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
Chris Lattner25c96482007-07-14 22:46:43 +00001669 llvm::SmallVector<IdentifierInfo*, 32> Arguments;
1670
Reid Spencer5f016e22007-07-11 17:01:13 +00001671 LexerToken Tok;
1672 while (1) {
1673 LexUnexpandedToken(Tok);
1674 switch (Tok.getKind()) {
1675 case tok::r_paren:
1676 // Found the end of the argument list.
Chris Lattner25c96482007-07-14 22:46:43 +00001677 if (Arguments.empty()) { // #define FOO()
1678 MI->setArgumentList(Arguments.begin(), Arguments.end());
1679 return false;
1680 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001681 // Otherwise we have #define FOO(A,)
1682 Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
1683 return true;
1684 case tok::ellipsis: // #define X(... -> C99 varargs
1685 // Warn if use of C99 feature in non-C99 mode.
1686 if (!Features.C99) Diag(Tok, diag::ext_variadic_macro);
1687
1688 // Lex the token after the identifier.
1689 LexUnexpandedToken(Tok);
1690 if (Tok.getKind() != tok::r_paren) {
1691 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1692 return true;
1693 }
1694 // Add the __VA_ARGS__ identifier as an argument.
Chris Lattner25c96482007-07-14 22:46:43 +00001695 Arguments.push_back(Ident__VA_ARGS__);
Reid Spencer5f016e22007-07-11 17:01:13 +00001696 MI->setIsC99Varargs();
Chris Lattner25c96482007-07-14 22:46:43 +00001697 MI->setArgumentList(Arguments.begin(), Arguments.end());
Reid Spencer5f016e22007-07-11 17:01:13 +00001698 return false;
1699 case tok::eom: // #define X(
1700 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1701 return true;
1702 default:
1703 // Handle keywords and identifiers here to accept things like
1704 // #define Foo(for) for.
1705 IdentifierInfo *II = Tok.getIdentifierInfo();
1706 if (II == 0) {
1707 // #define X(1
1708 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
1709 return true;
1710 }
1711
1712 // If this is already used as an argument, it is used multiple times (e.g.
1713 // #define X(A,A.
Chris Lattner25c96482007-07-14 22:46:43 +00001714 if (std::find(Arguments.begin(), Arguments.end(), II) !=
1715 Arguments.end()) { // C99 6.10.3p6
Reid Spencer5f016e22007-07-11 17:01:13 +00001716 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list, II->getName());
1717 return true;
1718 }
1719
1720 // Add the argument to the macro info.
Chris Lattner25c96482007-07-14 22:46:43 +00001721 Arguments.push_back(II);
Reid Spencer5f016e22007-07-11 17:01:13 +00001722
1723 // Lex the token after the identifier.
1724 LexUnexpandedToken(Tok);
1725
1726 switch (Tok.getKind()) {
1727 default: // #define X(A B
1728 Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
1729 return true;
1730 case tok::r_paren: // #define X(A)
Chris Lattner25c96482007-07-14 22:46:43 +00001731 MI->setArgumentList(Arguments.begin(), Arguments.end());
Reid Spencer5f016e22007-07-11 17:01:13 +00001732 return false;
1733 case tok::comma: // #define X(A,
1734 break;
1735 case tok::ellipsis: // #define X(A... -> GCC extension
1736 // Diagnose extension.
1737 Diag(Tok, diag::ext_named_variadic_macro);
1738
1739 // Lex the token after the identifier.
1740 LexUnexpandedToken(Tok);
1741 if (Tok.getKind() != tok::r_paren) {
1742 Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
1743 return true;
1744 }
1745
1746 MI->setIsGNUVarargs();
Chris Lattner25c96482007-07-14 22:46:43 +00001747 MI->setArgumentList(Arguments.begin(), Arguments.end());
Reid Spencer5f016e22007-07-11 17:01:13 +00001748 return false;
1749 }
1750 }
1751 }
1752}
1753
1754/// HandleDefineDirective - Implements #define. This consumes the entire macro
1755/// line then lets the caller lex the next real token. If 'isTargetSpecific' is
1756/// true, then this is a "#define_target", otherwise this is a "#define".
1757///
1758void Preprocessor::HandleDefineDirective(LexerToken &DefineTok,
1759 bool isTargetSpecific) {
1760 ++NumDefined;
1761
1762 LexerToken MacroNameTok;
1763 ReadMacroName(MacroNameTok, 1);
1764
1765 // Error reading macro name? If so, diagnostic already issued.
1766 if (MacroNameTok.getKind() == tok::eom)
1767 return;
Chris Lattnerc215bd62007-07-14 22:11:41 +00001768
Reid Spencer5f016e22007-07-11 17:01:13 +00001769 // If we are supposed to keep comments in #defines, reenable comment saving
1770 // mode.
1771 CurLexer->KeepCommentMode = KeepMacroComments;
1772
1773 // Create the new macro.
1774 MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation());
1775 if (isTargetSpecific) MI->setIsTargetSpecific();
1776
1777 // If the identifier is an 'other target' macro, clear this bit.
1778 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1779
1780
1781 LexerToken Tok;
1782 LexUnexpandedToken(Tok);
1783
1784 // If this is a function-like macro definition, parse the argument list,
1785 // marking each of the identifiers as being used as macro arguments. Also,
1786 // check other constraints on the first token of the macro body.
1787 if (Tok.getKind() == tok::eom) {
1788 // If there is no body to this macro, we have no special handling here.
1789 } else if (Tok.getKind() == tok::l_paren && !Tok.hasLeadingSpace()) {
1790 // This is a function-like macro definition. Read the argument list.
1791 MI->setIsFunctionLike();
1792 if (ReadMacroDefinitionArgList(MI)) {
1793 // Forget about MI.
1794 delete MI;
1795 // Throw away the rest of the line.
1796 if (CurLexer->ParsingPreprocessorDirective)
1797 DiscardUntilEndOfDirective();
1798 return;
1799 }
1800
1801 // Read the first token after the arg list for down below.
1802 LexUnexpandedToken(Tok);
1803 } else if (!Tok.hasLeadingSpace()) {
1804 // C99 requires whitespace between the macro definition and the body. Emit
1805 // a diagnostic for something like "#define X+".
1806 if (Features.C99) {
1807 Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
1808 } else {
1809 // FIXME: C90/C++ do not get this diagnostic, but it does get a similar
1810 // one in some cases!
1811 }
1812 } else {
1813 // This is a normal token with leading space. Clear the leading space
1814 // marker on the first token to get proper expansion.
1815 Tok.clearFlag(LexerToken::LeadingSpace);
1816 }
1817
1818 // If this is a definition of a variadic C99 function-like macro, not using
1819 // the GNU named varargs extension, enabled __VA_ARGS__.
1820
1821 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
1822 // This gets unpoisoned where it is allowed.
1823 assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
1824 if (MI->isC99Varargs())
1825 Ident__VA_ARGS__->setIsPoisoned(false);
1826
1827 // Read the rest of the macro body.
Chris Lattnerb5e240f2007-07-14 21:54:03 +00001828 if (MI->isObjectLike()) {
1829 // Object-like macros are very simple, just read their body.
1830 while (Tok.getKind() != tok::eom) {
1831 MI->AddTokenToBody(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +00001832 // Get the next token of the macro.
1833 LexUnexpandedToken(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +00001834 }
1835
Chris Lattnerb5e240f2007-07-14 21:54:03 +00001836 } else {
1837 // Otherwise, read the body of a function-like macro. This has to validate
1838 // the # (stringize) operator.
1839 while (Tok.getKind() != tok::eom) {
1840 MI->AddTokenToBody(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +00001841
Chris Lattnerb5e240f2007-07-14 21:54:03 +00001842 // Check C99 6.10.3.2p1: ensure that # operators are followed by macro
1843 // parameters in function-like macro expansions.
1844 if (Tok.getKind() != tok::hash) {
1845 // Get the next token of the macro.
1846 LexUnexpandedToken(Tok);
1847 continue;
1848 }
1849
1850 // Get the next token of the macro.
1851 LexUnexpandedToken(Tok);
1852
1853 // Not a macro arg identifier?
1854 if (!Tok.getIdentifierInfo() ||
1855 MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
1856 Diag(Tok, diag::err_pp_stringize_not_parameter);
1857 delete MI;
1858
1859 // Disable __VA_ARGS__ again.
1860 Ident__VA_ARGS__->setIsPoisoned(true);
1861 return;
1862 }
1863
1864 // Things look ok, add the param name token to the macro.
1865 MI->AddTokenToBody(Tok);
1866
1867 // Get the next token of the macro.
1868 LexUnexpandedToken(Tok);
1869 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001870 }
1871
Chris Lattnerc215bd62007-07-14 22:11:41 +00001872
Reid Spencer5f016e22007-07-11 17:01:13 +00001873 // Disable __VA_ARGS__ again.
1874 Ident__VA_ARGS__->setIsPoisoned(true);
1875
1876 // Check that there is no paste (##) operator at the begining or end of the
1877 // replacement list.
1878 unsigned NumTokens = MI->getNumTokens();
1879 if (NumTokens != 0) {
1880 if (MI->getReplacementToken(0).getKind() == tok::hashhash) {
1881 Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
1882 delete MI;
1883 return;
1884 }
1885 if (MI->getReplacementToken(NumTokens-1).getKind() == tok::hashhash) {
1886 Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
1887 delete MI;
1888 return;
1889 }
1890 }
1891
1892 // If this is the primary source file, remember that this macro hasn't been
1893 // used yet.
1894 if (isInPrimaryFile())
1895 MI->setIsUsed(false);
1896
1897 // Finally, if this identifier already had a macro defined for it, verify that
1898 // the macro bodies are identical and free the old definition.
1899 if (MacroInfo *OtherMI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
1900 if (!OtherMI->isUsed())
1901 Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
1902
1903 // Macros must be identical. This means all tokes and whitespace separation
1904 // must be the same. C99 6.10.3.2.
1905 if (!MI->isIdenticalTo(*OtherMI, *this)) {
1906 Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef,
1907 MacroNameTok.getIdentifierInfo()->getName());
1908 Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2);
1909 }
1910 delete OtherMI;
1911 }
1912
1913 MacroNameTok.getIdentifierInfo()->setMacroInfo(MI);
1914}
1915
1916/// HandleDefineOtherTargetDirective - Implements #define_other_target.
1917void Preprocessor::HandleDefineOtherTargetDirective(LexerToken &Tok) {
1918 LexerToken MacroNameTok;
1919 ReadMacroName(MacroNameTok, 1);
1920
1921 // Error reading macro name? If so, diagnostic already issued.
1922 if (MacroNameTok.getKind() == tok::eom)
1923 return;
1924
1925 // Check to see if this is the last token on the #undef line.
1926 CheckEndOfDirective("#define_other_target");
1927
1928 // If there is already a macro defined by this name, turn it into a
1929 // target-specific define.
1930 if (MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo()) {
1931 MI->setIsTargetSpecific(true);
1932 return;
1933 }
1934
1935 // Mark the identifier as being a macro on some other target.
1936 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro();
1937}
1938
1939
1940/// HandleUndefDirective - Implements #undef.
1941///
1942void Preprocessor::HandleUndefDirective(LexerToken &UndefTok) {
1943 ++NumUndefined;
1944
1945 LexerToken MacroNameTok;
1946 ReadMacroName(MacroNameTok, 2);
1947
1948 // Error reading macro name? If so, diagnostic already issued.
1949 if (MacroNameTok.getKind() == tok::eom)
1950 return;
1951
1952 // Check to see if this is the last token on the #undef line.
1953 CheckEndOfDirective("#undef");
1954
1955 // Okay, we finally have a valid identifier to undef.
1956 MacroInfo *MI = MacroNameTok.getIdentifierInfo()->getMacroInfo();
1957
1958 // #undef untaints an identifier if it were marked by define_other_target.
1959 MacroNameTok.getIdentifierInfo()->setIsOtherTargetMacro(false);
1960
1961 // If the macro is not defined, this is a noop undef, just return.
1962 if (MI == 0) return;
1963
1964 if (!MI->isUsed())
1965 Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
1966
1967 // Free macro definition.
1968 delete MI;
1969 MacroNameTok.getIdentifierInfo()->setMacroInfo(0);
1970}
1971
1972
1973//===----------------------------------------------------------------------===//
1974// Preprocessor Conditional Directive Handling.
1975//===----------------------------------------------------------------------===//
1976
1977/// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
1978/// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
1979/// if any tokens have been returned or pp-directives activated before this
1980/// #ifndef has been lexed.
1981///
1982void Preprocessor::HandleIfdefDirective(LexerToken &Result, bool isIfndef,
1983 bool ReadAnyTokensBeforeDirective) {
1984 ++NumIf;
1985 LexerToken DirectiveTok = Result;
1986
1987 LexerToken MacroNameTok;
1988 ReadMacroName(MacroNameTok);
1989
1990 // Error reading macro name? If so, diagnostic already issued.
1991 if (MacroNameTok.getKind() == tok::eom)
1992 return;
1993
1994 // Check to see if this is the last token on the #if[n]def line.
1995 CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef");
1996
1997 // If the start of a top-level #ifdef, inform MIOpt.
1998 if (!ReadAnyTokensBeforeDirective &&
1999 CurLexer->getConditionalStackDepth() == 0) {
2000 assert(isIfndef && "#ifdef shouldn't reach here");
2001 CurLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo());
2002 }
2003
2004 IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
2005 MacroInfo *MI = MII->getMacroInfo();
2006
2007 // If there is a macro, process it.
2008 if (MI) {
2009 // Mark it used.
2010 MI->setIsUsed(true);
2011
2012 // If this is the first use of a target-specific macro, warn about it.
2013 if (MI->isTargetSpecific()) {
2014 MI->setIsTargetSpecific(false); // Don't warn on second use.
2015 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2016 diag::port_target_macro_use);
2017 }
2018 } else {
2019 // Use of a target-specific macro for some other target? If so, warn.
2020 if (MII->isOtherTargetMacro()) {
2021 MII->setIsOtherTargetMacro(false); // Don't warn on second use.
2022 getTargetInfo().DiagnoseNonPortability(MacroNameTok.getLocation(),
2023 diag::port_target_macro_use);
2024 }
2025 }
2026
2027 // Should we include the stuff contained by this directive?
2028 if (!MI == isIfndef) {
2029 // Yes, remember that we are inside a conditional, then lex the next token.
2030 CurLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false,
2031 /*foundnonskip*/true, /*foundelse*/false);
2032 } else {
2033 // No, skip the contents of this block and return the first token after it.
2034 SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
2035 /*Foundnonskip*/false,
2036 /*FoundElse*/false);
2037 }
2038}
2039
2040/// HandleIfDirective - Implements the #if directive.
2041///
2042void Preprocessor::HandleIfDirective(LexerToken &IfToken,
2043 bool ReadAnyTokensBeforeDirective) {
2044 ++NumIf;
2045
2046 // Parse and evaluation the conditional expression.
2047 IdentifierInfo *IfNDefMacro = 0;
2048 bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
2049
2050 // Should we include the stuff contained by this directive?
2051 if (ConditionalTrue) {
2052 // If this condition is equivalent to #ifndef X, and if this is the first
2053 // directive seen, handle it for the multiple-include optimization.
2054 if (!ReadAnyTokensBeforeDirective &&
2055 CurLexer->getConditionalStackDepth() == 0 && IfNDefMacro)
2056 CurLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
2057
2058 // Yes, remember that we are inside a conditional, then lex the next token.
2059 CurLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
2060 /*foundnonskip*/true, /*foundelse*/false);
2061 } else {
2062 // No, skip the contents of this block and return the first token after it.
2063 SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
2064 /*FoundElse*/false);
2065 }
2066}
2067
2068/// HandleEndifDirective - Implements the #endif directive.
2069///
2070void Preprocessor::HandleEndifDirective(LexerToken &EndifToken) {
2071 ++NumEndif;
2072
2073 // Check that this is the whole directive.
2074 CheckEndOfDirective("#endif");
2075
2076 PPConditionalInfo CondInfo;
2077 if (CurLexer->popConditionalLevel(CondInfo)) {
2078 // No conditionals on the stack: this is an #endif without an #if.
2079 return Diag(EndifToken, diag::err_pp_endif_without_if);
2080 }
2081
2082 // If this the end of a top-level #endif, inform MIOpt.
2083 if (CurLexer->getConditionalStackDepth() == 0)
2084 CurLexer->MIOpt.ExitTopLevelConditional();
2085
2086 assert(!CondInfo.WasSkipping && !CurLexer->LexingRawMode &&
2087 "This code should only be reachable in the non-skipping case!");
2088}
2089
2090
2091void Preprocessor::HandleElseDirective(LexerToken &Result) {
2092 ++NumElse;
2093
2094 // #else directive in a non-skipping conditional... start skipping.
2095 CheckEndOfDirective("#else");
2096
2097 PPConditionalInfo CI;
2098 if (CurLexer->popConditionalLevel(CI))
2099 return Diag(Result, diag::pp_err_else_without_if);
2100
2101 // If this is a top-level #else, inform the MIOpt.
2102 if (CurLexer->getConditionalStackDepth() == 0)
2103 CurLexer->MIOpt.FoundTopLevelElse();
2104
2105 // If this is a #else with a #else before it, report the error.
2106 if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
2107
2108 // Finally, skip the rest of the contents of this block and return the first
2109 // token after it.
2110 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2111 /*FoundElse*/true);
2112}
2113
2114void Preprocessor::HandleElifDirective(LexerToken &ElifToken) {
2115 ++NumElse;
2116
2117 // #elif directive in a non-skipping conditional... start skipping.
2118 // We don't care what the condition is, because we will always skip it (since
2119 // the block immediately before it was included).
2120 DiscardUntilEndOfDirective();
2121
2122 PPConditionalInfo CI;
2123 if (CurLexer->popConditionalLevel(CI))
2124 return Diag(ElifToken, diag::pp_err_elif_without_if);
2125
2126 // If this is a top-level #elif, inform the MIOpt.
2127 if (CurLexer->getConditionalStackDepth() == 0)
2128 CurLexer->MIOpt.FoundTopLevelElse();
2129
2130 // If this is a #elif with a #else before it, report the error.
2131 if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
2132
2133 // Finally, skip the rest of the contents of this block and return the first
2134 // token after it.
2135 return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
2136 /*FoundElse*/CI.FoundElse);
2137}
2138