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