Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TClingCallbacks.cxx
Go to the documentation of this file.
1// @(#)root/core/meta:$Id$
2// Author: Vassil Vassilev 7/10/2012
3
4/*************************************************************************
5 * Copyright (C) 1995-2012, Rene Brun and Fons Rademakers. *
6 * All rights reserved. *
7 * *
8 * For the licensing terms see $ROOTSYS/LICENSE. *
9 * For the list of contributors see $ROOTSYS/README/CREDITS. *
10 *************************************************************************/
11
12#include "TClingCallbacks.h"
13
15
16#include "cling/Interpreter/DynamicLibraryManager.h"
17#include "cling/Interpreter/Interpreter.h"
18#include "cling/Interpreter/InterpreterCallbacks.h"
19#include "cling/Interpreter/Transaction.h"
20#include "cling/Utils/AST.h"
21
22#include "clang/AST/ASTConsumer.h"
23#include "clang/AST/ASTContext.h"
24#include "clang/AST/DeclBase.h"
25#include "clang/AST/DeclTemplate.h"
26#include "clang/AST/GlobalDecl.h"
27#include "clang/Frontend/CompilerInstance.h"
28#include "clang/Lex/HeaderSearch.h"
29#include "clang/Lex/PPCallbacks.h"
30#include "clang/Lex/Preprocessor.h"
31#include "clang/Parse/Parser.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Scope.h"
34#include "clang/Serialization/ASTReader.h"
35#include "clang/Serialization/GlobalModuleIndex.h"
36#include "clang/Basic/DiagnosticSema.h"
37
38#include "llvm/ExecutionEngine/Orc/Core.h"
39
40#include "llvm/Support/Error.h"
41#include "llvm/Support/FileSystem.h"
42#include "llvm/Support/Path.h"
43#include "llvm/Support/Process.h"
44
45#include "TClingUtils.h"
46#include "ClingRAII.h"
47
48#include <optional>
49
50using namespace clang;
51using namespace cling;
52using namespace ROOT::Internal;
53
55class TObject;
56
57// Functions used to forward calls from code compiled with no-rtti to code
58// compiled with rtti.
59extern "C" {
60 void TCling__UpdateListsOnCommitted(const cling::Transaction&, Interpreter*);
61 void TCling__UpdateListsOnUnloaded(const cling::Transaction&);
62 void TCling__InvalidateGlobal(const clang::Decl*);
63 void TCling__TransactionRollback(const cling::Transaction&);
65 TObject* TCling__GetObjectAddress(const char *Name, void *&LookupCtx);
67 int TCling__AutoLoadCallback(const char* className);
68 int TCling__AutoParseCallback(const char* className);
69 const char* TCling__GetClassSharedLibs(const char* className);
70 int TCling__IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl* name);
71 int TCling__CompileMacro(const char *fileName, const char *options);
72 void TCling__SplitAclicMode(const char* fileName, std::string &mode,
73 std::string &args, std::string &io, std::string &fname);
74 int TCling__LoadLibrary(const char *library);
75 bool TCling__LibraryLoadingFailed(const std::string&, const std::string&, bool, bool);
76 void TCling__LibraryLoadedRTTI(const void* dyLibHandle,
77 llvm::StringRef canonicalName);
78 void TCling__LibraryUnloadedRTTI(const void* dyLibHandle,
79 llvm::StringRef canonicalName);
82 void TCling__RestoreInterpreterMutex(void *state);
85}
86
89 cling::Interpreter *fInterpreter;
90public:
91 AutoloadLibraryGenerator(cling::Interpreter *interp, const TClingCallbacks& cb)
92 : fCallbacks(cb), fInterpreter(interp) {}
93
94 llvm::Error tryToGenerate(llvm::orc::LookupState &LS, llvm::orc::LookupKind K, llvm::orc::JITDylib &JD,
95 llvm::orc::JITDylibLookupFlags JDLookupFlags,
96 const llvm::orc::SymbolLookupSet &Symbols) override
97 {
99 return llvm::Error::success();
100
101 // If we get here, the symbols have not been found in the current process,
102 // so no need to check that again. Instead search for the library that
103 // provides the symbol and create one MaterializationUnit per library to
104 // actually load it if needed.
105 std::unordered_map<std::string, llvm::orc::SymbolNameVector> found;
106
107 // TODO: Do we need to take gInterpreterMutex?
108 // R__LOCKGUARD(gInterpreterMutex);
109
110 for (auto &&KV : Symbols) {
111 llvm::orc::SymbolStringPtr name = KV.first;
112
113 const cling::DynamicLibraryManager &DLM = *fInterpreter->getDynamicLibraryManager();
114
115 std::string libName = DLM.searchLibrariesForSymbol((*name).str(),
116 /*searchSystem=*/true);
117
118 // libNew overrides memory management functions; must never autoload that.
119 assert(libName.find("/libNew.") == std::string::npos && "We must not autoload libNew!");
120
121 // libCling symbols are intentionally hidden from the process, and libCling must not be
122 // dlopened. Instead, symbols must be resolved by specifically querying the dynlib handle of
123 // libCling, which by definition is loaded - else we could not call this code. The handle
124 // is made available as argument to `CreateInterpreter`.
125 assert(libName.find("/libCling.") == std::string::npos && "Must not autoload libCling!");
126
127 if (!libName.empty())
128 found[libName].push_back(name);
129 }
130
131 llvm::orc::SymbolMap loadedSymbols;
132 for (const auto &KV : found) {
133 // Try to load the library which should provide the symbol definition.
134 // TODO: Should this interface with the DynamicLibraryManager directly?
135 if (TCling__LoadLibrary(KV.first.c_str()) < 0) {
136 ROOT::TMetaUtils::Error("AutoloadLibraryMU", "Failed to load library %s", KV.first.c_str());
137 }
138
139 for (const auto &symbol : KV.second) {
140 std::string symbolStr = (*symbol).str();
141 std::string nameForDlsym = ROOT::TMetaUtils::DemangleNameForDlsym(symbolStr);
142
143 void *addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(nameForDlsym);
144 if (addr) {
145 loadedSymbols[symbol] = {llvm::orc::ExecutorAddr::fromPtr(addr), llvm::JITSymbolFlags::Exported};
146 }
147 }
148 }
149
150 if (!loadedSymbols.empty()) {
151 return JD.define(absoluteSymbols(std::move(loadedSymbols)));
152 }
153
154 return llvm::Error::success();
155 }
156};
157
158TClingCallbacks::TClingCallbacks(cling::Interpreter *interp, bool hasCodeGen) : InterpreterCallbacks(interp)
159{
160 if (hasCodeGen) {
161 Transaction* T = nullptr;
162 m_Interpreter->declare("namespace __ROOT_SpecialObjects{}", &T);
163 fROOTSpecialNamespace = dyn_cast<NamespaceDecl>(T->getFirstDecl().getSingleDecl());
164
165 interp->addGenerator(std::make_unique<AutoloadLibraryGenerator>(interp, *this));
166 }
167}
168
169//pin the vtable here
171
172void TClingCallbacks::InclusionDirective(clang::SourceLocation sLoc/*HashLoc*/,
173 const clang::Token &/*IncludeTok*/,
174 llvm::StringRef FileName,
175 bool /*IsAngled*/,
176 clang::CharSourceRange /*FilenameRange*/,
177 clang::OptionalFileEntryRef FE,
178 llvm::StringRef /*SearchPath*/,
179 llvm::StringRef /*RelativePath*/,
180 const clang::Module * Imported,
181 clang::SrcMgr::CharacteristicKind FileType) {
182 // We found a module. Do not try to do anything else.
183 Sema &SemaR = m_Interpreter->getSema();
184 if (Imported) {
185 // FIXME: We should make the module visible at that point.
186 if (!SemaR.isModuleVisible(Imported))
187 ROOT::TMetaUtils::Info("TClingCallbacks::InclusionDirective",
188 "Module %s resolved but not visible!", Imported->Name.c_str());
189 else
190 return;
191 }
192
193 // Method called via Callbacks->InclusionDirective()
194 // in Preprocessor::HandleIncludeDirective(), invoked whenever an
195 // inclusion directive has been processed, and allowing us to try
196 // to autoload libraries using their header file name.
197 // Two strategies are tried:
198 // 1) The header name is looked for in the list of autoload keys
199 // 2) Heurists are applied to the header name to distill a classname.
200 // For example try to autoload TGClient (libGui) when seeing #include "TGClient.h"
201 // or TH1F in presence of TH1F.h.
202 // Strategy 2) is tried only if 1) fails.
203
204 bool isHeaderFile = FileName.endswith(".h") || FileName.endswith(".hxx") || FileName.endswith(".hpp");
205 if (!IsAutoLoadingEnabled() || fIsAutoLoadingRecursively || !isHeaderFile)
206 return;
207
208 std::string localString(FileName.str());
209
210 DeclarationName Name = &SemaR.getASTContext().Idents.get(localString.c_str());
211 LookupResult RHeader(SemaR, Name, sLoc, Sema::LookupOrdinaryName);
212
213 tryAutoParseInternal(localString, RHeader, SemaR.getCurScope(), FE);
214}
215
216// TCling__LibraryLoadingFailed is a function in TCling which handles errmessage
217bool TClingCallbacks::LibraryLoadingFailed(const std::string& errmessage, const std::string& libStem,
218 bool permanent, bool resolved) {
219 return TCling__LibraryLoadingFailed(errmessage, libStem, permanent, resolved);
220}
221
222// Preprocessor callbacks used to handle special cases like for example:
223// #include "myMacro.C+"
224//
225bool TClingCallbacks::FileNotFound(llvm::StringRef FileName) {
226 // Method called via Callbacks->FileNotFound(Filename)
227 // in Preprocessor::HandleIncludeDirective(), initially allowing to
228 // change the include path, and allowing us to compile code via ACLiC
229 // when specifying #include "myfile.C+", and suppressing the preprocessor
230 // error message:
231 // input_line_23:1:10: fatal error: 'myfile.C+' file not found
232
233 Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor();
234
235 // remove any trailing "\n
236 std::string filename(FileName.str().substr(0,FileName.str().find_last_of('"')));
237 std::string fname, mode, arguments, io;
238 // extract the filename and ACliC mode
239 TCling__SplitAclicMode(filename.c_str(), mode, arguments, io, fname);
240 if (mode.length() > 0) {
241 if (llvm::sys::fs::exists(fname)) {
242 // format the CompileMacro() option string
243 std::string options = "k";
244 if (mode.find("++") != std::string::npos) options += "f";
245 if (mode.find("g") != std::string::npos) options += "g";
246 if (mode.find("O") != std::string::npos) options += "O";
247
248 // Save state of the preprocessor
249 Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
250 Parser& P = const_cast<Parser&>(m_Interpreter->getParser());
251 // We parsed 'include' token. Store it.
252 clang::Parser::ParserCurTokRestoreRAII fSavedCurToken(P);
253 // We provide our own way of handling the entire #include "file.c+"
254 // After we have saved the token reset the current one to
255 // something which is safe (semi colon usually means empty decl)
256 Token& Tok = const_cast<Token&>(P.getCurToken());
257 Tok.setKind(tok::semi);
258 // We can't PushDeclContext, because we go up and the routine that pops
259 // the DeclContext assumes that we drill down always.
260 // We have to be on the global context. At that point we are in a
261 // wrapper function so the parent context must be the global.
262 // This is needed to solve potential issues when using #include "myFile.C+"
263 // after a scope declaration like:
264 // void Check(TObject* obj) {
265 // if (obj) cout << "Found the referenced object\n";
266 // else cout << "Error: Could not find the referenced object\n";
267 // }
268 // #include "A.C+"
269 Sema& SemaR = m_Interpreter->getSema();
270 ASTContext& C = SemaR.getASTContext();
271 Sema::ContextAndScopeRAII pushedDCAndS(SemaR, C.getTranslationUnitDecl(),
272 SemaR.TUScope);
273 int retcode = TCling__CompileMacro(fname.c_str(), options.c_str());
274 if (retcode) {
275 // compilation was successful, tell the preprocess to silently
276 // skip the file
277 return true;
278 }
279 }
280 }
281 return false;
282}
283
284
285static bool topmostDCIsFunction(Scope* S) {
286 if (!S)
287 return false;
288
289 DeclContext* DC = S->getEntity();
290 // For DeclContext-less scopes like if (dyn_expr) {}
291 // Find the DC enclosing S.
292 while (!DC) {
293 S = S->getParent();
294 DC = S->getEntity();
295 }
296
297 // DynamicLookup only happens inside topmost functions:
298 clang::DeclContext* MaybeTU = DC;
299 while (MaybeTU && !isa<TranslationUnitDecl>(MaybeTU)) {
300 DC = MaybeTU;
301 MaybeTU = MaybeTU->getParent();
302 }
303 return isa<FunctionDecl>(DC);
304}
305
306// On a failed lookup we have to try to more things before issuing an error.
307// The symbol might need to be loaded by ROOT's AutoLoading mechanism or
308// it might be a ROOT special object.
309//
310// Try those first and if still failing issue the diagnostics.
311//
312// returns true when a declaration is found and no error should be emitted.
313//
314bool TClingCallbacks::LookupObject(LookupResult &R, Scope *S) {
316 // init error or rootcling
317 return false;
318 }
319
320 // Don't do any extra work if an error that is not still recovered occurred.
321 if (m_Interpreter->getSema().getDiagnostics().hasErrorOccurred())
322 return false;
323
324 if (tryAutoParseInternal(R.getLookupName().getAsString(), R, S))
325 return true; // happiness.
326
327 // The remaining lookup routines only work on global scope functions
328 // ("macros"), not in classes, namespaces etc - anything that looks like
329 // it has seen any trace of software development.
330 if (!topmostDCIsFunction(S))
331 return false;
332
333 // If the autoload wasn't successful try ROOT specials.
335 return true;
336
337 // For backward-compatibility with CINT we must support stmts like:
338 // x = 4; y = new MyClass();
339 // I.e we should "inject" a C++11 auto keyword in front of "x" and "y"
340 // This has to have higher precedence than the dynamic scopes. It is claimed
341 // that if one assigns to a name and the lookup of that name fails if *must*
342 // auto keyword must be injected and the stmt evaluation must not be delayed
343 // until runtime.
344 // For now supported only at the prompt.
346 return true;
347 }
348
350 return false;
351
352 // Finally try to resolve this name as a dynamic name, i.e delay its
353 // resolution for runtime.
355}
356
357bool TClingCallbacks::findInGlobalModuleIndex(DeclarationName Name, bool loadFirstMatchOnly /*=true*/)
358{
359 std::optional<std::string> envUseGMI = llvm::sys::Process::GetEnv("ROOT_USE_GMI");
360 if (envUseGMI.has_value())
361 if (!envUseGMI->empty() && !ROOT::FoundationUtils::ConvertEnvValueToBool(*envUseGMI))
362 return false;
363
364 const CompilerInstance *CI = m_Interpreter->getCI();
365 const LangOptions &LangOpts = CI->getPreprocessor().getLangOpts();
366
367 if (!LangOpts.Modules)
368 return false;
369
370 // We are currently building a module, we should not import .
371 if (LangOpts.isCompilingModule())
372 return false;
373
374 if (fIsCodeGening)
375 return false;
376
377 // We are currently instantiating one (or more) templates. At that point,
378 // all Decls are present in the AST (with possibly deserialization pending),
379 // and we should not load more modules which could find an implicit template
380 // instantiation that is lazily loaded.
381 Sema &SemaR = m_Interpreter->getSema();
382 if (SemaR.InstantiatingSpecializations.size() > 0)
383 return false;
384
385 GlobalModuleIndex *Index = CI->getASTReader()->getGlobalIndex();
386 if (!Index)
387 return false;
388
389 // FIXME: We should load only the first available and rely on other callbacks
390 // such as RequireCompleteType and LookupUnqualified to load all.
391 GlobalModuleIndex::FileNameHitSet FoundModules;
392
393 // Find the modules that reference the identifier.
394 // Note that this only finds top-level modules.
395 if (Index->lookupIdentifier(Name.getAsString(), FoundModules)) {
396 for (llvm::StringRef FileName : FoundModules) {
397 StringRef ModuleName = llvm::sys::path::stem(FileName);
398
399 // Skip to the first not-yet-loaded module.
400 if (m_LoadedModuleFiles.count(FileName)) {
401 if (gDebug > 2)
402 llvm::errs() << "Module '" << ModuleName << "' already loaded"
403 << " for '" << Name.getAsString() << "'\n";
404 continue;
405 }
406
407 fIsLoadingModule = true;
408 if (gDebug > 2)
409 llvm::errs() << "Loading '" << ModuleName << "' on demand"
410 << " for '" << Name.getAsString() << "'\n";
411
412 m_Interpreter->loadModule(ModuleName.str());
413 fIsLoadingModule = false;
414 m_LoadedModuleFiles[FileName] = Name;
415 if (loadFirstMatchOnly)
416 break;
417 }
418 return true;
419 }
420 return false;
421}
422
423bool TClingCallbacks::LookupObject(const DeclContext* DC, DeclarationName Name) {
425 // init error or rootcling
426 return false;
427 }
428
430 return false;
431
433 return false;
434
435 if (Name.getNameKind() != DeclarationName::Identifier)
436 return false;
437
438 Sema &SemaR = m_Interpreter->getSema();
439 auto *D = cast<Decl>(DC);
440 SourceLocation Loc = D->getLocation();
441 if (Loc.isValid() && SemaR.getSourceManager().isInSystemHeader(Loc)) {
442 // This declaration comes from a system module, we do not want to try
443 // autoparsing it and find instantiations in our ROOT modules.
444 return false;
445 }
446
447 // Get the 'lookup' decl context.
448 // We need to cast away the constness because we will lookup items of this
449 // namespace/DeclContext
450 NamespaceDecl* NSD = dyn_cast<NamespaceDecl>(const_cast<DeclContext*>(DC));
451
452 // When GMI is mixed with rootmaps, we might have a name for two different
453 // entities provided by the two systems. In that case check if the rootmaps
454 // registered the enclosing namespace as a rootmap name resolution namespace
455 // and only if that was not the case use the information in the GMI.
456 if (!NSD || !TCling__IsAutoLoadNamespaceCandidate(NSD)) {
457 // After loading modules, we must update the redeclaration chains.
458 return findInGlobalModuleIndex(Name, /*loadFirstMatchOnly*/ false) && D->getMostRecentDecl();
459 }
460
461 const DeclContext* primaryDC = NSD->getPrimaryContext();
462 if (primaryDC != DC)
463 return false;
464
465 LookupResult R(SemaR, Name, SourceLocation(), Sema::LookupOrdinaryName);
466 R.suppressDiagnostics();
467 // We need the qualified name for TCling to find the right library.
468 std::string qualName
469 = NSD->getQualifiedNameAsString() + "::" + Name.getAsString();
470
471
472 // We want to avoid qualified lookups, because they are expensive and
473 // difficult to construct. This is why we *artificially* push a scope and
474 // a decl context, where Sema should do the lookup.
475 clang::Scope S(SemaR.TUScope, clang::Scope::DeclScope, SemaR.getDiagnostics());
476 S.setEntity(const_cast<DeclContext*>(DC));
477 Sema::ContextAndScopeRAII pushedDCAndS(SemaR, const_cast<DeclContext*>(DC), &S);
478
479 if (tryAutoParseInternal(qualName, R, SemaR.getCurScope())) {
480 llvm::SmallVector<NamedDecl*, 4> lookupResults;
481 for(LookupResult::iterator I = R.begin(), E = R.end(); I < E; ++I)
482 lookupResults.push_back(*I);
483 UpdateWithNewDecls(DC, Name, llvm::ArrayRef(lookupResults.data(), lookupResults.size()));
484 return true;
485 }
486 return false;
487}
488
489bool TClingCallbacks::LookupObject(clang::TagDecl* Tag) {
491 // init error or rootcling
492 return false;
493 }
494
496 return false;
497
498 // Clang needs Tag's complete definition. Can we parse it?
500
501 // if (findInGlobalModuleIndex(Tag->getDeclName(), /*loadFirstMatchOnly*/false))
502 // return true;
503
504 Sema &SemaR = m_Interpreter->getSema();
505
506 SourceLocation Loc = Tag->getLocation();
507 if (SemaR.getSourceManager().isInSystemHeader(Loc)) {
508 // This declaration comes from a system module, we do not want to try
509 // autoparsing it and find instantiations in our ROOT modules.
510 return false;
511 }
512
513 for (auto ReRD: Tag->redecls()) {
514 // Don't autoparse a TagDecl while we are parsing its definition!
515 if (ReRD->isBeingDefined())
516 return false;
517 }
518
519
520 if (RecordDecl* RD = dyn_cast<RecordDecl>(Tag)) {
521 ASTContext& C = SemaR.getASTContext();
522 Parser& P = const_cast<Parser&>(m_Interpreter->getParser());
523
524 ParsingStateRAII raii(P,SemaR);
525
526 // Use the Normalized name for the autoload
527 std::string Name;
528 const ROOT::TMetaUtils::TNormalizedCtxt* tNormCtxt = nullptr;
531 C.getTypeDeclType(RD),
532 *m_Interpreter,
533 *tNormCtxt);
534 // Autoparse implies autoload
535 if (TCling__AutoParseCallback(Name.c_str())) {
536 // We have read it; remember that.
537 Tag->setHasExternalLexicalStorage(false);
538 return true;
539 }
540 }
541 return false;
542}
543
544
545// The symbol might be defined in the ROOT class AutoLoading map so we have to
546// try to autoload it first and do secondary lookup to try to find it.
547//
548// returns true when a declaration is found and no error should be emitted.
549// If FileEntry, this is a reacting on a #include and Name is the included
550// filename.
551//
552bool TClingCallbacks::tryAutoParseInternal(llvm::StringRef Name, LookupResult &R,
553 Scope *S, clang::OptionalFileEntryRef FE) {
555 // init error or rootcling
556 return false;
557 }
558
559 Sema &SemaR = m_Interpreter->getSema();
560
561 // Try to autoload first if AutoLoading is enabled
562 if (IsAutoLoadingEnabled()) {
563 // Avoid tail chasing.
565 return false;
566
567 // We should try autoload only for special lookup failures.
568 Sema::LookupNameKind kind = R.getLookupKind();
569 if (!(kind == Sema::LookupTagName || kind == Sema::LookupOrdinaryName
570 || kind == Sema::LookupNestedNameSpecifierName
571 || kind == Sema::LookupNamespaceName))
572 return false;
573
575
576 bool lookupSuccess = false;
577 // Save state of the PP
578 Parser &P = const_cast<Parser &>(m_Interpreter->getParser());
579
580 ParsingStateRAII raii(P, SemaR);
581
582 // First see whether we have a fwd decl of this name.
583 // We shall only do that if lookup makes sense for it (!FE).
584 if (!FE) {
585 lookupSuccess = SemaR.LookupName(R, S);
586 if (lookupSuccess) {
587 if (R.isSingleResult()) {
588 if (isa<clang::RecordDecl>(R.getFoundDecl())) {
589 // Good enough; RequireCompleteType() will tell us if we
590 // need to auto parse.
591 // But we might need to auto-load.
592 TCling__AutoLoadCallback(Name.data());
594 return true;
595 }
596 }
597 }
598 }
599
600 if (TCling__AutoParseCallback(Name.str().c_str())) {
601 // Shouldn't we pop more?
602 raii.fPushedDCAndS.pop();
603 raii.fCleanupRAII.pop();
604 lookupSuccess = FE || SemaR.LookupName(R, S);
605 } else if (FE && TCling__GetClassSharedLibs(Name.str().c_str())) {
606 // We are "autoparsing" a header, and the header was not parsed.
607 // But its library is known - so we do know about that header.
608 // Do the parsing explicitly here, while recursive AutoLoading is
609 // disabled.
610 std::string incl = "#include \"";
611 incl += FE->getName();
612 incl += '"';
613 m_Interpreter->declare(incl);
614 }
615
617
618 if (lookupSuccess)
619 return true;
620 }
621
622 return false;
623}
624
625// If cling cannot find a name it should ask ROOT before it issues an error.
626// If ROOT knows the name then it has to create a new variable with that name
627// and type in dedicated for that namespace (eg. __ROOT_SpecialObjects).
628// For example if the interpreter is looking for h in h-Draw(), this routine
629// will create
630// namespace __ROOT_SpecialObjects {
631// THist* h = (THist*) the_address;
632// }
633//
634// Later if h is called again it again won't be found by the standart lookup
635// because it is in our hidden namespace (nobody should do using namespace
636// __ROOT_SpecialObjects). It caches the variable declarations and their
637// last address. If the newly found decl with the same name (h) has different
638// address than the cached one it goes directly at the address and updates it.
639//
640// returns true when declaration is found and no error should be emitted.
641//
642bool TClingCallbacks::tryFindROOTSpecialInternal(LookupResult &R, Scope *S) {
644 // init error or rootcling
645 return false;
646 }
647
648 // User must be able to redefine the names that come from a file.
649 if (R.isForRedeclaration())
650 return false;
651 // If there is a result abort.
652 if (!R.empty())
653 return false;
654 const Sema::LookupNameKind LookupKind = R.getLookupKind();
655 if (LookupKind != Sema::LookupOrdinaryName)
656 return false;
657
658
659 Sema &SemaR = m_Interpreter->getSema();
660 ASTContext& C = SemaR.getASTContext();
661 Preprocessor &PP = SemaR.getPreprocessor();
662 DeclContext *CurDC = SemaR.CurContext;
663 DeclarationName Name = R.getLookupName();
664
665 // Make sure that the failed lookup comes from a function body.
666 if(!CurDC || !CurDC->isFunctionOrMethod())
667 return false;
668
669 // Save state of the PP, because TCling__GetObjectAddress may induce nested
670 // lookup.
671 Preprocessor::CleanupAndRestoreCacheRAII cleanupPPRAII(PP);
672 TObject *obj = TCling__GetObjectAddress(Name.getAsString().c_str(),
674 cleanupPPRAII.pop(); // force restoring the cache
675
676 if (obj) {
677
678#if defined(R__MUST_REVISIT)
679#if R__MUST_REVISIT(6,2)
680 // Register the address in TCling::fgSetOfSpecials
681 // to speed-up the execution of TCling::RecursiveRemove when
682 // the object is not a special.
683 // See http://root.cern.ch/viewvc/trunk/core/meta/src/TCint.cxx?view=log#rev18109
684 if (!fgSetOfSpecials) {
685 fgSetOfSpecials = new std::set<TObject*>;
686 }
687 ((std::set<TObject*>*)fgSetOfSpecials)->insert((TObject*)*obj);
688#endif
689#endif
690
691 VarDecl *VD = cast_or_null<VarDecl>(utils::Lookup::Named(&SemaR, Name,
693 if (VD) {
694 //TODO: Check for same types.
695 GlobalDecl GD(VD);
696 TObject **address = (TObject**)m_Interpreter->getAddressOfGlobal(GD);
697 // Since code was generated already we cannot rely on the initializer
698 // of the decl in the AST, however we will update that init so that it
699 // will be easier while debugging.
700 CStyleCastExpr *CStyleCast = cast<CStyleCastExpr>(VD->getInit());
701 Expr* newInit = utils::Synthesize::IntegerLiteralExpr(C, (uint64_t)obj);
702 CStyleCast->setSubExpr(newInit);
703
704 // The actual update happens here, directly in memory.
705 *address = obj;
706 }
707 else {
708 // Save state of the PP
709 Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
710
711 const Decl *TD = TCling__GetObjectDecl(obj);
712 // We will declare the variable as pointer.
713 QualType QT = C.getPointerType(C.getTypeDeclType(cast<TypeDecl>(TD)));
714
715 VD = VarDecl::Create(C, fROOTSpecialNamespace, SourceLocation(),
716 SourceLocation(), Name.getAsIdentifierInfo(), QT,
717 /*TypeSourceInfo*/nullptr, SC_None);
718 // Build an initializer
719 Expr* Init
720 = utils::Synthesize::CStyleCastPtrExpr(&SemaR, QT, (uint64_t)obj);
721 // Register the decl in our hidden special namespace
722 VD->setInit(Init);
723 fROOTSpecialNamespace->addDecl(VD);
724
725 cling::CompilationOptions CO;
726 CO.DeclarationExtraction = 0;
727 CO.ValuePrinting = CompilationOptions::VPDisabled;
728 CO.ResultEvaluation = 0;
729 CO.DynamicScoping = 0;
730 CO.Debug = 0;
731 CO.CodeGeneration = 1;
732
733 cling::Transaction* T = new cling::Transaction(CO, SemaR);
734 T->append(VD);
735 T->setState(cling::Transaction::kCompleted);
736
737 m_Interpreter->emitAllDecls(T);
738 }
739 assert(VD && "Cannot be null!");
740 R.addDecl(VD);
741 return true;
742 }
743
744 return false;
745}
746
747bool TClingCallbacks::tryResolveAtRuntimeInternal(LookupResult &R, Scope *S) {
749 // init error or rootcling
750 return false;
751 }
752
753 if (!shouldResolveAtRuntime(R, S))
754 return false;
755
756 DeclarationName Name = R.getLookupName();
757 IdentifierInfo* II = Name.getAsIdentifierInfo();
758 SourceLocation Loc = R.getNameLoc();
759 Sema& SemaRef = R.getSema();
760 ASTContext& C = SemaRef.getASTContext();
761 DeclContext* TU = C.getTranslationUnitDecl();
762 assert(TU && "Must not be null.");
763
764 // DynamicLookup only happens inside wrapper functions:
765 clang::FunctionDecl* Wrapper = nullptr;
766 Scope* Cursor = S;
767 do {
768 DeclContext* DCCursor = Cursor->getEntity();
769 if (DCCursor == TU)
770 return false;
771 Wrapper = dyn_cast_or_null<FunctionDecl>(DCCursor);
772 if (Wrapper) {
773 if (utils::Analyze::IsWrapper(Wrapper)) {
774 break;
775 } else {
776 // Can't have a function inside the wrapper:
777 return false;
778 }
779 }
780 } while ((Cursor = Cursor->getParent()));
781
782 if (!Wrapper) {
783 // The parent of S wasn't the TU?!
784 return false;
785 }
786
787 // Prevent redundant declarations for control statements (e.g., for, if, while)
788 // that have already been annotated.
789 if (auto annot = Wrapper->getAttr<AnnotateAttr>())
790 if (annot->getAnnotation().equals("__ResolveAtRuntime") && S->isControlScope())
791 return false;
792
793 VarDecl* Result = VarDecl::Create(C, TU, Loc, Loc, II, C.DependentTy,
794 /*TypeSourceInfo*/nullptr, SC_None);
795
796 if (!Result) {
797 // We cannot handle the situation. Give up
798 return false;
799 }
800
801 // Annotate the decl to give a hint in cling. FIXME: Current implementation
802 // is a gross hack, because TClingCallbacks shouldn't know about
803 // EvaluateTSynthesizer at all!
804
805 Wrapper->addAttr(AnnotateAttr::CreateImplicit(C, "__ResolveAtRuntime", nullptr, 0));
806
807 // Here we have the scope but we cannot do Sema::PushDeclContext, because
808 // on pop it will try to go one level up, which we don't want.
809 Sema::ContextRAII pushedDC(SemaRef, TU);
810 R.addDecl(Result);
811 //SemaRef.PushOnScopeChains(Result, SemaRef.TUScope, /*Add to ctx*/true);
812 // Say that we can handle the situation. Clang should try to recover
813 return true;
814}
815
816bool TClingCallbacks::shouldResolveAtRuntime(LookupResult& R, Scope* S) {
817 if (m_IsRuntime)
818 return false;
819
820 if (R.getLookupKind() != Sema::LookupOrdinaryName)
821 return false;
822
823 if (R.isForRedeclaration())
824 return false;
825
826 if (!R.empty())
827 return false;
828
829 const Transaction* T = getInterpreter()->getCurrentTransaction();
830 if (!T)
831 return false;
832 const cling::CompilationOptions& COpts = T->getCompilationOpts();
833 if (!COpts.DynamicScoping)
834 return false;
835
836 auto &PP = R.getSema().PP;
837 // In `foo bar`, `foo` is certainly a type name and must not be resolved. We
838 // cannot rely on `PP.LookAhead(0)` as the parser might have already consumed
839 // some tokens.
840 SourceLocation LocAfterIdent = PP.getLocForEndOfToken(R.getNameLoc());
841 Token LookAhead0;
842 PP.getRawToken(LocAfterIdent, LookAhead0, /*IgnoreWhiteSpace=*/true);
843 if (LookAhead0.is(tok::raw_identifier))
844 return false;
845
846 // FIXME: Figure out better way to handle:
847 // C++ [basic.lookup.classref]p1:
848 // In a class member access expression (5.2.5), if the . or -> token is
849 // immediately followed by an identifier followed by a <, the
850 // identifier must be looked up to determine whether the < is the
851 // beginning of a template argument list (14.2) or a less-than operator.
852 // The identifier is first looked up in the class of the object
853 // expression. If the identifier is not found, it is then looked up in
854 // the context of the entire postfix-expression and shall name a class
855 // or function template.
856 //
857 // We want to ignore object(.|->)member<template>
858 //if (R.getSema().PP.LookAhead(0).getKind() == tok::less)
859 // TODO: check for . or -> in the cached token stream
860 // return false;
861
862 for (Scope* DepScope = S; DepScope; DepScope = DepScope->getParent()) {
863 if (DeclContext* Ctx = static_cast<DeclContext*>(DepScope->getEntity())) {
864 if (!Ctx->isDependentContext())
865 // For now we support only the prompt.
866 if (isa<FunctionDecl>(Ctx))
867 return true;
868 }
869 }
870
871 return false;
872}
873
876 // init error or rootcling
877 return false;
878 }
879
880 // Should be disabled with the dynamic scopes.
881 if (m_IsRuntime)
882 return false;
883
884 if (R.isForRedeclaration())
885 return false;
886
887 if (R.getLookupKind() != Sema::LookupOrdinaryName)
888 return false;
889
890 if (!isa<FunctionDecl>(R.getSema().CurContext))
891 return false;
892
893 {
894 // ROOT-8538: only top-most (function-level) scope is supported.
895 DeclContext* ScopeDC = S->getEntity();
896 if (!ScopeDC || !llvm::isa<FunctionDecl>(ScopeDC))
897 return false;
898
899 // Make sure that the failed lookup comes the prompt. Currently, we
900 // support only the prompt.
901 Scope* FnScope = S->getFnParent();
902 if (!FnScope)
903 return false;
904 auto FD = dyn_cast_or_null<FunctionDecl>(FnScope->getEntity());
905 if (!FD || !utils::Analyze::IsWrapper(FD))
906 return false;
907 }
908
909 Sema& SemaRef = R.getSema();
910 ASTContext& C = SemaRef.getASTContext();
911 DeclContext* DC = SemaRef.CurContext;
912 assert(DC && "Must not be null.");
913
914
915 Preprocessor& PP = R.getSema().getPreprocessor();
916 //Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
917 //PP.EnableBacktrackAtThisPos();
918 if (PP.LookAhead(0).isNot(tok::equal)) {
919 //PP.Backtrack();
920 return false;
921 }
922 //PP.CommitBacktrackedTokens();
923 //cleanupRAII.pop();
924 DeclarationName Name = R.getLookupName();
925 IdentifierInfo* II = Name.getAsIdentifierInfo();
926 SourceLocation Loc = R.getNameLoc();
927 VarDecl* Result = VarDecl::Create(C, DC, Loc, Loc, II,
928 C.getAutoType(QualType(),
929 clang::AutoTypeKeyword::Auto,
930 /*IsDependent*/false),
931 /*TypeSourceInfo*/nullptr, SC_None);
932
933 if (!Result) {
934 ROOT::TMetaUtils::Error("TClingCallbacks::tryInjectImplicitAutoKeyword",
935 "Cannot create VarDecl");
936 return false;
937 }
938
939 // Annotate the decl to give a hint in cling.
940 // FIXME: We should move this in cling, when we implement turning it on
941 // and off.
942 Result->addAttr(AnnotateAttr::CreateImplicit(C, "__Auto", nullptr, 0));
943
944 R.addDecl(Result);
945
946 // Raise a warning when trying to use implicit auto injection feature.
947 SemaRef.getDiagnostics().setSeverity(diag::warn_deprecated_message, diag::Severity::Warning, SourceLocation());
948 SemaRef.Diag(Loc, diag::warn_deprecated_message)
949 << "declaration without the 'auto' keyword" << DC << Loc << FixItHint::CreateInsertion(Loc, "auto ");
950
951 // Say that we can handle the situation. Clang should try to recover
952 return true;
953}
954
956 // Replay existing decls from the AST.
957 if (fFirstRun) {
958 // Before setting up the callbacks register what cling have seen during init.
959 Sema& SemaR = m_Interpreter->getSema();
960 cling::Transaction TPrev((cling::CompilationOptions(), SemaR));
961 TPrev.append(SemaR.getASTContext().getTranslationUnitDecl());
962 TCling__UpdateListsOnCommitted(TPrev, m_Interpreter);
963
964 fFirstRun = false;
965 }
966}
967
968// The callback is used to update the list of globals in ROOT.
969//
970void TClingCallbacks::TransactionCommitted(const Transaction &T) {
971 if (fFirstRun && T.empty())
972 Initialize();
973
974 TCling__UpdateListsOnCommitted(T, m_Interpreter);
975}
976
977// The callback is used to update the list of globals in ROOT.
978//
979void TClingCallbacks::TransactionUnloaded(const Transaction &T) {
980 if (T.empty())
981 return;
982
984}
985
986// The callback is used to clear the autoparsing caches.
987//
988void TClingCallbacks::TransactionRollback(const Transaction &T) {
989 if (T.empty())
990 return;
991
993}
994
995void TClingCallbacks::DefinitionShadowed(const clang::NamedDecl *D) {
997}
998
999void TClingCallbacks::LibraryLoaded(const void* dyLibHandle,
1000 llvm::StringRef canonicalName) {
1001 TCling__LibraryLoadedRTTI(dyLibHandle, canonicalName);
1002}
1003
1004void TClingCallbacks::LibraryUnloaded(const void* dyLibHandle,
1005 llvm::StringRef canonicalName) {
1006 TCling__LibraryUnloadedRTTI(dyLibHandle, canonicalName);
1007}
1008
1011}
1012
1014{
1015 // We can safely assume that if the lock exist already when we are in Cling code,
1016 // then the lock has (or should been taken) already. Any action (that caused callers
1017 // to take the lock) is halted during ProcessLine. So it is fair to unlock it.
1019}
1020
1022{
1024}
1025
1027{
1029}
1030
1032{
1034}
#define R__EXTERN
Definition DllImport.h:26
The file contains utilities which are foundational and could be used across the core component of ROO...
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...
Definition TCling.cxx:351
void * TCling__LockCompilationDuringUserCodeExecution()
Lock the interpreter.
Definition TCling.cxx:368
int TCling__LoadLibrary(const char *library)
Load a library.
Definition TCling.cxx:333
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)
Definition TCling.cxx:651
void TCling__TransactionRollback(const cling::Transaction &)
Definition TCling.cxx:579
const char * TCling__GetClassSharedLibs(const char *className)
int TCling__AutoParseCallback(const char *className)
Definition TCling.cxx:628
Decl * TCling__GetObjectDecl(TObject *obj)
Definition TCling.cxx:604
R__EXTERN int gDebug
void TCling__GetNormalizedContext(const ROOT::TMetaUtils::TNormalizedCtxt *&)
Definition TCling.cxx:557
void TCling__RestoreInterpreterMutex(void *state)
Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
Definition TCling.cxx:341
int TCling__CompileMacro(const char *fileName, const char *options)
Definition TCling.cxx:644
void * TCling__ResetInterpreterMutex()
Reset the interpreter lock to the state it had before interpreter-related calls happened.
Definition TCling.cxx:360
int TCling__AutoLoadCallback(const char *className)
Definition TCling.cxx:623
void TCling__LibraryUnloadedRTTI(const void *dyLibHandle, llvm::StringRef canonicalName)
void TCling__PrintStackTrace()
Print a StackTrace!
Definition TCling.cxx:326
int TCling__IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl *name)
Definition TCling.cxx:639
void TCling__UpdateListsOnUnloaded(const cling::Transaction &)
Definition TCling.cxx:569
void TCling__UnlockCompilationDuringUserCodeExecution(void *state)
Unlock the interpreter.
Definition TCling.cxx:379
static bool topmostDCIsFunction(Scope *S)
void TCling__InvalidateGlobal(const clang::Decl *)
Definition TCling.cxx:574
void TCling__LibraryLoadedRTTI(const void *dyLibHandle, llvm::StringRef canonicalName)
TObject * TCling__GetObjectAddress(const char *Name, void *&LookupCtx)
Definition TCling.cxx:600
void TCling__RestoreInterpreterMutex(void *delta)
Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
Definition TCling.cxx:341
void TCling__TransactionRollback(const cling::Transaction &T)
Definition TCling.cxx:579
void TCling__InvalidateGlobal(const clang::Decl *D)
Definition TCling.cxx:574
void * TCling__LockCompilationDuringUserCodeExecution()
Lock the interpreter.
Definition TCling.cxx:368
void TCling__UpdateListsOnUnloaded(const cling::Transaction &T)
Definition TCling.cxx:569
void TCling__GetNormalizedContext(const ROOT::TMetaUtils::TNormalizedCtxt *&normCtxt)
Definition TCling.cxx:557
bool TCling__LibraryLoadingFailed(const std::string &errmessage, const std::string &libStem, bool permanent, bool resolved)
Lookup libraries in LD_LIBRARY_PATH and DYLD_LIBRARY_PATH with mangled_name, which is extracted by er...
Definition TCling.cxx:351
const char * TCling__GetClassSharedLibs(const char *className, bool skipCore)
Definition TCling.cxx:633
void TCling__UnlockCompilationDuringUserCodeExecution(void *)
Unlock the interpreter.
Definition TCling.cxx:379
int TCling__AutoParseCallback(const char *className)
Definition TCling.cxx:628
void TCling__LibraryUnloadedRTTI(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:593
void TCling__UpdateListsOnCommitted(const cling::Transaction &T, cling::Interpreter *)
Definition TCling.cxx:564
const Decl * TCling__GetObjectDecl(TObject *obj)
Definition TCling.cxx:604
int TCling__CompileMacro(const char *fileName, const char *options)
Definition TCling.cxx:644
void * TCling__ResetInterpreterMutex()
Reset the interpreter lock to the state it had before interpreter-related calls happened.
Definition TCling.cxx:360
int TCling__AutoLoadCallback(const char *className)
Definition TCling.cxx:623
void TCling__PrintStackTrace()
Print a StackTrace!
Definition TCling.cxx:326
void TCling__LibraryLoadedRTTI(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:583
TObject * TCling__GetObjectAddress(const char *Name, void *&LookupCtx)
Definition TCling.cxx:600
int TCling__IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl *nsDecl)
Definition TCling.cxx:639
void TCling__SplitAclicMode(const char *fileName, string &mode, string &args, string &io, string &fname)
Definition TCling.cxx:651
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char filename
Option_t Option_t TPoint TPoint const char mode
char name[80]
Definition TGX11.cxx:110
XID Cursor
Definition TGX11.h:34
Int_t gDebug
Definition TROOT.cxx:597
AutoloadLibraryGenerator(cling::Interpreter *interp, const TClingCallbacks &cb)
const TClingCallbacks & fCallbacks
cling::Interpreter * fInterpreter
llvm::Error tryToGenerate(llvm::orc::LookupState &LS, llvm::orc::LookupKind K, llvm::orc::JITDylib &JD, llvm::orc::JITDylibLookupFlags JDLookupFlags, const llvm::orc::SymbolLookupSet &Symbols) override
void LibraryUnloaded(const void *dyLibHandle, llvm::StringRef canonicalName) override
bool tryFindROOTSpecialInternal(clang::LookupResult &R, clang::Scope *S)
void ReturnedFromUserCode(void *stateInfo) override
bool tryResolveAtRuntimeInternal(clang::LookupResult &R, clang::Scope *S)
bool findInGlobalModuleIndex(clang::DeclarationName Name, bool loadFirstMatchOnly=true)
bool tryAutoParseInternal(llvm::StringRef Name, clang::LookupResult &R, clang::Scope *S, clang::OptionalFileEntryRef FE=std::nullopt)
void PrintStackTrace() override
bool tryInjectImplicitAutoKeyword(clang::LookupResult &R, clang::Scope *S)
clang::NamespaceDecl * fROOTSpecialNamespace
void TransactionRollback(const cling::Transaction &T) override
void TransactionCommitted(const cling::Transaction &T) override
bool FileNotFound(llvm::StringRef FileName) override
TClingCallbacks(cling::Interpreter *interp, bool hasCodeGen)
llvm::DenseMap< llvm::StringRef, clang::DeclarationName > m_LoadedModuleFiles
bool IsAutoLoadingEnabled() const
void DefinitionShadowed(const clang::NamedDecl *D) override
A previous definition has been shadowed; invalidate TCling' stored data about the old (global) decl.
void * EnteringUserCode() override
void UnlockCompilationDuringUserCodeExecution(void *StateInfo) override
bool LibraryLoadingFailed(const std::string &, const std::string &, bool, bool) override
void InclusionDirective(clang::SourceLocation, const clang::Token &, llvm::StringRef FileName, bool, clang::CharSourceRange, clang::OptionalFileEntryRef, llvm::StringRef, llvm::StringRef, const clang::Module *, clang::SrcMgr::CharacteristicKind) override
void * LockCompilationDuringUserCodeExecution() override
bool LookupObject(clang::LookupResult &R, clang::Scope *S) override
void LibraryLoaded(const void *dyLibHandle, llvm::StringRef canonicalName) override
bool shouldResolveAtRuntime(clang::LookupResult &R, clang::Scope *S)
void TransactionUnloaded(const cling::Transaction &T) override
Mother of all ROOT objects.
Definition TObject.h:41
#define I(x, y, z)
bool ConvertEnvValueToBool(const std::string &value)
void Error(const char *location, const char *fmt,...)
void Info(const char *location, const char *fmt,...)
void GetNormalizedName(std::string &norm_name, const clang::QualType &type, const cling::Interpreter &interpreter, const TNormalizedCtxt &normCtxt)
Return the type name normalized for ROOT, keeping only the ROOT opaque typedef (Double32_t,...
static std::string DemangleNameForDlsym(const std::string &name)
RooArgSet S(Args_t &&... args)
Definition RooArgSet.h:195
constexpr Double_t E()
Base of natural log: .
Definition TMath.h:93
const char * Name
Definition TXMLSetup.cxx:67
RAII used to store Parser, Sema, Preprocessor state for recursive parsing.
Definition ClingRAII.h:22
clang::Preprocessor::CleanupAndRestoreCacheRAII fCleanupRAII
Definition ClingRAII.h:60
clang::Sema::ContextAndScopeRAII fPushedDCAndS
Definition ClingRAII.h:73