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"
61 std::string &args, std::string &io, std::string &fname);
64 llvm::StringRef canonicalName);
66 llvm::StringRef canonicalName);
73 std::vector<std::string> &sPaths,
74 cling::Interpreter &interpreter,
bool searchSystem);
78 : InterpreterCallbacks(interp),
79 fLastLookupCtx(0), fROOTSpecialNamespace(0),
80 fFirstRun(true), fIsAutoloading(false), fIsAutoloadingRecursively(false),
81 fIsAutoParsingSuspended(false), fPPOldFlag(false), fPPChanged(false) {
83 m_Interpreter->declare(
"namespace __ROOT_SpecialObjects{}", &
T);
92 llvm::StringRef FileName,
94 clang::CharSourceRange ,
95 const clang::FileEntry *FE,
98 const clang::Module * Imported) {
101 Sema &SemaR = m_Interpreter->getSema();
103 if (!SemaR.isModuleVisible(Imported))
105 "Module %s resolved but not visible!", Imported->Name.c_str());
121 bool isHeaderFile = FileName.endswith(
".h") || FileName.endswith(
".hxx") || FileName.endswith(
".hpp");
125 std::string localString(FileName.str());
127 Sema &SemaR = m_Interpreter->getSema();
128 DeclarationName
Name = &SemaR.getASTContext().Idents.get(localString.c_str());
129 LookupResult RHeader(SemaR,
Name, sLoc, Sema::LookupOrdinaryName);
136 bool permanent,
bool resolved) {
144 llvm::SmallVectorImpl<char> &RecoveryPath) {
152 Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor();
155 std::string filename(FileName.str().substr(0,FileName.str().find_last_of(
'"')));
156 std::string fname, mode, arguments, io;
159 if (mode.length() > 0) {
160 if (llvm::sys::fs::exists(fname)) {
162 std::string options =
"k";
163 if (mode.find(
"++") != std::string::npos) options +=
"f";
164 if (mode.find(
"g") != std::string::npos) options +=
"g";
165 if (mode.find(
"O") != std::string::npos) options +=
"O";
168 Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
169 Parser&
P =
const_cast<Parser&
>(m_Interpreter->getParser());
172 Token& Tok =
const_cast<Token&
>(
P.getCurToken());
177 Tok.setKind(tok::semi);
189 Sema& SemaR = m_Interpreter->getSema();
190 ASTContext&
C = SemaR.getASTContext();
191 Sema::ContextAndScopeRAII pushedDCAndS(SemaR,
C.getTranslationUnitDecl(),
198 fPPOldFlag = PP.GetSuppressIncludeNotFoundError();
199 PP.SetSuppressIncludeNotFoundError(
true);
208 PP.SetSuppressIncludeNotFoundError(
fPPOldFlag);
219 DeclContext* DC =
S->getEntity();
228 clang::DeclContext* MaybeTU = DC;
229 while (MaybeTU && !isa<TranslationUnitDecl>(MaybeTU)) {
231 MaybeTU = MaybeTU->getParent();
233 return isa<FunctionDecl>(DC);
246 if (m_Interpreter->getSema().getDiagnostics().hasErrorOccurred())
285 if (
Name.getNameKind() != DeclarationName::Identifier)
return false;
292 NamespaceDecl* NSD = dyn_cast<NamespaceDecl>(
const_cast<DeclContext*
>(DC));
299 const DeclContext* primaryDC = NSD->getPrimaryContext();
303 Sema &SemaR = m_Interpreter->getSema();
304 LookupResult
R(SemaR,
Name, SourceLocation(), Sema::LookupOrdinaryName);
305 R.suppressDiagnostics();
308 = NSD->getQualifiedNameAsString() +
"::" +
Name.getAsString();
314 clang::Scope
S(SemaR.TUScope, clang::Scope::DeclScope, SemaR.getDiagnostics());
315 S.setEntity(
const_cast<DeclContext*
>(DC));
316 Sema::ContextAndScopeRAII pushedDCAndS(SemaR,
const_cast<DeclContext*
>(DC), &
S);
319 llvm::SmallVector<NamedDecl*, 4> lookupResults;
320 for(LookupResult::iterator
I =
R.begin(),
E =
R.end();
I <
E; ++
I)
321 lookupResults.push_back(*
I);
322 UpdateWithNewDecls(DC,
Name, llvm::makeArrayRef(lookupResults.data(),
323 lookupResults.size()));
333 Sema &SemaR = m_Interpreter->getSema();
335 SourceLocation Loc = Tag->getLocation();
336 if (SemaR.getSourceManager().isInSystemHeader(Loc)) {
341 for (
auto ReRD: Tag->redecls()) {
343 if (ReRD->isBeingDefined())
348 if (RecordDecl* RD = dyn_cast<RecordDecl>(Tag)) {
349 ASTContext&
C = SemaR.getASTContext();
350 Parser&
P =
const_cast<Parser&
>(m_Interpreter->getParser());
356 const ROOT::TMetaUtils::TNormalizedCtxt* tNormCtxt = NULL;
359 C.getTypeDeclType(RD),
365 Tag->setHasExternalLexicalStorage(
false);
381 Scope *
S,
const FileEntry* FE ) {
382 Sema &SemaR = m_Interpreter->getSema();
391 Sema::LookupNameKind kind =
R.getLookupKind();
392 if (!(kind == Sema::LookupTagName || kind == Sema::LookupOrdinaryName
393 || kind == Sema::LookupNestedNameSpecifierName
394 || kind == Sema::LookupNamespaceName))
399 bool lookupSuccess =
false;
401 Parser &
P =
const_cast<Parser &
>(m_Interpreter->getParser());
408 lookupSuccess = SemaR.LookupName(
R,
S);
410 if (
R.isSingleResult()) {
411 if (isa<clang::RecordDecl>(
R.getFoundDecl())) {
427 lookupSuccess = FE || SemaR.LookupName(
R,
S);
433 std::string incl =
"#include \"";
434 incl += FE->getName();
436 m_Interpreter->declare(incl);
467 if (
R.isForRedeclaration())
472 const Sema::LookupNameKind LookupKind =
R.getLookupKind();
473 if (LookupKind != Sema::LookupOrdinaryName)
477 Sema &SemaR = m_Interpreter->getSema();
478 ASTContext&
C = SemaR.getASTContext();
479 Preprocessor &PP = SemaR.getPreprocessor();
480 DeclContext *CurDC = SemaR.CurContext;
481 DeclarationName
Name =
R.getLookupName();
484 if(!CurDC || !CurDC->isFunctionOrMethod())
489 Preprocessor::CleanupAndRestoreCacheRAII cleanupPPRAII(PP);
496#if defined(R__MUST_REVISIT)
497#if R__MUST_REVISIT(6,2)
502 if (!fgSetOfSpecials) {
503 fgSetOfSpecials =
new std::set<TObject*>;
505 ((std::set<TObject*>*)fgSetOfSpecials)->insert((
TObject*)*obj);
509 VarDecl *VD = cast_or_null<VarDecl>(utils::Lookup::Named(&SemaR,
Name,
514 TObject **address = (
TObject**)m_Interpreter->getAddressOfGlobal(GD);
518 CStyleCastExpr *CStyleCast = cast<CStyleCastExpr>(VD->getInit());
519 Expr* newInit = utils::Synthesize::IntegerLiteralExpr(
C, (uint64_t)obj);
520 CStyleCast->setSubExpr(newInit);
527 Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
531 QualType QT =
C.getPointerType(
C.getTypeDeclType(cast<TypeDecl>(TD)));
534 SourceLocation(),
Name.getAsIdentifierInfo(), QT,
538 = utils::Synthesize::CStyleCastPtrExpr(&SemaR, QT, (uint64_t)obj);
543 cling::CompilationOptions CO;
544 CO.DeclarationExtraction = 0;
545 CO.ValuePrinting = CompilationOptions::VPDisabled;
546 CO.ResultEvaluation = 0;
547 CO.DynamicScoping = 0;
549 CO.CodeGeneration = 1;
551 cling::Transaction*
T =
new cling::Transaction(CO, SemaR);
553 T->setState(cling::Transaction::kCompleted);
555 m_Interpreter->emitAllDecls(
T);
557 assert(VD &&
"Cannot be null!");
569 DeclarationName
Name =
R.getLookupName();
570 IdentifierInfo* II =
Name.getAsIdentifierInfo();
571 SourceLocation Loc =
R.getNameLoc();
572 Sema& SemaRef =
R.getSema();
573 ASTContext&
C = SemaRef.getASTContext();
574 DeclContext* TU =
C.getTranslationUnitDecl();
575 assert(TU &&
"Must not be null.");
578 clang::FunctionDecl* Wrapper =
nullptr;
581 DeclContext* DCCursor =
Cursor->getEntity();
584 Wrapper = dyn_cast_or_null<FunctionDecl>(DCCursor);
586 if (utils::Analyze::IsWrapper(Wrapper)) {
600 VarDecl* Result = VarDecl::Create(
C, TU, Loc, Loc, II,
C.DependentTy,
612 SourceRange invalidRange;
613 Wrapper->addAttr(
new (
C) AnnotateAttr(invalidRange,
C,
"__ResolveAtRuntime", 0));
617 Sema::ContextRAII pushedDC(SemaRef, TU);
628 if (
R.getLookupKind() != Sema::LookupOrdinaryName)
631 if (
R.isForRedeclaration())
637 const Transaction*
T = getInterpreter()->getCurrentTransaction();
640 const cling::CompilationOptions& COpts =
T->getCompilationOpts();
641 if (!COpts.DynamicScoping)
660 for (Scope* DepScope =
S; DepScope; DepScope = DepScope->getParent()) {
661 if (DeclContext* Ctx =
static_cast<DeclContext*
>(DepScope->getEntity())) {
662 if (!Ctx->isDependentContext())
664 if (isa<FunctionDecl>(Ctx))
677 if (
R.isForRedeclaration())
680 if (
R.getLookupKind() != Sema::LookupOrdinaryName)
683 if (!isa<FunctionDecl>(
R.getSema().CurContext))
688 DeclContext* ScopeDC =
S->getEntity();
689 if (!ScopeDC || !llvm::isa<FunctionDecl>(ScopeDC))
694 Scope* FnScope =
S->getFnParent();
697 auto FD = dyn_cast_or_null<FunctionDecl>(FnScope->getEntity());
698 if (!FD || !utils::Analyze::IsWrapper(FD))
702 Sema& SemaRef =
R.getSema();
703 ASTContext&
C = SemaRef.getASTContext();
704 DeclContext* DC = SemaRef.CurContext;
705 assert(DC &&
"Must not be null.");
708 Preprocessor& PP =
R.getSema().getPreprocessor();
711 if (PP.LookAhead(0).isNot(tok::equal)) {
717 DeclarationName
Name =
R.getLookupName();
718 IdentifierInfo* II =
Name.getAsIdentifierInfo();
719 SourceLocation Loc =
R.getNameLoc();
720 VarDecl* Result = VarDecl::Create(
C, DC, Loc, Loc, II,
721 C.getAutoType(QualType(),
722 clang::AutoTypeKeyword::Auto,
728 "Cannot create VarDecl");
735 SourceRange invalidRange;
736 Result->addAttr(
new (
C) AnnotateAttr(invalidRange,
C,
"__Auto", 0));
747 Sema& SemaR = m_Interpreter->getSema();
748 cling::Transaction TPrev((cling::CompilationOptions(), SemaR));
749 TPrev.append(SemaR.getASTContext().getTranslationUnitDecl());
784 if (
const RecordDecl* RD = dyn_cast<RecordDecl>(D)) {
797 llvm::StringRef canonicalName) {
802 llvm::StringRef canonicalName) {
834 std::vector<std::pair<uint32_t, std::string>> &sLibraries, std::vector<std::string> &sPaths,
835 std::unordered_set<std::string>& alreadyLookedPath, cling::DynamicLibraryManager* dyLibManager)
838 auto it = alreadyLookedPath.insert(Path);
841 StringRef DirPath(Path);
845 if (!llvm::sys::fs::is_directory(DirPath) || Path ==
".")
850 for (llvm::sys::fs::directory_iterator DirIt(DirPath, EC), DirEnd;
851 DirIt != DirEnd && !EC; DirIt.increment(EC)) {
853 std::string FileName(DirIt->path());
858 if (dyLibManager->isLibraryLoaded(FileName.c_str()))
860 sLibraries.push_back(std::make_pair(sPaths.size(), llvm::sys::path::filename(FileName)));
866 sPaths.push_back(Path);
877 std::vector<std::string> &sPaths,
878 cling::Interpreter &interpreter,
bool searchSystem)
881 static std::unordered_set<std::string> alreadyLookedPath;
882 const clang::Preprocessor &PP = interpreter.getCI()->getPreprocessor();
883 const HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts();
884 cling::DynamicLibraryManager* dyLibManager = interpreter.getDynamicLibraryManager();
887 llvm::SmallVector<std::string, 32> systemPath = dyLibManager->getSystemSearchPath();
888 for (
const std::string& sysPath : systemPath) {
889 SearchAndAddPath(sysPath, sLibraries, sPaths, alreadyLookedPath, dyLibManager);
892 const std::vector<std::string>& MPaths = HSOpts.PrebuiltModulePaths;
894 for (
const std::string& mPath : MPaths) {
895 SearchAndAddPath(mPath, sLibraries, sPaths, alreadyLookedPath, dyLibManager);
#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)
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__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,...)
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)
TClingCallbacks(cling::Interpreter *interp)
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)
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)
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