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