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