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/Object/ELFObjectFile.h"
34#include "llvm/Object/ObjectFile.h"
35#include "llvm/Support/FileSystem.h"
36#include "llvm/Support/Path.h"
38#include "TClingUtils.h"
64 std::string &args, std::string &io, std::string &fname);
67 llvm::StringRef canonicalName);
69 llvm::StringRef canonicalName);
76 std::vector<std::string> &sPaths,
77 cling::Interpreter &interpreter,
bool searchSystem);
81 : InterpreterCallbacks(interp),
82 fLastLookupCtx(0), fROOTSpecialNamespace(0),
83 fFirstRun(true), fIsAutoloading(false), fIsAutoloadingRecursively(false),
84 fIsAutoParsingSuspended(false), fPPOldFlag(false), fPPChanged(false) {
87 m_Interpreter->declare(
"namespace __ROOT_SpecialObjects{}", &
T);
97 llvm::StringRef FileName,
99 clang::CharSourceRange ,
100 const clang::FileEntry *FE,
103 const clang::Module * Imported) {
105 Sema &SemaR = m_Interpreter->getSema();
108 if (!SemaR.isModuleVisible(Imported))
110 "Module %s resolved but not visible!", Imported->Name.c_str());
126 bool isHeaderFile = FileName.endswith(
".h") || FileName.endswith(
".hxx") || FileName.endswith(
".hpp");
130 std::string localString(FileName.str());
132 DeclarationName
Name = &SemaR.getASTContext().Idents.get(localString.c_str());
133 LookupResult RHeader(SemaR,
Name, sLoc, Sema::LookupOrdinaryName);
140 bool permanent,
bool resolved) {
148 llvm::SmallVectorImpl<char> &RecoveryPath) {
156 Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor();
159 std::string filename(FileName.str().substr(0,FileName.str().find_last_of(
'"')));
160 std::string fname, mode, arguments, io;
163 if (mode.length() > 0) {
164 if (llvm::sys::fs::exists(fname)) {
166 std::string options =
"k";
167 if (mode.find(
"++") != std::string::npos) options +=
"f";
168 if (mode.find(
"g") != std::string::npos) options +=
"g";
169 if (mode.find(
"O") != std::string::npos) options +=
"O";
172 Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
173 Parser&
P =
const_cast<Parser&
>(m_Interpreter->getParser());
176 Token& Tok =
const_cast<Token&
>(
P.getCurToken());
181 Tok.setKind(tok::semi);
193 Sema& SemaR = m_Interpreter->getSema();
194 ASTContext&
C = SemaR.getASTContext();
195 Sema::ContextAndScopeRAII pushedDCAndS(SemaR,
C.getTranslationUnitDecl(),
202 fPPOldFlag = PP.GetSuppressIncludeNotFoundError();
203 PP.SetSuppressIncludeNotFoundError(
true);
212 PP.SetSuppressIncludeNotFoundError(
fPPOldFlag);
223 DeclContext* DC =
S->getEntity();
232 clang::DeclContext* MaybeTU = DC;
233 while (MaybeTU && !isa<TranslationUnitDecl>(MaybeTU)) {
235 MaybeTU = MaybeTU->getParent();
237 return isa<FunctionDecl>(DC);
255 if (m_Interpreter->getSema().getDiagnostics().hasErrorOccurred())
299 if (
Name.getNameKind() != DeclarationName::Identifier)
return false;
306 NamespaceDecl* NSD = dyn_cast<NamespaceDecl>(
const_cast<DeclContext*
>(DC));
313 const DeclContext* primaryDC = NSD->getPrimaryContext();
317 Sema &SemaR = m_Interpreter->getSema();
318 LookupResult
R(SemaR,
Name, SourceLocation(), Sema::LookupOrdinaryName);
319 R.suppressDiagnostics();
322 = NSD->getQualifiedNameAsString() +
"::" +
Name.getAsString();
328 clang::Scope
S(SemaR.TUScope, clang::Scope::DeclScope, SemaR.getDiagnostics());
329 S.setEntity(
const_cast<DeclContext*
>(DC));
330 Sema::ContextAndScopeRAII pushedDCAndS(SemaR,
const_cast<DeclContext*
>(DC), &
S);
333 llvm::SmallVector<NamedDecl*, 4> lookupResults;
334 for(LookupResult::iterator
I =
R.begin(),
E =
R.end();
I <
E; ++
I)
335 lookupResults.push_back(*
I);
336 UpdateWithNewDecls(DC,
Name, llvm::makeArrayRef(lookupResults.data(),
337 lookupResults.size()));
352 Sema &SemaR = m_Interpreter->getSema();
354 SourceLocation Loc = Tag->getLocation();
355 if (SemaR.getSourceManager().isInSystemHeader(Loc)) {
360 for (
auto ReRD: Tag->redecls()) {
362 if (ReRD->isBeingDefined())
367 if (RecordDecl* RD = dyn_cast<RecordDecl>(Tag)) {
368 ASTContext&
C = SemaR.getASTContext();
369 Parser&
P =
const_cast<Parser&
>(m_Interpreter->getParser());
375 const ROOT::TMetaUtils::TNormalizedCtxt* tNormCtxt = NULL;
378 C.getTypeDeclType(RD),
384 Tag->setHasExternalLexicalStorage(
false);
400 Scope *
S,
const FileEntry* FE ) {
406 Sema &SemaR = m_Interpreter->getSema();
415 Sema::LookupNameKind kind =
R.getLookupKind();
416 if (!(kind == Sema::LookupTagName || kind == Sema::LookupOrdinaryName
417 || kind == Sema::LookupNestedNameSpecifierName
418 || kind == Sema::LookupNamespaceName))
423 bool lookupSuccess =
false;
425 Parser &
P =
const_cast<Parser &
>(m_Interpreter->getParser());
432 lookupSuccess = SemaR.LookupName(
R,
S);
434 if (
R.isSingleResult()) {
435 if (isa<clang::RecordDecl>(
R.getFoundDecl())) {
451 lookupSuccess = FE || SemaR.LookupName(
R,
S);
457 std::string incl =
"#include \"";
458 incl += FE->getName();
460 m_Interpreter->declare(incl);
496 if (
R.isForRedeclaration())
501 const Sema::LookupNameKind LookupKind =
R.getLookupKind();
502 if (LookupKind != Sema::LookupOrdinaryName)
506 Sema &SemaR = m_Interpreter->getSema();
507 ASTContext&
C = SemaR.getASTContext();
508 Preprocessor &PP = SemaR.getPreprocessor();
509 DeclContext *CurDC = SemaR.CurContext;
510 DeclarationName
Name =
R.getLookupName();
513 if(!CurDC || !CurDC->isFunctionOrMethod())
518 Preprocessor::CleanupAndRestoreCacheRAII cleanupPPRAII(PP);
525#if defined(R__MUST_REVISIT)
526#if R__MUST_REVISIT(6,2)
531 if (!fgSetOfSpecials) {
532 fgSetOfSpecials =
new std::set<TObject*>;
534 ((std::set<TObject*>*)fgSetOfSpecials)->insert((
TObject*)*obj);
538 VarDecl *VD = cast_or_null<VarDecl>(utils::Lookup::Named(&SemaR,
Name,
543 TObject **address = (
TObject**)m_Interpreter->getAddressOfGlobal(GD);
547 CStyleCastExpr *CStyleCast = cast<CStyleCastExpr>(VD->getInit());
548 Expr* newInit = utils::Synthesize::IntegerLiteralExpr(
C, (uint64_t)obj);
549 CStyleCast->setSubExpr(newInit);
556 Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
560 QualType QT =
C.getPointerType(
C.getTypeDeclType(cast<TypeDecl>(TD)));
563 SourceLocation(),
Name.getAsIdentifierInfo(), QT,
567 = utils::Synthesize::CStyleCastPtrExpr(&SemaR, QT, (uint64_t)obj);
572 cling::CompilationOptions CO;
573 CO.DeclarationExtraction = 0;
574 CO.ValuePrinting = CompilationOptions::VPDisabled;
575 CO.ResultEvaluation = 0;
576 CO.DynamicScoping = 0;
578 CO.CodeGeneration = 1;
580 cling::Transaction*
T =
new cling::Transaction(CO, SemaR);
582 T->setState(cling::Transaction::kCompleted);
584 m_Interpreter->emitAllDecls(
T);
586 assert(VD &&
"Cannot be null!");
603 DeclarationName
Name =
R.getLookupName();
604 IdentifierInfo* II =
Name.getAsIdentifierInfo();
605 SourceLocation Loc =
R.getNameLoc();
606 Sema& SemaRef =
R.getSema();
607 ASTContext&
C = SemaRef.getASTContext();
608 DeclContext* TU =
C.getTranslationUnitDecl();
609 assert(TU &&
"Must not be null.");
612 clang::FunctionDecl* Wrapper =
nullptr;
615 DeclContext* DCCursor =
Cursor->getEntity();
618 Wrapper = dyn_cast_or_null<FunctionDecl>(DCCursor);
620 if (utils::Analyze::IsWrapper(Wrapper)) {
634 VarDecl* Result = VarDecl::Create(
C, TU, Loc, Loc, II,
C.DependentTy,
646 SourceRange invalidRange;
647 Wrapper->addAttr(
new (
C) AnnotateAttr(invalidRange,
C,
"__ResolveAtRuntime", 0));
651 Sema::ContextRAII pushedDC(SemaRef, TU);
662 if (
R.getLookupKind() != Sema::LookupOrdinaryName)
665 if (
R.isForRedeclaration())
671 const Transaction*
T = getInterpreter()->getCurrentTransaction();
674 const cling::CompilationOptions& COpts =
T->getCompilationOpts();
675 if (!COpts.DynamicScoping)
694 for (Scope* DepScope =
S; DepScope; DepScope = DepScope->getParent()) {
695 if (DeclContext* Ctx =
static_cast<DeclContext*
>(DepScope->getEntity())) {
696 if (!Ctx->isDependentContext())
698 if (isa<FunctionDecl>(Ctx))
716 if (
R.isForRedeclaration())
719 if (
R.getLookupKind() != Sema::LookupOrdinaryName)
722 if (!isa<FunctionDecl>(
R.getSema().CurContext))
727 DeclContext* ScopeDC =
S->getEntity();
728 if (!ScopeDC || !llvm::isa<FunctionDecl>(ScopeDC))
733 Scope* FnScope =
S->getFnParent();
736 auto FD = dyn_cast_or_null<FunctionDecl>(FnScope->getEntity());
737 if (!FD || !utils::Analyze::IsWrapper(FD))
741 Sema& SemaRef =
R.getSema();
742 ASTContext&
C = SemaRef.getASTContext();
743 DeclContext* DC = SemaRef.CurContext;
744 assert(DC &&
"Must not be null.");
747 Preprocessor& PP =
R.getSema().getPreprocessor();
750 if (PP.LookAhead(0).isNot(tok::equal)) {
756 DeclarationName
Name =
R.getLookupName();
757 IdentifierInfo* II =
Name.getAsIdentifierInfo();
758 SourceLocation Loc =
R.getNameLoc();
759 VarDecl* Result = VarDecl::Create(
C, DC, Loc, Loc, II,
760 C.getAutoType(QualType(),
761 clang::AutoTypeKeyword::Auto,
767 "Cannot create VarDecl");
774 SourceRange invalidRange;
775 Result->addAttr(
new (
C) AnnotateAttr(invalidRange,
C,
"__Auto", 0));
786 Sema& SemaR = m_Interpreter->getSema();
787 cling::Transaction TPrev((cling::CompilationOptions(), SemaR));
788 TPrev.append(SemaR.getASTContext().getTranslationUnitDecl());
827 if (
const RecordDecl* RD = dyn_cast<RecordDecl>(D)) {
840 llvm::StringRef canonicalName) {
845 llvm::StringRef canonicalName) {
877 const cling::DynamicLibraryManager& dyLibManager) {
878 if (llvm::sys::fs::is_directory(FileName))
881 if (!cling::DynamicLibraryManager::isSharedLibrary(FileName))
886 if (dyLibManager.isLibraryLoaded(FileName.c_str()))
890 auto ObjF = llvm::object::ObjectFile::createObjectFile(FileName);
898 llvm::object::ObjectFile *
file = ObjF.get().getBinary();
900 if (isa<llvm::object::ELFObjectFileBase>(*
file)) {
901 for (
auto S :
file->sections()) {
904 if (
name ==
".text") {
909 auto SecRef =
static_cast<llvm::object::ELFSectionRef&
>(
S);
910 if (SecRef.getType() == llvm::ELF::SHT_NOBITS)
913 return (SecRef.getFlags() & llvm::ELF::SHF_ALLOC) == 0;
920 llvm::StringRef fileStem = llvm::sys::path::stem(FileName);
921 return fileStem.startswith(
"libNew");
925 std::vector<std::pair<uint32_t, std::string>> &sLibraries, std::vector<std::string> &sPaths,
926 std::unordered_set<std::string>& alreadyLookedPath, cling::DynamicLibraryManager* dyLibManager)
929 auto it = alreadyLookedPath.insert(Path);
932 StringRef DirPath(Path);
933 if (!llvm::sys::fs::is_directory(DirPath))
938 for (llvm::sys::fs::directory_iterator DirIt(DirPath, EC), DirEnd;
939 DirIt != DirEnd && !EC; DirIt.increment(EC)) {
941 std::string FileName(DirIt->path());
945 sLibraries.push_back(std::make_pair(sPaths.size(), llvm::sys::path::filename(FileName)));
950 sPaths.push_back(Path);
961 std::vector<std::string> &sPaths,
962 cling::Interpreter &interpreter,
bool searchSystem)
965 static std::unordered_set<std::string> alreadyLookedPath;
966 cling::DynamicLibraryManager* dyLibManager = interpreter.getDynamicLibraryManager();
968 const auto &searchPaths = dyLibManager->getSearchPath();
969 for (
const cling::DynamicLibraryManager::SearchPathInfo &
Info : searchPaths) {
970 if (!
Info.IsUser && !searchSystem)
#define R(a, b, c, d, e, f, g, h, i)
bool TCling__LibraryLoadingFailed(const std::string &, const std::string &, bool, bool)
Lookup libraries in LD_LIBRARY_PATH and DYLD_LIBRARY_PATH with mangled_name, which is extracted by er...
static void SearchAndAddPath(const std::string &Path, std::vector< std::pair< uint32_t, std::string > > &sLibraries, std::vector< std::string > &sPaths, std::unordered_set< std::string > &alreadyLookedPath, cling::DynamicLibraryManager *dyLibManager)
void TCling__FindLoadedLibraries(std::vector< std::pair< uint32_t, std::string > > &sLibraries, std::vector< std::string > &sPaths, cling::Interpreter &interpreter, bool searchSystem)
static bool shouldIgnore(const std::string &FileName, const cling::DynamicLibraryManager &dyLibManager)
void * TCling__LockCompilationDuringUserCodeExecution()
Lock the interpreter.
void TCling__UpdateListsOnCommitted(const cling::Transaction &, Interpreter *)
void TCling__SplitAclicMode(const char *fileName, std::string &mode, std::string &args, std::string &io, std::string &fname)
void TCling__TransactionRollback(const cling::Transaction &)
const char * TCling__GetClassSharedLibs(const char *className)
int TCling__AutoParseCallback(const char *className)
Decl * TCling__GetObjectDecl(TObject *obj)
void TCling__GetNormalizedContext(const ROOT::TMetaUtils::TNormalizedCtxt *&)
void TCling__RestoreInterpreterMutex(void *state)
Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
int TCling__CompileMacro(const char *fileName, const char *options)
void * TCling__ResetInterpreterMutex()
Reset the interpreter lock to the state it had before interpreter-related calls happened.
int TCling__AutoLoadCallback(const char *className)
void TCling__LibraryUnloadedRTTI(const void *dyLibHandle, llvm::StringRef canonicalName)
void TCling__PrintStackTrace()
Print a StackTrace!
int TCling__IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl *name)
void TCling__UpdateListsOnUnloaded(const cling::Transaction &)
void TCling__UnlockCompilationDuringUserCodeExecution(void *state)
Unlock the interpreter.
static bool topmostDCIsFunction(Scope *S)
void TCling__InvalidateGlobal(const clang::Decl *)
void TCling__LibraryLoadedRTTI(const void *dyLibHandle, llvm::StringRef canonicalName)
TObject * TCling__GetObjectAddress(const char *Name, void *&LookupCtx)
void Info(const char *location, const char *msgfmt,...)
void Error(const char *location, const char *msgfmt,...)
void Warning(const char *location, const char *msgfmt,...)
typedef void((*Func_t)())
virtual void LibraryUnloaded(const void *dyLibHandle, llvm::StringRef canonicalName)
virtual void * LockCompilationDuringUserCodeExecution()
bool tryAutoParseInternal(llvm::StringRef Name, clang::LookupResult &R, clang::Scope *S, const clang::FileEntry *FE=0)
bool tryFindROOTSpecialInternal(clang::LookupResult &R, clang::Scope *S)
virtual bool LookupObject(clang::LookupResult &R, clang::Scope *S)
bool fIsAutoParsingSuspended
bool tryResolveAtRuntimeInternal(clang::LookupResult &R, clang::Scope *S)
virtual bool LibraryLoadingFailed(const std::string &, const std::string &, bool, bool)
virtual void LibraryLoaded(const void *dyLibHandle, llvm::StringRef canonicalName)
virtual void DeclDeserialized(const clang::Decl *D)
virtual void ReturnedFromUserCode(void *stateInfo)
bool tryInjectImplicitAutoKeyword(clang::LookupResult &R, clang::Scope *S)
clang::NamespaceDecl * fROOTSpecialNamespace
virtual void InclusionDirective(clang::SourceLocation, const clang::Token &, llvm::StringRef FileName, bool, clang::CharSourceRange, const clang::FileEntry *, llvm::StringRef, llvm::StringRef, const clang::Module *)
virtual void UnlockCompilationDuringUserCodeExecution(void *StateInfo)
TClingCallbacks(cling::Interpreter *interp, bool hasCodeGen)
virtual void TransactionRollback(const cling::Transaction &T)
virtual void TransactionUnloaded(const cling::Transaction &T)
virtual void PrintStackTrace()
bool IsAutoloadingEnabled()
virtual bool FileNotFound(llvm::StringRef FileName, llvm::SmallVectorImpl< char > &RecoveryPath)
virtual void * EnteringUserCode()
virtual void TransactionCommitted(const cling::Transaction &T)
bool fIsAutoloadingRecursively
bool shouldResolveAtRuntime(clang::LookupResult &R, clang::Scope *S)
virtual void DefinitionShadowed(const clang::NamedDecl *D)
A previous definition has been shadowed; invalidate TCling' stored data about the old (global) decl.
Mother of all ROOT objects.
RooArgSet S(const RooAbsArg &v1)
void Init(TClassEdit::TInterpreterLookupHelper *helper)
void GetNormalizedName(std::string &norm_name, std::string_view name)
Return the normalized name.
constexpr Double_t E()
Base of natural log:
RAII used to store Parser, Sema, Preprocessor state for recursive parsing.
clang::Preprocessor::CleanupAndRestoreCacheRAII fCleanupRAII
clang::Sema::ContextAndScopeRAII fPushedDCAndS