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