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