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 "MacroArgs.h"
30 #include "clang/Lex/ExternalPreprocessorSource.h"
31 #include "clang/Lex/HeaderSearch.h"
32 #include "clang/Lex/MacroInfo.h"
33 #include "clang/Lex/Pragma.h"
34 #include "clang/Lex/PreprocessingRecord.h"
35 #include "clang/Lex/ScratchBuffer.h"
36 #include "clang/Lex/LexDiagnostic.h"
37 #include "clang/Lex/CodeCompletionHandler.h"
38 #include "clang/Basic/SourceManager.h"
39 #include "clang/Basic/FileManager.h"
40 #include "clang/Basic/TargetInfo.h"
41 #include "llvm/ADT/APFloat.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/raw_ostream.h"
45 using namespace clang;
46 
47 //===----------------------------------------------------------------------===//
48 ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
49 
50 Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
51                            const TargetInfo &target, SourceManager &SM,
52                            HeaderSearch &Headers,
53                            IdentifierInfoLookup* IILookup,
54                            bool OwnsHeaders)
55   : Diags(&diags), Features(opts), Target(target),FileMgr(Headers.getFileMgr()),
56     SourceMgr(SM),
57     HeaderInfo(Headers), ExternalSource(0),
58     Identifiers(opts, IILookup), BuiltinInfo(Target), CodeComplete(0),
59     CodeCompletionFile(0), SkipMainFilePreamble(0, true), CurPPLexer(0),
60     CurDirLookup(0), Callbacks(0), MacroArgCache(0), Record(0), MIChainHead(0),
61     MICache(0) {
62   ScratchBuf = new ScratchBuffer(SourceMgr);
63   CounterValue = 0; // __COUNTER__ starts at 0.
64   OwnsHeaderSearch = OwnsHeaders;
65 
66   // Clear stats.
67   NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
68   NumIf = NumElse = NumEndif = 0;
69   NumEnteredSourceFiles = 0;
70   NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
71   NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
72   MaxIncludeStackDepth = 0;
73   NumSkipped = 0;
74 
75   // Default to discarding comments.
76   KeepComments = false;
77   KeepMacroComments = false;
78 
79   // Macro expansion is enabled.
80   DisableMacroExpansion = false;
81   InMacroArgs = false;
82   NumCachedTokenLexers = 0;
83 
84   CachedLexPos = 0;
85 
86   // We haven't read anything from the external source.
87   ReadMacrosFromExternalSource = false;
88 
89   // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
90   // This gets unpoisoned where it is allowed.
91   (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
92   SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
93 
94   // Initialize the pragma handlers.
95   PragmaHandlers = new PragmaNamespace(llvm::StringRef());
96   RegisterBuiltinPragmas();
97 
98   // Initialize builtin macros like __LINE__ and friends.
99   RegisterBuiltinMacros();
100 
101   if(Features.Borland) {
102     Ident__exception_info        = getIdentifierInfo("_exception_info");
103     Ident___exception_info       = getIdentifierInfo("__exception_info");
104     Ident_GetExceptionInfo       = getIdentifierInfo("GetExceptionInformation");
105     Ident__exception_code        = getIdentifierInfo("_exception_code");
106     Ident___exception_code       = getIdentifierInfo("__exception_code");
107     Ident_GetExceptionCode       = getIdentifierInfo("GetExceptionCode");
108     Ident__abnormal_termination  = getIdentifierInfo("_abnormal_termination");
109     Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
110     Ident_AbnormalTermination    = getIdentifierInfo("AbnormalTermination");
111   } else {
112     Ident__exception_info = Ident__exception_code = Ident__abnormal_termination = 0;
113     Ident___exception_info = Ident___exception_code = Ident___abnormal_termination = 0;
114     Ident_GetExceptionInfo = Ident_GetExceptionCode = Ident_AbnormalTermination = 0;
115   }
116 
117 }
118 
119 Preprocessor::~Preprocessor() {
120   assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
121 
122   while (!IncludeMacroStack.empty()) {
123     delete IncludeMacroStack.back().TheLexer;
124     delete IncludeMacroStack.back().TheTokenLexer;
125     IncludeMacroStack.pop_back();
126   }
127 
128   // Free any macro definitions.
129   for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next)
130     I->MI.Destroy();
131 
132   // Free any cached macro expanders.
133   for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
134     delete TokenLexerCache[i];
135 
136   // Free any cached MacroArgs.
137   for (MacroArgs *ArgList = MacroArgCache; ArgList; )
138     ArgList = ArgList->deallocate();
139 
140   // Release pragma information.
141   delete PragmaHandlers;
142 
143   // Delete the scratch buffer info.
144   delete ScratchBuf;
145 
146   // Delete the header search info, if we own it.
147   if (OwnsHeaderSearch)
148     delete &HeaderInfo;
149 
150   delete Callbacks;
151 }
152 
153 void Preprocessor::setPTHManager(PTHManager* pm) {
154   PTH.reset(pm);
155   FileMgr.addStatCache(PTH->createStatCache());
156 }
157 
158 void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
159   llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
160                << getSpelling(Tok) << "'";
161 
162   if (!DumpFlags) return;
163 
164   llvm::errs() << "\t";
165   if (Tok.isAtStartOfLine())
166     llvm::errs() << " [StartOfLine]";
167   if (Tok.hasLeadingSpace())
168     llvm::errs() << " [LeadingSpace]";
169   if (Tok.isExpandDisabled())
170     llvm::errs() << " [ExpandDisabled]";
171   if (Tok.needsCleaning()) {
172     const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
173     llvm::errs() << " [UnClean='" << llvm::StringRef(Start, Tok.getLength())
174                  << "']";
175   }
176 
177   llvm::errs() << "\tLoc=<";
178   DumpLocation(Tok.getLocation());
179   llvm::errs() << ">";
180 }
181 
182 void Preprocessor::DumpLocation(SourceLocation Loc) const {
183   Loc.dump(SourceMgr);
184 }
185 
186 void Preprocessor::DumpMacro(const MacroInfo &MI) const {
187   llvm::errs() << "MACRO: ";
188   for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
189     DumpToken(MI.getReplacementToken(i));
190     llvm::errs() << "  ";
191   }
192   llvm::errs() << "\n";
193 }
194 
195 void Preprocessor::PrintStats() {
196   llvm::errs() << "\n*** Preprocessor Stats:\n";
197   llvm::errs() << NumDirectives << " directives found:\n";
198   llvm::errs() << "  " << NumDefined << " #define.\n";
199   llvm::errs() << "  " << NumUndefined << " #undef.\n";
200   llvm::errs() << "  #include/#include_next/#import:\n";
201   llvm::errs() << "    " << NumEnteredSourceFiles << " source files entered.\n";
202   llvm::errs() << "    " << MaxIncludeStackDepth << " max include stack depth\n";
203   llvm::errs() << "  " << NumIf << " #if/#ifndef/#ifdef.\n";
204   llvm::errs() << "  " << NumElse << " #else/#elif.\n";
205   llvm::errs() << "  " << NumEndif << " #endif.\n";
206   llvm::errs() << "  " << NumPragma << " #pragma.\n";
207   llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
208 
209   llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
210              << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
211              << NumFastMacroExpanded << " on the fast path.\n";
212   llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
213              << " token paste (##) operations performed, "
214              << NumFastTokenPaste << " on the fast path.\n";
215 }
216 
217 Preprocessor::macro_iterator
218 Preprocessor::macro_begin(bool IncludeExternalMacros) const {
219   if (IncludeExternalMacros && ExternalSource &&
220       !ReadMacrosFromExternalSource) {
221     ReadMacrosFromExternalSource = true;
222     ExternalSource->ReadDefinedMacros();
223   }
224 
225   return Macros.begin();
226 }
227 
228 Preprocessor::macro_iterator
229 Preprocessor::macro_end(bool IncludeExternalMacros) const {
230   if (IncludeExternalMacros && ExternalSource &&
231       !ReadMacrosFromExternalSource) {
232     ReadMacrosFromExternalSource = true;
233     ExternalSource->ReadDefinedMacros();
234   }
235 
236   return Macros.end();
237 }
238 
239 bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
240                                           unsigned TruncateAtLine,
241                                           unsigned TruncateAtColumn) {
242   using llvm::MemoryBuffer;
243 
244   CodeCompletionFile = File;
245 
246   // Okay to clear out the code-completion point by passing NULL.
247   if (!CodeCompletionFile)
248     return false;
249 
250   // Load the actual file's contents.
251   bool Invalid = false;
252   const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
253   if (Invalid)
254     return true;
255 
256   // Find the byte position of the truncation point.
257   const char *Position = Buffer->getBufferStart();
258   for (unsigned Line = 1; Line < TruncateAtLine; ++Line) {
259     for (; *Position; ++Position) {
260       if (*Position != '\r' && *Position != '\n')
261         continue;
262 
263       // Eat \r\n or \n\r as a single line.
264       if ((Position[1] == '\r' || Position[1] == '\n') &&
265           Position[0] != Position[1])
266         ++Position;
267       ++Position;
268       break;
269     }
270   }
271 
272   Position += TruncateAtColumn - 1;
273 
274   // Truncate the buffer.
275   if (Position < Buffer->getBufferEnd()) {
276     llvm::StringRef Data(Buffer->getBufferStart(),
277                          Position-Buffer->getBufferStart());
278     MemoryBuffer *TruncatedBuffer
279       = MemoryBuffer::getMemBufferCopy(Data, Buffer->getBufferIdentifier());
280     SourceMgr.overrideFileContents(File, TruncatedBuffer);
281   }
282 
283   return false;
284 }
285 
286 bool Preprocessor::isCodeCompletionFile(SourceLocation FileLoc) const {
287   return CodeCompletionFile && FileLoc.isFileID() &&
288     SourceMgr.getFileEntryForID(SourceMgr.getFileID(FileLoc))
289       == CodeCompletionFile;
290 }
291 
292 void Preprocessor::CodeCompleteNaturalLanguage() {
293   SetCodeCompletionPoint(0, 0, 0);
294   getDiagnostics().setSuppressAllDiagnostics(true);
295   if (CodeComplete)
296     CodeComplete->CodeCompleteNaturalLanguage();
297 }
298 
299 /// getSpelling - This method is used to get the spelling of a token into a
300 /// SmallVector. Note that the returned StringRef may not point to the
301 /// supplied buffer if a copy can be avoided.
302 llvm::StringRef Preprocessor::getSpelling(const Token &Tok,
303                                           llvm::SmallVectorImpl<char> &Buffer,
304                                           bool *Invalid) const {
305   // NOTE: this has to be checked *before* testing for an IdentifierInfo.
306   if (Tok.isNot(tok::raw_identifier)) {
307     // Try the fast path.
308     if (const IdentifierInfo *II = Tok.getIdentifierInfo())
309       return II->getName();
310   }
311 
312   // Resize the buffer if we need to copy into it.
313   if (Tok.needsCleaning())
314     Buffer.resize(Tok.getLength());
315 
316   const char *Ptr = Buffer.data();
317   unsigned Len = getSpelling(Tok, Ptr, Invalid);
318   return llvm::StringRef(Ptr, Len);
319 }
320 
321 /// CreateString - Plop the specified string into a scratch buffer and return a
322 /// location for it.  If specified, the source location provides a source
323 /// location for the token.
324 void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok,
325                                 SourceLocation InstantiationLoc) {
326   Tok.setLength(Len);
327 
328   const char *DestPtr;
329   SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr);
330 
331   if (InstantiationLoc.isValid())
332     Loc = SourceMgr.createInstantiationLoc(Loc, InstantiationLoc,
333                                            InstantiationLoc, Len);
334   Tok.setLocation(Loc);
335 
336   // If this is a raw identifier or a literal token, set the pointer data.
337   if (Tok.is(tok::raw_identifier))
338     Tok.setRawIdentifierData(DestPtr);
339   else if (Tok.isLiteral())
340     Tok.setLiteralData(DestPtr);
341 }
342 
343 
344 
345 //===----------------------------------------------------------------------===//
346 // Preprocessor Initialization Methods
347 //===----------------------------------------------------------------------===//
348 
349 
350 /// EnterMainSourceFile - Enter the specified FileID as the main source file,
351 /// which implicitly adds the builtin defines etc.
352 void Preprocessor::EnterMainSourceFile() {
353   // We do not allow the preprocessor to reenter the main file.  Doing so will
354   // cause FileID's to accumulate information from both runs (e.g. #line
355   // information) and predefined macros aren't guaranteed to be set properly.
356   assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
357   FileID MainFileID = SourceMgr.getMainFileID();
358 
359   // Enter the main file source buffer.
360   EnterSourceFile(MainFileID, 0, SourceLocation());
361 
362   // If we've been asked to skip bytes in the main file (e.g., as part of a
363   // precompiled preamble), do so now.
364   if (SkipMainFilePreamble.first > 0)
365     CurLexer->SkipBytes(SkipMainFilePreamble.first,
366                         SkipMainFilePreamble.second);
367 
368   // Tell the header info that the main file was entered.  If the file is later
369   // #imported, it won't be re-entered.
370   if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
371     HeaderInfo.IncrementIncludeCount(FE);
372 
373   // Preprocess Predefines to populate the initial preprocessor state.
374   llvm::MemoryBuffer *SB =
375     llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
376   assert(SB && "Cannot create predefined source buffer");
377   FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
378   assert(!FID.isInvalid() && "Could not create FileID for predefines?");
379 
380   // Start parsing the predefines.
381   EnterSourceFile(FID, 0, SourceLocation());
382 }
383 
384 void Preprocessor::EndSourceFile() {
385   // Notify the client that we reached the end of the source file.
386   if (Callbacks)
387     Callbacks->EndOfMainFile();
388 }
389 
390 //===----------------------------------------------------------------------===//
391 // Lexer Event Handling.
392 //===----------------------------------------------------------------------===//
393 
394 /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
395 /// identifier information for the token and install it into the token,
396 /// updating the token kind accordingly.
397 IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
398   assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!");
399 
400   // Look up this token, see if it is a macro, or if it is a language keyword.
401   IdentifierInfo *II;
402   if (!Identifier.needsCleaning()) {
403     // No cleaning needed, just use the characters from the lexed buffer.
404     II = getIdentifierInfo(llvm::StringRef(Identifier.getRawIdentifierData(),
405                                            Identifier.getLength()));
406   } else {
407     // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
408     llvm::SmallString<64> IdentifierBuffer;
409     llvm::StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
410     II = getIdentifierInfo(CleanedStr);
411   }
412 
413   // Update the token info (identifier info and appropriate token kind).
414   Identifier.setIdentifierInfo(II);
415   Identifier.setKind(II->getTokenID());
416 
417   return II;
418 }
419 
420 void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
421   PoisonReasons[II] = DiagID;
422 }
423 
424 void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
425   assert(Ident__exception_code && Ident__exception_info);
426   assert(Ident___exception_code && Ident___exception_info);
427   Ident__exception_code->setIsPoisoned(Poison);
428   Ident___exception_code->setIsPoisoned(Poison);
429   Ident_GetExceptionCode->setIsPoisoned(Poison);
430   Ident__exception_info->setIsPoisoned(Poison);
431   Ident___exception_info->setIsPoisoned(Poison);
432   Ident_GetExceptionInfo->setIsPoisoned(Poison);
433   Ident__abnormal_termination->setIsPoisoned(Poison);
434   Ident___abnormal_termination->setIsPoisoned(Poison);
435   Ident_AbnormalTermination->setIsPoisoned(Poison);
436 }
437 
438 void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
439   assert(Identifier.getIdentifierInfo() &&
440          "Can't handle identifiers without identifier info!");
441   llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
442     PoisonReasons.find(Identifier.getIdentifierInfo());
443   if(it == PoisonReasons.end())
444     Diag(Identifier, diag::err_pp_used_poisoned_id);
445   else
446     Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
447 }
448 
449 /// HandleIdentifier - This callback is invoked when the lexer reads an
450 /// identifier.  This callback looks up the identifier in the map and/or
451 /// potentially macro expands it or turns it into a named token (like 'for').
452 ///
453 /// Note that callers of this method are guarded by checking the
454 /// IdentifierInfo's 'isHandleIdentifierCase' bit.  If this method changes, the
455 /// IdentifierInfo methods that compute these properties will need to change to
456 /// match.
457 void Preprocessor::HandleIdentifier(Token &Identifier) {
458   assert(Identifier.getIdentifierInfo() &&
459          "Can't handle identifiers without identifier info!");
460 
461   IdentifierInfo &II = *Identifier.getIdentifierInfo();
462 
463   // If this identifier was poisoned, and if it was not produced from a macro
464   // expansion, emit an error.
465   if (II.isPoisoned() && CurPPLexer) {
466     HandlePoisonedIdentifier(Identifier);
467   }
468 
469   // If this is a macro to be expanded, do it.
470   if (MacroInfo *MI = getMacroInfo(&II)) {
471     if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
472       if (MI->isEnabled()) {
473         if (!HandleMacroExpandedIdentifier(Identifier, MI))
474           return;
475       } else {
476         // C99 6.10.3.4p2 says that a disabled macro may never again be
477         // expanded, even if it's in a context where it could be expanded in the
478         // future.
479         Identifier.setFlag(Token::DisableExpand);
480       }
481     }
482   }
483 
484   // C++ 2.11p2: If this is an alternative representation of a C++ operator,
485   // then we act as if it is the actual operator and not the textual
486   // representation of it.
487   if (II.isCPlusPlusOperatorKeyword())
488     Identifier.setIdentifierInfo(0);
489 
490   // If this is an extension token, diagnose its use.
491   // We avoid diagnosing tokens that originate from macro definitions.
492   // FIXME: This warning is disabled in cases where it shouldn't be,
493   // like "#define TY typeof", "TY(1) x".
494   if (II.isExtensionToken() && !DisableMacroExpansion)
495     Diag(Identifier, diag::ext_token_used);
496 }
497 
498 void Preprocessor::AddCommentHandler(CommentHandler *Handler) {
499   assert(Handler && "NULL comment handler");
500   assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
501          CommentHandlers.end() && "Comment handler already registered");
502   CommentHandlers.push_back(Handler);
503 }
504 
505 void Preprocessor::RemoveCommentHandler(CommentHandler *Handler) {
506   std::vector<CommentHandler *>::iterator Pos
507   = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
508   assert(Pos != CommentHandlers.end() && "Comment handler not registered");
509   CommentHandlers.erase(Pos);
510 }
511 
512 bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
513   bool AnyPendingTokens = false;
514   for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
515        HEnd = CommentHandlers.end();
516        H != HEnd; ++H) {
517     if ((*H)->HandleComment(*this, Comment))
518       AnyPendingTokens = true;
519   }
520   if (!AnyPendingTokens || getCommentRetentionState())
521     return false;
522   Lex(result);
523   return true;
524 }
525 
526 CommentHandler::~CommentHandler() { }
527 
528 CodeCompletionHandler::~CodeCompletionHandler() { }
529 
530 void Preprocessor::createPreprocessingRecord(
531                                       bool IncludeNestedMacroInstantiations) {
532   if (Record)
533     return;
534 
535   Record = new PreprocessingRecord(IncludeNestedMacroInstantiations);
536   addPPCallbacks(Record);
537 }
538