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