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