14 #include "cling/Interpreter/DynamicLibraryManager.h"
15 #include "cling/Interpreter/Interpreter.h"
16 #include "cling/Interpreter/InterpreterCallbacks.h"
17 #include "cling/Interpreter/Transaction.h"
18 #include "cling/Utils/AST.h"
20 #include "clang/AST/ASTConsumer.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/DeclBase.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/GlobalDecl.h"
25 #include "clang/Frontend/CompilerInstance.h"
26 #include "clang/Lex/HeaderSearch.h"
27 #include "clang/Lex/PPCallbacks.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Parse/Parser.h"
30 #include "clang/Sema/Lookup.h"
31 #include "clang/Sema/Scope.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/Path.h"
36 #include "TClingUtils.h"
39 using namespace clang;
40 using namespace cling;
41 using namespace ROOT::Internal;
48 void TCling__UpdateListsOnCommitted(
const cling::Transaction&, Interpreter*);
49 void TCling__UpdateListsOnUnloaded(
const cling::Transaction&);
50 void TCling__InvalidateGlobal(
const clang::Decl*);
51 void TCling__TransactionRollback(
const cling::Transaction&);
52 void TCling__GetNormalizedContext(
const ROOT::TMetaUtils::TNormalizedCtxt*&);
53 TObject* TCling__GetObjectAddress(
const char *Name,
void *&LookupCtx);
54 Decl* TCling__GetObjectDecl(TObject *obj);
55 int TCling__AutoLoadCallback(
const char* className);
56 int TCling__AutoParseCallback(
const char* className);
57 const char* TCling__GetClassSharedLibs(
const char* className);
58 int TCling__IsAutoLoadNamespaceCandidate(
const clang::NamespaceDecl* name);
59 int TCling__CompileMacro(
const char *fileName,
const char *options);
60 void TCling__SplitAclicMode(
const char* fileName, std::string &mode,
61 std::string &args, std::string &io, std::string &fname);
62 bool TCling__LibraryLoadingFailed(
const std::string&,
const std::string&,
bool,
bool);
63 void TCling__LibraryLoadedRTTI(
const void* dyLibHandle,
64 llvm::StringRef canonicalName);
65 void TCling__LibraryUnloadedRTTI(
const void* dyLibHandle,
66 llvm::StringRef canonicalName);
67 void TCling__PrintStackTrace();
68 void *TCling__ResetInterpreterMutex();
69 void TCling__RestoreInterpreterMutex(
void *state);
70 void *TCling__LockCompilationDuringUserCodeExecution();
71 void TCling__UnlockCompilationDuringUserCodeExecution(
void *state);
72 void TCling__FindLoadedLibraries(std::vector<std::pair<uint32_t, std::string>> &sLibraries,
73 std::vector<std::string> &sPaths,
74 cling::Interpreter &interpreter,
bool searchSystem);
77 TClingCallbacks::TClingCallbacks(cling::Interpreter* interp,
bool hasCodeGen)
78 : InterpreterCallbacks(interp),
79 fLastLookupCtx(0), fROOTSpecialNamespace(0),
80 fFirstRun(true), fIsAutoloading(false), fIsAutoloadingRecursively(false),
81 fIsAutoParsingSuspended(false), fPPOldFlag(false), fPPChanged(false) {
84 m_Interpreter->declare(
"namespace __ROOT_SpecialObjects{}", &T);
85 fROOTSpecialNamespace = dyn_cast<NamespaceDecl>(T->getFirstDecl().getSingleDecl());
90 TClingCallbacks::~TClingCallbacks() {}
92 void TClingCallbacks::InclusionDirective(clang::SourceLocation sLoc,
94 llvm::StringRef FileName,
96 clang::CharSourceRange ,
97 const clang::FileEntry *FE,
100 const clang::Module * Imported) {
102 Sema &SemaR = m_Interpreter->getSema();
105 if (!SemaR.isModuleVisible(Imported))
106 ROOT::TMetaUtils::Info(
"TClingCallbacks::InclusionDirective",
107 "Module %s resolved but not visible!", Imported->Name.c_str());
123 bool isHeaderFile = FileName.endswith(
".h") || FileName.endswith(
".hxx") || FileName.endswith(
".hpp");
124 if (!IsAutoloadingEnabled() || fIsAutoloadingRecursively || !isHeaderFile)
127 std::string localString(FileName.str());
129 DeclarationName Name = &SemaR.getASTContext().Idents.get(localString.c_str());
130 LookupResult RHeader(SemaR, Name, sLoc, Sema::LookupOrdinaryName);
132 tryAutoParseInternal(localString, RHeader, SemaR.getCurScope(), FE);
136 bool TClingCallbacks::LibraryLoadingFailed(
const std::string& errmessage,
const std::string& libStem,
137 bool permanent,
bool resolved) {
138 return TCling__LibraryLoadingFailed(errmessage, libStem, permanent, resolved);
144 bool TClingCallbacks::FileNotFound(llvm::StringRef FileName,
145 llvm::SmallVectorImpl<char> &RecoveryPath) {
153 Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor();
156 std::string filename(FileName.str().substr(0,FileName.str().find_last_of(
'"')));
157 std::string fname, mode, arguments, io;
159 TCling__SplitAclicMode(filename.c_str(), mode, arguments, io, fname);
160 if (mode.length() > 0) {
161 if (llvm::sys::fs::exists(fname)) {
163 std::string options =
"k";
164 if (mode.find(
"++") != std::string::npos) options +=
"f";
165 if (mode.find(
"g") != std::string::npos) options +=
"g";
166 if (mode.find(
"O") != std::string::npos) options +=
"O";
169 Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
170 Parser& P =
const_cast<Parser&
>(m_Interpreter->getParser());
173 Token& Tok =
const_cast<Token&
>(P.getCurToken());
178 Tok.setKind(tok::semi);
190 Sema& SemaR = m_Interpreter->getSema();
191 ASTContext& C = SemaR.getASTContext();
192 Sema::ContextAndScopeRAII pushedDCAndS(SemaR, C.getTranslationUnitDecl(),
194 int retcode = TCling__CompileMacro(fname.c_str(), options.c_str());
199 fPPOldFlag = PP.GetSuppressIncludeNotFoundError();
200 PP.SetSuppressIncludeNotFoundError(
true);
209 PP.SetSuppressIncludeNotFoundError(fPPOldFlag);
216 static bool topmostDCIsFunction(Scope* S) {
220 DeclContext* DC = S->getEntity();
229 clang::DeclContext* MaybeTU = DC;
230 while (MaybeTU && !isa<TranslationUnitDecl>(MaybeTU)) {
232 MaybeTU = MaybeTU->getParent();
234 return isa<FunctionDecl>(DC);
245 bool TClingCallbacks::LookupObject(LookupResult &R, Scope *S) {
246 if (!fROOTSpecialNamespace) {
252 if (m_Interpreter->getSema().getDiagnostics().hasErrorOccurred())
255 if (tryAutoParseInternal(R.getLookupName().getAsString(), R, S))
261 if (!topmostDCIsFunction(S))
265 if (tryFindROOTSpecialInternal(R, S))
276 if (tryInjectImplicitAutoKeyword(R, S)) {
280 if (fIsAutoloadingRecursively)
285 return tryResolveAtRuntimeInternal(R, S);
288 bool TClingCallbacks::LookupObject(
const DeclContext* DC, DeclarationName Name) {
289 if (!fROOTSpecialNamespace) {
294 if (!IsAutoloadingEnabled() || fIsAutoloadingRecursively)
return false;
296 if (Name.getNameKind() != DeclarationName::Identifier)
return false;
303 NamespaceDecl* NSD = dyn_cast<NamespaceDecl>(
const_cast<DeclContext*
>(DC));
307 if ( !TCling__IsAutoLoadNamespaceCandidate(NSD) )
310 const DeclContext* primaryDC = NSD->getPrimaryContext();
314 Sema &SemaR = m_Interpreter->getSema();
315 LookupResult R(SemaR, Name, SourceLocation(), Sema::LookupOrdinaryName);
316 R.suppressDiagnostics();
319 = NSD->getQualifiedNameAsString() +
"::" + Name.getAsString();
325 clang::Scope S(SemaR.TUScope, clang::Scope::DeclScope, SemaR.getDiagnostics());
326 S.setEntity(const_cast<DeclContext*>(DC));
327 Sema::ContextAndScopeRAII pushedDCAndS(SemaR, const_cast<DeclContext*>(DC), &S);
329 if (tryAutoParseInternal(qualName, R, SemaR.getCurScope())) {
330 llvm::SmallVector<NamedDecl*, 4> lookupResults;
331 for(LookupResult::iterator I = R.begin(), E = R.end(); I < E; ++I)
332 lookupResults.push_back(*I);
333 UpdateWithNewDecls(DC, Name, llvm::makeArrayRef(lookupResults.data(),
334 lookupResults.size()));
340 bool TClingCallbacks::LookupObject(clang::TagDecl* Tag) {
341 if (!fROOTSpecialNamespace) {
347 if (fIsAutoloadingRecursively || fIsAutoParsingSuspended)
return false;
349 Sema &SemaR = m_Interpreter->getSema();
351 SourceLocation Loc = Tag->getLocation();
352 if (SemaR.getSourceManager().isInSystemHeader(Loc)) {
357 for (
auto ReRD: Tag->redecls()) {
359 if (ReRD->isBeingDefined())
364 if (RecordDecl* RD = dyn_cast<RecordDecl>(Tag)) {
365 ASTContext& C = SemaR.getASTContext();
366 Parser& P =
const_cast<Parser&
>(m_Interpreter->getParser());
368 ParsingStateRAII raii(P,SemaR);
372 const ROOT::TMetaUtils::TNormalizedCtxt* tNormCtxt = NULL;
373 TCling__GetNormalizedContext(tNormCtxt);
374 ROOT::TMetaUtils::GetNormalizedName(Name,
375 C.getTypeDeclType(RD),
379 if (TCling__AutoParseCallback(Name.c_str())) {
381 Tag->setHasExternalLexicalStorage(
false);
396 bool TClingCallbacks::tryAutoParseInternal(llvm::StringRef Name, LookupResult &R,
397 Scope *S,
const FileEntry* FE ) {
398 if (!fROOTSpecialNamespace) {
403 Sema &SemaR = m_Interpreter->getSema();
406 if (IsAutoloadingEnabled()) {
408 if (fIsAutoloadingRecursively)
412 Sema::LookupNameKind kind = R.getLookupKind();
413 if (!(kind == Sema::LookupTagName || kind == Sema::LookupOrdinaryName
414 || kind == Sema::LookupNestedNameSpecifierName
415 || kind == Sema::LookupNamespaceName))
418 fIsAutoloadingRecursively =
true;
420 bool lookupSuccess =
false;
422 Parser &P =
const_cast<Parser &
>(m_Interpreter->getParser());
424 ParsingStateRAII raii(P, SemaR);
429 lookupSuccess = SemaR.LookupName(R, S);
431 if (R.isSingleResult()) {
432 if (isa<clang::RecordDecl>(R.getFoundDecl())) {
436 TCling__AutoLoadCallback(Name.data());
437 fIsAutoloadingRecursively =
false;
444 if (TCling__AutoParseCallback(Name.str().c_str())) {
446 raii.fPushedDCAndS.pop();
447 raii.fCleanupRAII.pop();
448 lookupSuccess = FE || SemaR.LookupName(R, S);
449 }
else if (FE && TCling__GetClassSharedLibs(Name.str().c_str())) {
454 std::string incl =
"#include \"";
455 incl += FE->getName();
457 m_Interpreter->declare(incl);
460 fIsAutoloadingRecursively =
false;
486 bool TClingCallbacks::tryFindROOTSpecialInternal(LookupResult &R, Scope *S) {
487 if (!fROOTSpecialNamespace) {
493 if (R.isForRedeclaration())
498 const Sema::LookupNameKind LookupKind = R.getLookupKind();
499 if (LookupKind != Sema::LookupOrdinaryName)
503 Sema &SemaR = m_Interpreter->getSema();
504 ASTContext& C = SemaR.getASTContext();
505 Preprocessor &PP = SemaR.getPreprocessor();
506 DeclContext *CurDC = SemaR.CurContext;
507 DeclarationName Name = R.getLookupName();
510 if(!CurDC || !CurDC->isFunctionOrMethod())
515 Preprocessor::CleanupAndRestoreCacheRAII cleanupPPRAII(PP);
516 TObject *obj = TCling__GetObjectAddress(Name.getAsString().c_str(),
522 #if defined(R__MUST_REVISIT)
523 #if R__MUST_REVISIT(6,2)
528 if (!fgSetOfSpecials) {
529 fgSetOfSpecials =
new std::set<TObject*>;
531 ((std::set<TObject*>*)fgSetOfSpecials)->insert((TObject*)*obj);
535 VarDecl *VD = cast_or_null<VarDecl>(utils::Lookup::Named(&SemaR, Name,
536 fROOTSpecialNamespace));
540 TObject **address = (TObject**)m_Interpreter->getAddressOfGlobal(GD);
544 CStyleCastExpr *CStyleCast = cast<CStyleCastExpr>(VD->getInit());
545 Expr* newInit = utils::Synthesize::IntegerLiteralExpr(C, (uint64_t)obj);
546 CStyleCast->setSubExpr(newInit);
553 Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
555 const Decl *TD = TCling__GetObjectDecl(obj);
557 QualType QT = C.getPointerType(C.getTypeDeclType(cast<TypeDecl>(TD)));
559 VD = VarDecl::Create(C, fROOTSpecialNamespace, SourceLocation(),
560 SourceLocation(), Name.getAsIdentifierInfo(), QT,
564 = utils::Synthesize::CStyleCastPtrExpr(&SemaR, QT, (uint64_t)obj);
567 fROOTSpecialNamespace->addDecl(VD);
569 cling::CompilationOptions CO;
570 CO.DeclarationExtraction = 0;
571 CO.ValuePrinting = CompilationOptions::VPDisabled;
572 CO.ResultEvaluation = 0;
573 CO.DynamicScoping = 0;
575 CO.CodeGeneration = 1;
577 cling::Transaction* T =
new cling::Transaction(CO, SemaR);
579 T->setState(cling::Transaction::kCompleted);
581 m_Interpreter->emitAllDecls(T);
583 assert(VD &&
"Cannot be null!");
591 bool TClingCallbacks::tryResolveAtRuntimeInternal(LookupResult &R, Scope *S) {
592 if (!fROOTSpecialNamespace) {
597 if (!shouldResolveAtRuntime(R, S))
600 DeclarationName Name = R.getLookupName();
601 IdentifierInfo* II = Name.getAsIdentifierInfo();
602 SourceLocation Loc = R.getNameLoc();
603 Sema& SemaRef = R.getSema();
604 ASTContext& C = SemaRef.getASTContext();
605 DeclContext* TU = C.getTranslationUnitDecl();
606 assert(TU &&
"Must not be null.");
609 clang::FunctionDecl* Wrapper =
nullptr;
612 DeclContext* DCCursor = Cursor->getEntity();
615 Wrapper = dyn_cast_or_null<FunctionDecl>(DCCursor);
617 if (utils::Analyze::IsWrapper(Wrapper)) {
624 }
while ((Cursor = Cursor->getParent()));
631 VarDecl* Result = VarDecl::Create(C, TU, Loc, Loc, II, C.DependentTy,
643 SourceRange invalidRange;
644 Wrapper->addAttr(
new (C) AnnotateAttr(invalidRange, C,
"__ResolveAtRuntime", 0));
648 Sema::ContextRAII pushedDC(SemaRef, TU);
655 bool TClingCallbacks::shouldResolveAtRuntime(LookupResult& R, Scope* S) {
659 if (R.getLookupKind() != Sema::LookupOrdinaryName)
662 if (R.isForRedeclaration())
668 const Transaction* T = getInterpreter()->getCurrentTransaction();
671 const cling::CompilationOptions& COpts = T->getCompilationOpts();
672 if (!COpts.DynamicScoping)
691 for (Scope* DepScope = S; DepScope; DepScope = DepScope->getParent()) {
692 if (DeclContext* Ctx = static_cast<DeclContext*>(DepScope->getEntity())) {
693 if (!Ctx->isDependentContext())
695 if (isa<FunctionDecl>(Ctx))
703 bool TClingCallbacks::tryInjectImplicitAutoKeyword(LookupResult &R, Scope *S) {
704 if (!fROOTSpecialNamespace) {
713 if (R.isForRedeclaration())
716 if (R.getLookupKind() != Sema::LookupOrdinaryName)
719 if (!isa<FunctionDecl>(R.getSema().CurContext))
724 DeclContext* ScopeDC = S->getEntity();
725 if (!ScopeDC || !llvm::isa<FunctionDecl>(ScopeDC))
730 Scope* FnScope = S->getFnParent();
733 auto FD = dyn_cast_or_null<FunctionDecl>(FnScope->getEntity());
734 if (!FD || !utils::Analyze::IsWrapper(FD))
738 Sema& SemaRef = R.getSema();
739 ASTContext& C = SemaRef.getASTContext();
740 DeclContext* DC = SemaRef.CurContext;
741 assert(DC &&
"Must not be null.");
744 Preprocessor& PP = R.getSema().getPreprocessor();
747 if (PP.LookAhead(0).isNot(tok::equal)) {
753 DeclarationName Name = R.getLookupName();
754 IdentifierInfo* II = Name.getAsIdentifierInfo();
755 SourceLocation Loc = R.getNameLoc();
756 VarDecl* Result = VarDecl::Create(C, DC, Loc, Loc, II,
757 C.getAutoType(QualType(),
758 clang::AutoTypeKeyword::Auto,
763 ROOT::TMetaUtils::Error(
"TClingCallbacks::tryInjectImplicitAutoKeyword",
764 "Cannot create VarDecl");
771 SourceRange invalidRange;
772 Result->addAttr(
new (C) AnnotateAttr(invalidRange, C,
"__Auto", 0));
779 void TClingCallbacks::Initialize() {
783 Sema& SemaR = m_Interpreter->getSema();
784 cling::Transaction TPrev((cling::CompilationOptions(), SemaR));
785 TPrev.append(SemaR.getASTContext().getTranslationUnitDecl());
786 TCling__UpdateListsOnCommitted(TPrev, m_Interpreter);
794 void TClingCallbacks::TransactionCommitted(
const Transaction &T) {
795 if (fFirstRun && T.empty())
798 TCling__UpdateListsOnCommitted(T, m_Interpreter);
803 void TClingCallbacks::TransactionUnloaded(
const Transaction &T) {
807 TCling__UpdateListsOnUnloaded(T);
812 void TClingCallbacks::TransactionRollback(
const Transaction &T) {
816 TCling__TransactionRollback(T);
819 void TClingCallbacks::DefinitionShadowed(
const clang::NamedDecl *D) {
820 TCling__InvalidateGlobal(D);
823 void TClingCallbacks::DeclDeserialized(
const clang::Decl* D) {
824 if (
const RecordDecl* RD = dyn_cast<RecordDecl>(D)) {
836 void TClingCallbacks::LibraryLoaded(
const void* dyLibHandle,
837 llvm::StringRef canonicalName) {
838 TCling__LibraryLoadedRTTI(dyLibHandle, canonicalName);
841 void TClingCallbacks::LibraryUnloaded(
const void* dyLibHandle,
842 llvm::StringRef canonicalName) {
843 TCling__LibraryUnloadedRTTI(dyLibHandle, canonicalName);
846 void TClingCallbacks::PrintStackTrace() {
847 TCling__PrintStackTrace();
850 void *TClingCallbacks::EnteringUserCode()
855 return TCling__ResetInterpreterMutex();
858 void TClingCallbacks::ReturnedFromUserCode(
void *stateInfo)
860 TCling__RestoreInterpreterMutex(stateInfo);
863 void *TClingCallbacks::LockCompilationDuringUserCodeExecution()
865 return TCling__LockCompilationDuringUserCodeExecution();
868 void TClingCallbacks::UnlockCompilationDuringUserCodeExecution(
void *StateInfo)
870 TCling__UnlockCompilationDuringUserCodeExecution(StateInfo);
873 static bool shouldIgnore(llvm::StringRef FileName) {
874 llvm::StringRef fileStem = llvm::sys::path::stem(FileName);
875 return fileStem.startswith(
"libNew");
878 static void SearchAndAddPath(
const std::string& Path,
879 std::vector<std::pair<uint32_t, std::string>> &sLibraries, std::vector<std::string> &sPaths,
880 std::unordered_set<std::string>& alreadyLookedPath, cling::DynamicLibraryManager* dyLibManager)
883 auto it = alreadyLookedPath.insert(Path);
886 StringRef DirPath(Path);
887 if (!llvm::sys::fs::is_directory(DirPath))
892 for (llvm::sys::fs::directory_iterator DirIt(DirPath, EC), DirEnd;
893 DirIt != DirEnd && !EC; DirIt.increment(EC)) {
895 std::string FileName(DirIt->path());
896 if (llvm::sys::fs::is_directory(FileName))
898 if (!cling::DynamicLibraryManager::isSharedLibrary(FileName))
902 if (dyLibManager->isLibraryLoaded(FileName.c_str()))
905 if (shouldIgnore(FileName))
908 sLibraries.push_back(std::make_pair(sPaths.size(), llvm::sys::path::filename(FileName)));
913 sPaths.push_back(Path);
923 void TCling__FindLoadedLibraries(std::vector<std::pair<uint32_t, std::string>> &sLibraries,
924 std::vector<std::string> &sPaths,
925 cling::Interpreter &interpreter,
bool searchSystem)
928 static std::unordered_set<std::string> alreadyLookedPath;
929 cling::DynamicLibraryManager* dyLibManager = interpreter.getDynamicLibraryManager();
931 const auto &searchPaths = dyLibManager->getSearchPath();
932 for (
const cling::DynamicLibraryManager::SearchPathInfo &Info : searchPaths) {
933 if (!Info.IsUser && !searchSystem)
935 SearchAndAddPath(Info.Path, sLibraries, sPaths, alreadyLookedPath, dyLibManager);