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