1 //===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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[DNI] - 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/Pragma.h"
32 #include "clang/Lex/ScratchBuffer.h"
33 #include "clang/Lex/LexDiagnostic.h"
34 #include "clang/Basic/SourceManager.h"
35 #include "clang/Basic/FileManager.h"
36 #include "clang/Basic/TargetInfo.h"
37 #include "llvm/ADT/APFloat.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include <cstdio>
42 using namespace clang;
43 
44 //===----------------------------------------------------------------------===//
45 
46 Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
47                            const TargetInfo &target, SourceManager &SM,
48                            HeaderSearch &Headers,
49                            IdentifierInfoLookup* IILookup,
50                            bool OwnsHeaders)
51   : Diags(&diags), Features(opts), Target(target),FileMgr(Headers.getFileMgr()),
52     SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts, IILookup),
53     BuiltinInfo(Target), CodeCompletionFile(0), CurPPLexer(0), CurDirLookup(0),
54     Callbacks(0) {
55   ScratchBuf = new ScratchBuffer(SourceMgr);
56   CounterValue = 0; // __COUNTER__ starts at 0.
57   OwnsHeaderSearch = OwnsHeaders;
58 
59   // Clear stats.
60   NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
61   NumIf = NumElse = NumEndif = 0;
62   NumEnteredSourceFiles = 0;
63   NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
64   NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
65   MaxIncludeStackDepth = 0;
66   NumSkipped = 0;
67 
68   // Default to discarding comments.
69   KeepComments = false;
70   KeepMacroComments = false;
71 
72   // Macro expansion is enabled.
73   DisableMacroExpansion = false;
74   InMacroArgs = false;
75   NumCachedTokenLexers = 0;
76 
77   CachedLexPos = 0;
78 
79   // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
80   // This gets unpoisoned where it is allowed.
81   (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
82 
83   // Initialize the pragma handlers.
84   PragmaHandlers = new PragmaNamespace(0);
85   RegisterBuiltinPragmas();
86 
87   // Initialize builtin macros like __LINE__ and friends.
88   RegisterBuiltinMacros();
89 }
90 
91 Preprocessor::~Preprocessor() {
92   assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
93 
94   while (!IncludeMacroStack.empty()) {
95     delete IncludeMacroStack.back().TheLexer;
96     delete IncludeMacroStack.back().TheTokenLexer;
97     IncludeMacroStack.pop_back();
98   }
99 
100   // Free any macro definitions.
101   for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
102        Macros.begin(), E = Macros.end(); I != E; ++I) {
103     // We don't need to free the MacroInfo objects directly.  These
104     // will be released when the BumpPtrAllocator 'BP' object gets
105     // destroyed. We still need to run the dstor, however, to free
106     // memory alocated by MacroInfo.
107     I->second->Destroy(BP);
108     I->first->setHasMacroDefinition(false);
109   }
110 
111   // Free any cached macro expanders.
112   for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
113     delete TokenLexerCache[i];
114 
115   // Release pragma information.
116   delete PragmaHandlers;
117 
118   // Delete the scratch buffer info.
119   delete ScratchBuf;
120 
121   // Delete the header search info, if we own it.
122   if (OwnsHeaderSearch)
123     delete &HeaderInfo;
124 
125   delete Callbacks;
126 }
127 
128 void Preprocessor::setPTHManager(PTHManager* pm) {
129   PTH.reset(pm);
130   FileMgr.addStatCache(PTH->createStatCache());
131 }
132 
133 void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
134   llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
135                << getSpelling(Tok) << "'";
136 
137   if (!DumpFlags) return;
138 
139   llvm::errs() << "\t";
140   if (Tok.isAtStartOfLine())
141     llvm::errs() << " [StartOfLine]";
142   if (Tok.hasLeadingSpace())
143     llvm::errs() << " [LeadingSpace]";
144   if (Tok.isExpandDisabled())
145     llvm::errs() << " [ExpandDisabled]";
146   if (Tok.needsCleaning()) {
147     const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
148     llvm::errs() << " [UnClean='" << std::string(Start, Start+Tok.getLength())
149                  << "']";
150   }
151 
152   llvm::errs() << "\tLoc=<";
153   DumpLocation(Tok.getLocation());
154   llvm::errs() << ">";
155 }
156 
157 void Preprocessor::DumpLocation(SourceLocation Loc) const {
158   Loc.dump(SourceMgr);
159 }
160 
161 void Preprocessor::DumpMacro(const MacroInfo &MI) const {
162   llvm::errs() << "MACRO: ";
163   for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
164     DumpToken(MI.getReplacementToken(i));
165     llvm::errs() << "  ";
166   }
167   llvm::errs() << "\n";
168 }
169 
170 void Preprocessor::PrintStats() {
171   llvm::errs() << "\n*** Preprocessor Stats:\n";
172   llvm::errs() << NumDirectives << " directives found:\n";
173   llvm::errs() << "  " << NumDefined << " #define.\n";
174   llvm::errs() << "  " << NumUndefined << " #undef.\n";
175   llvm::errs() << "  #include/#include_next/#import:\n";
176   llvm::errs() << "    " << NumEnteredSourceFiles << " source files entered.\n";
177   llvm::errs() << "    " << MaxIncludeStackDepth << " max include stack depth\n";
178   llvm::errs() << "  " << NumIf << " #if/#ifndef/#ifdef.\n";
179   llvm::errs() << "  " << NumElse << " #else/#elif.\n";
180   llvm::errs() << "  " << NumEndif << " #endif.\n";
181   llvm::errs() << "  " << NumPragma << " #pragma.\n";
182   llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
183 
184   llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
185              << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
186              << NumFastMacroExpanded << " on the fast path.\n";
187   llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
188              << " token paste (##) operations performed, "
189              << NumFastTokenPaste << " on the fast path.\n";
190 }
191 
192 bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
193                                           unsigned TruncateAtLine,
194                                           unsigned TruncateAtColumn) {
195   using llvm::MemoryBuffer;
196 
197   CodeCompletionFile = File;
198 
199   // Okay to clear out the code-completion point by passing NULL.
200   if (!CodeCompletionFile)
201     return false;
202 
203   // Load the actual file's contents.
204   const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
205   if (!Buffer)
206     return true;
207 
208   // Find the byte position of the truncation point.
209   const char *Position = Buffer->getBufferStart();
210   for (unsigned Line = 1; Line < TruncateAtLine; ++Line) {
211     for (; *Position; ++Position) {
212       if (*Position != '\r' && *Position != '\n')
213         continue;
214 
215       // Eat \r\n or \n\r as a single line.
216       if ((Position[1] == '\r' || Position[1] == '\n') &&
217           Position[0] != Position[1])
218         ++Position;
219       ++Position;
220       break;
221     }
222   }
223 
224   Position += TruncateAtColumn - 1;
225 
226   // Truncate the buffer.
227   if (Position < Buffer->getBufferEnd()) {
228     MemoryBuffer *TruncatedBuffer
229       = MemoryBuffer::getMemBufferCopy(Buffer->getBufferStart(), Position,
230                                        Buffer->getBufferIdentifier());
231     SourceMgr.overrideFileContents(File, TruncatedBuffer);
232   }
233 
234   return false;
235 }
236 
237 bool Preprocessor::isCodeCompletionFile(SourceLocation FileLoc) const {
238   return CodeCompletionFile && FileLoc.isFileID() &&
239     SourceMgr.getFileEntryForID(SourceMgr.getFileID(FileLoc))
240       == CodeCompletionFile;
241 }
242 
243 //===----------------------------------------------------------------------===//
244 // Token Spelling
245 //===----------------------------------------------------------------------===//
246 
247 /// getSpelling() - Return the 'spelling' of this token.  The spelling of a
248 /// token are the characters used to represent the token in the source file
249 /// after trigraph expansion and escaped-newline folding.  In particular, this
250 /// wants to get the true, uncanonicalized, spelling of things like digraphs
251 /// UCNs, etc.
252 std::string Preprocessor::getSpelling(const Token &Tok,
253                                       const SourceManager &SourceMgr,
254                                       const LangOptions &Features) {
255   assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
256 
257   // If this token contains nothing interesting, return it directly.
258   const char* TokStart = SourceMgr.getCharacterData(Tok.getLocation());
259   if (!Tok.needsCleaning())
260     return std::string(TokStart, TokStart+Tok.getLength());
261 
262   std::string Result;
263   Result.reserve(Tok.getLength());
264 
265   // Otherwise, hard case, relex the characters into the string.
266   for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
267        Ptr != End; ) {
268     unsigned CharSize;
269     Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
270     Ptr += CharSize;
271   }
272   assert(Result.size() != unsigned(Tok.getLength()) &&
273          "NeedsCleaning flag set on something that didn't need cleaning!");
274   return Result;
275 }
276 
277 /// getSpelling() - Return the 'spelling' of this token.  The spelling of a
278 /// token are the characters used to represent the token in the source file
279 /// after trigraph expansion and escaped-newline folding.  In particular, this
280 /// wants to get the true, uncanonicalized, spelling of things like digraphs
281 /// UCNs, etc.
282 std::string Preprocessor::getSpelling(const Token &Tok) const {
283   return getSpelling(Tok, SourceMgr, Features);
284 }
285 
286 /// getSpelling - This method is used to get the spelling of a token into a
287 /// preallocated buffer, instead of as an std::string.  The caller is required
288 /// to allocate enough space for the token, which is guaranteed to be at least
289 /// Tok.getLength() bytes long.  The actual length of the token is returned.
290 ///
291 /// Note that this method may do two possible things: it may either fill in
292 /// the buffer specified with characters, or it may *change the input pointer*
293 /// to point to a constant buffer with the data already in it (avoiding a
294 /// copy).  The caller is not allowed to modify the returned buffer pointer
295 /// if an internal buffer is returned.
296 unsigned Preprocessor::getSpelling(const Token &Tok,
297                                    const char *&Buffer) const {
298   assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
299 
300   // If this token is an identifier, just return the string from the identifier
301   // table, which is very quick.
302   if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
303     Buffer = II->getNameStart();
304     return II->getLength();
305   }
306 
307   // Otherwise, compute the start of the token in the input lexer buffer.
308   const char *TokStart = 0;
309 
310   if (Tok.isLiteral())
311     TokStart = Tok.getLiteralData();
312 
313   if (TokStart == 0)
314     TokStart = SourceMgr.getCharacterData(Tok.getLocation());
315 
316   // If this token contains nothing interesting, return it directly.
317   if (!Tok.needsCleaning()) {
318     Buffer = TokStart;
319     return Tok.getLength();
320   }
321 
322   // Otherwise, hard case, relex the characters into the string.
323   char *OutBuf = const_cast<char*>(Buffer);
324   for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
325        Ptr != End; ) {
326     unsigned CharSize;
327     *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
328     Ptr += CharSize;
329   }
330   assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
331          "NeedsCleaning flag set on something that didn't need cleaning!");
332 
333   return OutBuf-Buffer;
334 }
335 
336 /// CreateString - Plop the specified string into a scratch buffer and return a
337 /// location for it.  If specified, the source location provides a source
338 /// location for the token.
339 void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok,
340                                 SourceLocation InstantiationLoc) {
341   Tok.setLength(Len);
342 
343   const char *DestPtr;
344   SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr);
345 
346   if (InstantiationLoc.isValid())
347     Loc = SourceMgr.createInstantiationLoc(Loc, InstantiationLoc,
348                                            InstantiationLoc, Len);
349   Tok.setLocation(Loc);
350 
351   // If this is a literal token, set the pointer data.
352   if (Tok.isLiteral())
353     Tok.setLiteralData(DestPtr);
354 }
355 
356 
357 /// AdvanceToTokenCharacter - Given a location that specifies the start of a
358 /// token, return a new location that specifies a character within the token.
359 SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
360                                                      unsigned CharNo) {
361   // Figure out how many physical characters away the specified instantiation
362   // character is.  This needs to take into consideration newlines and
363   // trigraphs.
364   const char *TokPtr = SourceMgr.getCharacterData(TokStart);
365 
366   // If they request the first char of the token, we're trivially done.
367   if (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr))
368     return TokStart;
369 
370   unsigned PhysOffset = 0;
371 
372   // The usual case is that tokens don't contain anything interesting.  Skip
373   // over the uninteresting characters.  If a token only consists of simple
374   // chars, this method is extremely fast.
375   while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
376     if (CharNo == 0)
377       return TokStart.getFileLocWithOffset(PhysOffset);
378     ++TokPtr, --CharNo, ++PhysOffset;
379   }
380 
381   // If we have a character that may be a trigraph or escaped newline, use a
382   // lexer to parse it correctly.
383   for (; CharNo; --CharNo) {
384     unsigned Size;
385     Lexer::getCharAndSizeNoWarn(TokPtr, Size, Features);
386     TokPtr += Size;
387     PhysOffset += Size;
388   }
389 
390   // Final detail: if we end up on an escaped newline, we want to return the
391   // location of the actual byte of the token.  For example foo\<newline>bar
392   // advanced by 3 should return the location of b, not of \\.  One compounding
393   // detail of this is that the escape may be made by a trigraph.
394   if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
395     PhysOffset = Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
396 
397   return TokStart.getFileLocWithOffset(PhysOffset);
398 }
399 
400 /// \brief Computes the source location just past the end of the
401 /// token at this source location.
402 ///
403 /// This routine can be used to produce a source location that
404 /// points just past the end of the token referenced by \p Loc, and
405 /// is generally used when a diagnostic needs to point just after a
406 /// token where it expected something different that it received. If
407 /// the returned source location would not be meaningful (e.g., if
408 /// it points into a macro), this routine returns an invalid
409 /// source location.
410 SourceLocation Preprocessor::getLocForEndOfToken(SourceLocation Loc) {
411   if (Loc.isInvalid() || !Loc.isFileID())
412     return SourceLocation();
413 
414   unsigned Len = Lexer::MeasureTokenLength(Loc, getSourceManager(), Features);
415   return AdvanceToTokenCharacter(Loc, Len);
416 }
417 
418 
419 
420 //===----------------------------------------------------------------------===//
421 // Preprocessor Initialization Methods
422 //===----------------------------------------------------------------------===//
423 
424 
425 /// EnterMainSourceFile - Enter the specified FileID as the main source file,
426 /// which implicitly adds the builtin defines etc.
427 void Preprocessor::EnterMainSourceFile() {
428   // We do not allow the preprocessor to reenter the main file.  Doing so will
429   // cause FileID's to accumulate information from both runs (e.g. #line
430   // information) and predefined macros aren't guaranteed to be set properly.
431   assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
432   FileID MainFileID = SourceMgr.getMainFileID();
433 
434   // Enter the main file source buffer.
435   std::string ErrorStr;
436   bool Res = EnterSourceFile(MainFileID, 0, ErrorStr);
437   assert(!Res && "Entering main file should not fail!");
438 
439   // Tell the header info that the main file was entered.  If the file is later
440   // #imported, it won't be re-entered.
441   if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
442     HeaderInfo.IncrementIncludeCount(FE);
443 
444   std::vector<char> PrologFile;
445   PrologFile.reserve(4080);
446 
447   // FIXME: Don't make a copy.
448   PrologFile.insert(PrologFile.end(), Predefines.begin(), Predefines.end());
449 
450   // Memory buffer must end with a null byte!
451   PrologFile.push_back(0);
452 
453   // Now that we have emitted the predefined macros, #includes, etc into
454   // PrologFile, preprocess it to populate the initial preprocessor state.
455   llvm::MemoryBuffer *SB =
456     llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(),
457                                          "<built-in>");
458   assert(SB && "Cannot fail to create predefined source buffer");
459   FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
460   assert(!FID.isInvalid() && "Could not create FileID for predefines?");
461 
462   // Start parsing the predefines.
463   Res = EnterSourceFile(FID, 0, ErrorStr);
464   assert(!Res && "Entering predefines should not fail!");
465 }
466 
467 
468 //===----------------------------------------------------------------------===//
469 // Lexer Event Handling.
470 //===----------------------------------------------------------------------===//
471 
472 /// LookUpIdentifierInfo - Given a tok::identifier token, look up the
473 /// identifier information for the token and install it into the token.
474 IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
475                                                    const char *BufPtr) const {
476   assert(Identifier.is(tok::identifier) && "Not an identifier!");
477   assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
478 
479   // Look up this token, see if it is a macro, or if it is a language keyword.
480   IdentifierInfo *II;
481   if (BufPtr && !Identifier.needsCleaning()) {
482     // No cleaning needed, just use the characters from the lexed buffer.
483     II = getIdentifierInfo(llvm::StringRef(BufPtr, Identifier.getLength()));
484   } else {
485     // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
486     llvm::SmallVector<char, 64> IdentifierBuffer;
487     IdentifierBuffer.resize(Identifier.getLength());
488     const char *TmpBuf = &IdentifierBuffer[0];
489     unsigned Size = getSpelling(Identifier, TmpBuf);
490     II = getIdentifierInfo(llvm::StringRef(TmpBuf, Size));
491   }
492   Identifier.setIdentifierInfo(II);
493   return II;
494 }
495 
496 
497 /// HandleIdentifier - This callback is invoked when the lexer reads an
498 /// identifier.  This callback looks up the identifier in the map and/or
499 /// potentially macro expands it or turns it into a named token (like 'for').
500 ///
501 /// Note that callers of this method are guarded by checking the
502 /// IdentifierInfo's 'isHandleIdentifierCase' bit.  If this method changes, the
503 /// IdentifierInfo methods that compute these properties will need to change to
504 /// match.
505 void Preprocessor::HandleIdentifier(Token &Identifier) {
506   assert(Identifier.getIdentifierInfo() &&
507          "Can't handle identifiers without identifier info!");
508 
509   IdentifierInfo &II = *Identifier.getIdentifierInfo();
510 
511   // If this identifier was poisoned, and if it was not produced from a macro
512   // expansion, emit an error.
513   if (II.isPoisoned() && CurPPLexer) {
514     if (&II != Ident__VA_ARGS__)   // We warn about __VA_ARGS__ with poisoning.
515       Diag(Identifier, diag::err_pp_used_poisoned_id);
516     else
517       Diag(Identifier, diag::ext_pp_bad_vaargs_use);
518   }
519 
520   // If this is a macro to be expanded, do it.
521   if (MacroInfo *MI = getMacroInfo(&II)) {
522     if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
523       if (MI->isEnabled()) {
524         if (!HandleMacroExpandedIdentifier(Identifier, MI))
525           return;
526       } else {
527         // C99 6.10.3.4p2 says that a disabled macro may never again be
528         // expanded, even if it's in a context where it could be expanded in the
529         // future.
530         Identifier.setFlag(Token::DisableExpand);
531       }
532     }
533   }
534 
535   // C++ 2.11p2: If this is an alternative representation of a C++ operator,
536   // then we act as if it is the actual operator and not the textual
537   // representation of it.
538   if (II.isCPlusPlusOperatorKeyword())
539     Identifier.setIdentifierInfo(0);
540 
541   // If this is an extension token, diagnose its use.
542   // We avoid diagnosing tokens that originate from macro definitions.
543   // FIXME: This warning is disabled in cases where it shouldn't be,
544   // like "#define TY typeof", "TY(1) x".
545   if (II.isExtensionToken() && !DisableMacroExpansion)
546     Diag(Identifier, diag::ext_token_used);
547 }
548 
549 void Preprocessor::AddCommentHandler(CommentHandler *Handler) {
550   assert(Handler && "NULL comment handler");
551   assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
552          CommentHandlers.end() && "Comment handler already registered");
553   CommentHandlers.push_back(Handler);
554 }
555 
556 void Preprocessor::RemoveCommentHandler(CommentHandler *Handler) {
557   std::vector<CommentHandler *>::iterator Pos
558   = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
559   assert(Pos != CommentHandlers.end() && "Comment handler not registered");
560   CommentHandlers.erase(Pos);
561 }
562 
563 void Preprocessor::HandleComment(SourceRange Comment) {
564   for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
565        HEnd = CommentHandlers.end();
566        H != HEnd; ++H)
567     (*H)->HandleComment(*this, Comment);
568 }
569 
570 CommentHandler::~CommentHandler() { }
571