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