Logo ROOT  
Reference Guide
TClingUtils.cxx
Go to the documentation of this file.
1// @(#)root/metautils:$Id$
2// Author: Paul Russo, 2009-10-06
3
4/*************************************************************************
5 * Copyright (C) 1995-2011, 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//______________________________________________________________________________
13// //
14// ROOT::TMetaUtils provides utility wrappers around //
15// cling, the LLVM-based interpreter. It's an internal set of tools //
16// used by TCling and rootcling. //
17// //
18//______________________________________________________________________________
19#include <algorithm>
20#include <iostream>
21#include <sstream>
22#include <stdlib.h>
23#include <stdio.h>
24#include <unordered_set>
25
26#include "RConfigure.h"
27#include <ROOT/RConfig.hxx>
29#include "Rtypes.h"
30#include "strlcpy.h"
31
32#include "RStl.h"
33
34#include "clang/AST/ASTContext.h"
35#include "clang/AST/Attr.h"
36#include "clang/AST/CXXInheritance.h"
37#include "clang/AST/Decl.h"
38#include "clang/AST/DeclTemplate.h"
39#include "clang/AST/Mangle.h"
40#include "clang/AST/Type.h"
41#include "clang/AST/TypeVisitor.h"
42#include "clang/Frontend/CompilerInstance.h"
43#include "clang/Lex/HeaderSearch.h"
44#include "clang/Lex/ModuleMap.h"
45#include "clang/Lex/Preprocessor.h"
46#include "clang/Lex/PreprocessorOptions.h"
47
48#include "clang/Sema/Lookup.h"
49#include "clang/Sema/Sema.h"
50#include "clang/Sema/SemaDiagnostic.h"
51
52#include "cling/Interpreter/LookupHelper.h"
53#include "cling/Interpreter/Transaction.h"
54#include "cling/Interpreter/Interpreter.h"
55#include "cling/Utils/AST.h"
56
57#include "llvm/Support/Path.h"
58#include "llvm/Support/FileSystem.h"
59
60// Intentionally access non-public header ...
61#include "../../../interpreter/llvm/src/tools/clang/lib/Sema/HackForDefaultTemplateArg.h"
62
63#include "TClingUtils.h"
64
65#ifdef _WIN32
66#define strncasecmp _strnicmp
67#include <io.h>
68#else
69#include <unistd.h>
70#endif // _WIN32
71
72namespace ROOT {
73namespace TMetaUtils {
74
75std::string GetRealPath(const std::string &path)
76{
77 llvm::SmallString<256> result_path;
78 llvm::sys::fs::real_path(path, result_path, /*expandTilde*/true);
79 return result_path.str().str();
80}
81
82
83////////////////////////////////////////////////////////////////////////////////
84
86 using DeclsCont_t = TNormalizedCtxt::Config_t::SkipCollection;
90private:
94public:
95 TNormalizedCtxtImpl(const cling::LookupHelper &lh);
96
97 const Config_t &GetConfig() const { return fConfig; }
99 void AddTemplAndNargsToKeep(const clang::ClassTemplateDecl* templ, unsigned int i);
100 int GetNargsToKeep(const clang::ClassTemplateDecl* templ) const;
102 void keepTypedef(const cling::LookupHelper &lh, const char* name,
103 bool replace = false);
104};
105}
106}
107
108namespace {
109
110////////////////////////////////////////////////////////////////////////////////
111/// Add default parameter to the scope if needed.
112
113static clang::NestedNameSpecifier *AddDefaultParametersNNS(const clang::ASTContext& Ctx,
114 clang::NestedNameSpecifier* scope,
115 const cling::Interpreter &interpreter,
116 const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt) {
117 if (!scope) return nullptr;
118
119 const clang::Type* scope_type = scope->getAsType();
120 if (scope_type) {
121 // this is not a namespace, so we might need to desugar
122 clang::NestedNameSpecifier* outer_scope = scope->getPrefix();
123 if (outer_scope) {
124 outer_scope = AddDefaultParametersNNS(Ctx, outer_scope, interpreter, normCtxt);
125 }
126
127 clang::QualType addDefault =
128 ROOT::TMetaUtils::AddDefaultParameters(clang::QualType(scope_type,0), interpreter, normCtxt );
129 // NOTE: Should check whether the type has changed or not.
130 if (addDefault.getTypePtr() != scope_type)
131 return clang::NestedNameSpecifier::Create(Ctx,outer_scope,
132 false /* template keyword wanted */,
133 addDefault.getTypePtr());
134 }
135 return scope;
136}
137
138////////////////////////////////////////////////////////////////////////////////
139
140static bool CheckDefinition(const clang::CXXRecordDecl *cl, const clang::CXXRecordDecl *context)
141{
142 if (!cl->hasDefinition()) {
143 if (context) {
144 ROOT::TMetaUtils::Error("CheckDefinition",
145 "Missing definition for class %s, please #include its header in the header of %s\n",
146 cl->getName().str().c_str(), context->getName().str().c_str());
147 } else {
148 ROOT::TMetaUtils::Error("CheckDefinition",
149 "Missing definition for class %s\n",
150 cl->getName().str().c_str());
151 }
152 return false;
153 }
154 return true;
155}
156
157////////////////////////////////////////////////////////////////////////////////
158/// Check if 'scope' or any of its template parameter was substituted when
159/// instantiating the class template instance and replace it with the
160/// partially sugared types we have from 'instance'.
161
162static clang::NestedNameSpecifier *ReSubstTemplateArgNNS(const clang::ASTContext &Ctxt,
163 clang::NestedNameSpecifier *scope,
164 const clang::Type *instance)
165{
166 if (!scope) return nullptr;
167
168 const clang::Type* scope_type = scope->getAsType();
169 if (scope_type) {
170 clang::NestedNameSpecifier* outer_scope = scope->getPrefix();
171 if (outer_scope) {
172 outer_scope = ReSubstTemplateArgNNS(Ctxt, outer_scope, instance);
173 }
174 clang::QualType substScope =
175 ROOT::TMetaUtils::ReSubstTemplateArg(clang::QualType(scope_type,0), instance);
176 // NOTE: Should check whether the type has changed or not.
177 scope = clang::NestedNameSpecifier::Create(Ctxt,outer_scope,
178 false /* template keyword wanted */,
179 substScope.getTypePtr());
180 }
181 return scope;
182}
183
184////////////////////////////////////////////////////////////////////////////////
185
186static bool IsTypeInt(const clang::Type *type)
187{
188 const clang::BuiltinType * builtin = llvm::dyn_cast<clang::BuiltinType>(type->getCanonicalTypeInternal().getTypePtr());
189 if (builtin) {
190 return builtin->isInteger(); // builtin->getKind() == clang::BuiltinType::Int;
191 } else {
192 return false;
193 }
194}
195
196////////////////////////////////////////////////////////////////////////////////
197
198static bool IsFieldDeclInt(const clang::FieldDecl *field)
199{
200 return IsTypeInt(field->getType().getTypePtr());
201}
202
203////////////////////////////////////////////////////////////////////////////////
204/// Return a data member name 'what' in the class described by 'cl' if any.
205
206static const clang::FieldDecl *GetDataMemberFromAll(const clang::CXXRecordDecl &cl, llvm::StringRef what)
207{
208 clang::ASTContext &C = cl.getASTContext();
209 clang::DeclarationName DName = &C.Idents.get(what);
210 auto R = cl.lookup(DName);
211 for (const clang::NamedDecl *D : R)
212 if (auto FD = llvm::dyn_cast<const clang::FieldDecl>(D))
213 return FD;
214 return nullptr;
215}
216
217////////////////////////////////////////////////////////////////////////////////
218/// Return a data member name 'what' in any of the base classes of the class described by 'cl' if any.
219
220static const clang::FieldDecl *GetDataMemberFromAllParents(clang::Sema &SemaR, const clang::CXXRecordDecl &cl, const char *what)
221{
222 clang::DeclarationName DName = &SemaR.Context.Idents.get(what);
223 clang::LookupResult R(SemaR, DName, clang::SourceLocation(),
224 clang::Sema::LookupOrdinaryName,
225 clang::Sema::ForExternalRedeclaration);
226 SemaR.LookupInSuper(R, &const_cast<clang::CXXRecordDecl&>(cl));
227 if (R.empty())
228 return nullptr;
229 return llvm::dyn_cast<const clang::FieldDecl>(R.getFoundDecl());
230}
231
232static
233cling::LookupHelper::DiagSetting ToLHDS(bool wantDiags) {
234 return wantDiags
235 ? cling::LookupHelper::WithDiagnostics
236 : cling::LookupHelper::NoDiagnostics;
237}
238
239} // end of anonymous namespace
240
241
242namespace ROOT {
243namespace TMetaUtils {
244
245////////////////////////////////////////////////////////////////////////////////
246/// Add to the internal map the pointer of a template as key and the number of
247/// template arguments to keep as value.
248
249void TNormalizedCtxtImpl::AddTemplAndNargsToKeep(const clang::ClassTemplateDecl* templ,
250 unsigned int i){
251 if (!templ){
252 Error("TNormalizedCtxt::AddTemplAndNargsToKeep",
253 "Tring to specify a number of template arguments to keep for a null pointer. Exiting without assigning any value.\n");
254 return;
255 }
256
257 const clang::ClassTemplateDecl* canTempl = templ->getCanonicalDecl();
258
259 if(fTemplatePtrArgsToKeepMap.count(canTempl)==1 &&
260 fTemplatePtrArgsToKeepMap[canTempl]!=(int)i){
261 const std::string templateName (canTempl->getNameAsString());
262 const std::string i_str (std::to_string(i));
263 const std::string previousArgsToKeep(std::to_string(fTemplatePtrArgsToKeepMap[canTempl]));
264 Error("TNormalizedCtxt::AddTemplAndNargsToKeep",
265 "Tring to specify for template %s %s arguments to keep, while before this number was %s\n",
266 canTempl->getNameAsString().c_str(),
267 i_str.c_str(),
268 previousArgsToKeep.c_str());
269 }
270
271 fTemplatePtrArgsToKeepMap[canTempl]=i;
272}
273////////////////////////////////////////////////////////////////////////////////
274/// Get from the map the number of arguments to keep.
275/// It uses the canonical decl of the template as key.
276/// If not present, returns -1.
277
278int TNormalizedCtxtImpl::GetNargsToKeep(const clang::ClassTemplateDecl* templ) const{
279 const clang::ClassTemplateDecl* constTempl = templ->getCanonicalDecl();
280 auto thePairPtr = fTemplatePtrArgsToKeepMap.find(constTempl);
281 int nArgsToKeep = (thePairPtr != fTemplatePtrArgsToKeepMap.end() ) ? thePairPtr->second : -1;
282 return nArgsToKeep;
283}
284
285
286////////////////////////////////////////////////////////////////////////////////
287
288TNormalizedCtxt::TNormalizedCtxt(const cling::LookupHelper &lh):
289 fImpl(new TNormalizedCtxtImpl(lh))
290{}
291
293 fImpl(new TNormalizedCtxtImpl(*other.fImpl))
294{}
295
297 delete fImpl;
298}
300 return fImpl->GetConfig();
301}
304}
305void TNormalizedCtxt::AddTemplAndNargsToKeep(const clang::ClassTemplateDecl* templ, unsigned int i)
306{
307 return fImpl->AddTemplAndNargsToKeep(templ, i);
308}
309int TNormalizedCtxt::GetNargsToKeep(const clang::ClassTemplateDecl* templ) const
310{
311 return fImpl->GetNargsToKeep(templ);
312}
315}
316void TNormalizedCtxt::keepTypedef(const cling::LookupHelper &lh, const char* name,
317 bool replace /*= false*/)
318{
319 return fImpl->keepTypedef(lh, name, replace);
320}
321
322std::string AnnotatedRecordDecl::BuildDemangledTypeInfo(const clang::RecordDecl *rDecl,
323 const std::string &normalizedName)
324{
325 // Types with strong typedefs must not be findable through demangled type names, or else
326 // the demangled name will resolve to both sinblings double / Double32_t.
327 if (normalizedName.find("Double32_t") != std::string::npos
328 || normalizedName.find("Float16_t") != std::string::npos)
329 return {};
330 std::unique_ptr<clang::MangleContext> mangleCtx(rDecl->getASTContext().createMangleContext());
331 std::string mangledName;
332 {
333 llvm::raw_string_ostream sstr(mangledName);
334 if (const clang::TypeDecl* TD = llvm::dyn_cast<clang::TypeDecl>(rDecl)) {
335 mangleCtx->mangleCXXRTTI(clang::QualType(TD->getTypeForDecl(), 0), sstr);
336 }
337 }
338 if (!mangledName.empty()) {
339 int errDemangle = 0;
340#ifdef WIN32
341 if (mangledName[0] == '\01')
342 mangledName.erase(0, 1);
343 char *demangledTIName = TClassEdit::DemangleName(mangledName.c_str(), errDemangle);
344 if (!errDemangle && demangledTIName) {
345 static const char typeinfoNameFor[] = " `RTTI Type Descriptor'";
346 if (strstr(demangledTIName, typeinfoNameFor)) {
347 std::string demangledName = demangledTIName;
348 demangledName.erase(demangledName.end() - strlen(typeinfoNameFor), demangledName.end());
349#else
350 char* demangledTIName = TClassEdit::DemangleName(mangledName.c_str(), errDemangle);
351 if (!errDemangle && demangledTIName) {
352 static const char typeinfoNameFor[] = "typeinfo for ";
353 if (!strncmp(demangledTIName, typeinfoNameFor, strlen(typeinfoNameFor))) {
354 std::string demangledName = demangledTIName + strlen(typeinfoNameFor);
355#endif
356 free(demangledTIName);
357 return demangledName;
358 } else {
359#ifdef WIN32
360 ROOT::TMetaUtils::Error("AnnotatedRecordDecl::BuildDemangledTypeInfo",
361 "Demangled typeinfo name '%s' does not contain `RTTI Type Descriptor'\n",
362 demangledTIName);
363#else
364 ROOT::TMetaUtils::Error("AnnotatedRecordDecl::BuildDemangledTypeInfo",
365 "Demangled typeinfo name '%s' does not start with 'typeinfo for'\n",
366 demangledTIName);
367#endif
368 } // if demangled type_info starts with "typeinfo for "
369 } // if demangling worked
370 free(demangledTIName);
371 } // if mangling worked
372 return {};
373}
374
375
376////////////////////////////////////////////////////////////////////////////////
377/// There is no requested type name.
378/// Still let's normalized the actual name.
379
381 const clang::RecordDecl *decl,
382 bool rStreamerInfo,
383 bool rNoStreamer,
384 bool rRequestNoInputOperator,
385 bool rRequestOnlyTClass,
386 int rRequestedVersionNumber,
387 const cling::Interpreter &interpreter,
388 const TNormalizedCtxt &normCtxt) :
389 fRuleIndex(index), fDecl(decl), fRequestStreamerInfo(rStreamerInfo), fRequestNoStreamer(rNoStreamer),
390 fRequestNoInputOperator(rRequestNoInputOperator), fRequestOnlyTClass(rRequestOnlyTClass), fRequestedVersionNumber(rRequestedVersionNumber)
391{
392 TMetaUtils::GetNormalizedName(fNormalizedName, decl->getASTContext().getTypeDeclType(decl), interpreter,normCtxt);
394}
395
396////////////////////////////////////////////////////////////////////////////////
397/// Normalize the requested type name.
398
400 const clang::Type *requestedType,
401 const clang::RecordDecl *decl,
402 const char *requestName,
403 unsigned int nTemplateArgsToSkip,
404 bool rStreamerInfo,
405 bool rNoStreamer,
406 bool rRequestNoInputOperator,
407 bool rRequestOnlyTClass,
408 int rRequestVersionNumber,
409 const cling::Interpreter &interpreter,
410 const TNormalizedCtxt &normCtxt) :
411 fRuleIndex(index), fDecl(decl), fRequestedName(""), fRequestStreamerInfo(rStreamerInfo), fRequestNoStreamer(rNoStreamer),
412 fRequestNoInputOperator(rRequestNoInputOperator), fRequestOnlyTClass(rRequestOnlyTClass), fRequestedVersionNumber(rRequestVersionNumber)
413{
414 // For comparison purposes.
416 splitname1.ShortType(fRequestedName, 0);
417
418 TMetaUtils::GetNormalizedName( fNormalizedName, clang::QualType(requestedType,0), interpreter, normCtxt);
419 if ( 0!=TMetaUtils::RemoveTemplateArgsFromName( fNormalizedName, nTemplateArgsToSkip) ){
420 ROOT::TMetaUtils::Warning("AnnotatedRecordDecl",
421 "Could not remove the requested template arguments.\n");
422 }
424}
425
426////////////////////////////////////////////////////////////////////////////////
427/// Normalize the requested type name.
428
430 const clang::Type *requestedType,
431 const clang::RecordDecl *decl,
432 const char *requestName,
433 bool rStreamerInfo,
434 bool rNoStreamer,
435 bool rRequestNoInputOperator,
436 bool rRequestOnlyTClass,
437 int rRequestVersionNumber,
438 const cling::Interpreter &interpreter,
439 const TNormalizedCtxt &normCtxt) :
440 fRuleIndex(index), fDecl(decl), fRequestedName(""), fRequestStreamerInfo(rStreamerInfo), fRequestNoStreamer(rNoStreamer),
441 fRequestNoInputOperator(rRequestNoInputOperator), fRequestOnlyTClass(rRequestOnlyTClass), fRequestedVersionNumber(rRequestVersionNumber)
442{
443 // For comparison purposes.
445 splitname1.ShortType(fRequestedName, 0);
446
447 TMetaUtils::GetNormalizedName( fNormalizedName, clang::QualType(requestedType,0), interpreter, normCtxt);
449}
450
451////////////////////////////////////////////////////////////////////////////////
452/// Normalize the requested name.
453
455 const clang::RecordDecl *decl,
456 const char *requestName,
457 bool rStreamerInfo,
458 bool rNoStreamer,
459 bool rRequestNoInputOperator,
460 bool rRequestOnlyTClass,
461 int rRequestVersionNumber,
462 const cling::Interpreter &interpreter,
463 const TNormalizedCtxt &normCtxt) :
464 fRuleIndex(index), fDecl(decl), fRequestedName(""), fRequestStreamerInfo(rStreamerInfo), fRequestNoStreamer(rNoStreamer), fRequestNoInputOperator(rRequestNoInputOperator), fRequestOnlyTClass(rRequestOnlyTClass), fRequestedVersionNumber(rRequestVersionNumber)
465{
466 // const clang::ClassTemplateSpecializationDecl *tmplt_specialization = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl> (decl);
467 // if (tmplt_specialization) {
468 // tmplt_specialization->getTemplateArgs ().data()->print(decl->getASTContext().getPrintingPolicy(),llvm::outs());
469 // llvm::outs() << "\n";
470 // }
471 // const char *current = requestName;
472 // Strips spaces and std::
473 if (requestName && requestName[0]) {
476
478 } else {
479 TMetaUtils::GetNormalizedName( fNormalizedName, decl->getASTContext().getTypeDeclType(decl),interpreter,normCtxt);
480 }
482}
483
484////////////////////////////////////////////////////////////////////////////////
485
486TClingLookupHelper::TClingLookupHelper(cling::Interpreter &interpreter,
487 TNormalizedCtxt &normCtxt,
488 ExistingTypeCheck_t existingTypeCheck,
489 AutoParse_t autoParse,
490 bool *shuttingDownPtr,
491 const int* pgDebug /*= 0*/):
492 fInterpreter(&interpreter),fNormalizedCtxt(&normCtxt),
493 fExistingTypeCheck(existingTypeCheck),
494 fAutoParse(autoParse),
495 fInterpreterIsShuttingDownPtr(shuttingDownPtr),
496 fPDebug(pgDebug)
497{
498}
499
500////////////////////////////////////////////////////////////////////////////////
501/// Helper routine to ry hard to avoid looking up in the Cling database as
502/// this could enduce an unwanted autoparsing.
503
504bool TClingLookupHelper::ExistingTypeCheck(const std::string &tname,
505 std::string &result)
506{
507 if (tname.empty()) return false;
508
510 else return false;
511}
512
513////////////////////////////////////////////////////////////////////////////////
514
516{
517 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
518 clang::QualType t = lh.findType(nameLong, ToLHDS(WantDiags()));
519 if (!t.isNull()) {
520 clang::QualType dest = cling::utils::Transform::GetPartiallyDesugaredType(fInterpreter->getCI()->getASTContext(), t, fNormalizedCtxt->GetConfig(), true /* fully qualify */);
521 if (!dest.isNull() && (dest != t)) {
522 // getAsStringInternal() appends.
523 nameLong.clear();
524 dest.getAsStringInternal(nameLong, fInterpreter->getCI()->getASTContext().getPrintingPolicy());
525 }
526 }
527}
528
529////////////////////////////////////////////////////////////////////////////////
530
532 const std::string &nameLong)
533{
534 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
535 clang::QualType t = lh.findType(nondef.c_str(), ToLHDS(WantDiags()));
536 if (!t.isNull()) {
537 clang::QualType dest = cling::utils::Transform::GetPartiallyDesugaredType(fInterpreter->getCI()->getASTContext(), t, fNormalizedCtxt->GetConfig(), true /* fully qualify */);
538 if (!dest.isNull() && (dest != t) &&
539 nameLong == t.getAsString(fInterpreter->getCI()->getASTContext().getPrintingPolicy()))
540 return true;
541 }
542 return false;
543}
544
545////////////////////////////////////////////////////////////////////////////////
546
547bool TClingLookupHelper::IsDeclaredScope(const std::string &base, bool &isInlined)
548{
549 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
550 const clang::Decl *scope = lh.findScope(base.c_str(), ToLHDS(WantDiags()), 0);
551
552 if (!scope) {
553 // the nesting namespace is not declared
554 isInlined = false;
555 return false;
556 }
557 const clang::NamespaceDecl *nsdecl = llvm::dyn_cast<clang::NamespaceDecl>(scope);
558 isInlined = nsdecl && nsdecl->isInline();
559 return true;
560}
561
562////////////////////////////////////////////////////////////////////////////////
563/// We assume that we have a simple type:
564/// [const] typename[*&][const]
565
567 std::string &result,
568 bool dropstd /* = true */)
569{
570 if (tname.empty()) return false;
571
572 // Try hard to avoid looking up in the Cling database as this could enduce
573 // an unwanted autoparsing.
574 // Note: this is always done by the callers and thus is redundant.
575 // Maybe replace with
576 assert(! (fExistingTypeCheck && fExistingTypeCheck(tname,result)) );
578 return ! result.empty();
579 }
580
581 if (fAutoParse) fAutoParse(tname.c_str());
582
583 // Since we already check via other means (TClassTable which is populated by
584 // the dictonary loading, and the gROOT list of classes and enums, which are
585 // populated via TProtoClass/Enum), we should be able to disable the autoloading
586 // ... which requires access to libCore or libCling ...
587 const cling::LookupHelper& lh = fInterpreter->getLookupHelper();
588 clang::QualType t = lh.findType(tname.c_str(), ToLHDS(WantDiags()));
589 // Technically we ought to try:
590 // if (t.isNull()) t = lh.findType(TClassEdit::InsertStd(tname), ToLHDS(WantDiags()));
591 // at least until the 'normalized name' contains the std:: prefix.
592
593 if (!t.isNull()) {
595 if (!dest.isNull() && dest != t) {
596 // Since our input is not a template instance name, rather than going through the full
597 // TMetaUtils::GetNormalizedName, we just do the 'strip leading std' and fix
598 // white space.
599 clang::PrintingPolicy policy(fInterpreter->getCI()->getASTContext().getPrintingPolicy());
600 policy.SuppressTagKeyword = true; // Never get the class or struct keyword
601 policy.SuppressScope = true; // Force the scope to be coming from a clang::ElaboratedType.
602 // The scope suppression is required for getting rid of the anonymous part of the name of a class defined in an anonymous namespace.
603 // This gives us more control vs not using the clang::ElaboratedType and relying on the Policy.SuppressUnwrittenScope which would
604 // strip both the anonymous and the inline namespace names (and we probably do not want the later to be suppressed).
605 // getAsStringInternal() appends.
606 result.clear();
607 dest.getAsStringInternal(result, policy);
608 // Strip the std::
609 unsigned long offset = 0;
610 if (strncmp(result.c_str(), "const ", 6) == 0) {
611 offset = 6;
612 }
613 if (dropstd && strncmp(result.c_str()+offset, "std::", 5) == 0) {
614 result.erase(offset,5);
615 }
616 for(unsigned int i = 1; i<result.length(); ++i) {
617 if (result[i]=='s') {
618 if (result[i-1]=='<' || result[i-1]==',' || result[i-1]==' ') {
619 if (dropstd && result.compare(i,5,"std::",5) == 0) {
620 result.erase(i,5);
621 }
622 }
623 }
624 if (result[i]==' ') {
625 if (result[i-1] == ',') {
626 result.erase(i,1);
627 --i;
628 } else if ( (i+1) < result.length() &&
629 (result[i+1]=='*' || result[i+1]=='&' || result[i+1]=='[') ) {
630 result.erase(i,1);
631 --i;
632 }
633 }
634 }
635
636// std::string alt;
637// TMetaUtils::GetNormalizedName(alt, dest, *fInterpreter, *fNormalizedCtxt);
638// if (alt != result) fprintf(stderr,"norm: %s vs result=%s\n",alt.c_str(),result.c_str());
639
640 return true;
641 }
642 }
643 return false;
644}
645
646////////////////////////////////////////////////////////////////////////////////
647// TClassEdit will call this routine as soon as any of its static variable (used
648// for caching) is destroyed.
650{
653}
654
655 } // end namespace ROOT
656} // end namespace TMetaUtils
657
658
659////////////////////////////////////////////////////////////////////////////////
660/// Insert the type with name into the collection of typedefs to keep.
661/// if replace, replace occurrences of the canonical type by name.
662
663void ROOT::TMetaUtils::TNormalizedCtxtImpl::keepTypedef(const cling::LookupHelper &lh,
664 const char* name,
665 bool replace /*=false*/) {
666 clang::QualType toSkip = lh.findType(name, cling::LookupHelper::WithDiagnostics);
667 if (const clang::Type* T = toSkip.getTypePtr()) {
668 const clang::TypedefType *tt = llvm::dyn_cast<clang::TypedefType>(T);
669 if (!tt) return;
670 clang::Decl* D = tt->getDecl();
671 fConfig.m_toSkip.insert(D);
672 if (replace) {
673 clang::QualType canon = toSkip->getCanonicalTypeInternal();
674 fConfig.m_toReplace.insert(std::make_pair(canon.getTypePtr(),T));
675 } else {
676 fTypeWithAlternative.insert(T);
677 }
678 }
679}
680
681////////////////////////////////////////////////////////////////////////////////
682/// Initialize the list of typedef to keep (i.e. make them opaque for normalization)
683/// and the list of typedef whose semantic is different from their underlying type
684/// (Double32_t and Float16_t).
685/// This might be specific to an interpreter.
686
688{
689 keepTypedef(lh, "Double32_t");
690 keepTypedef(lh, "Float16_t");
691 keepTypedef(lh, "Long64_t", true);
692 keepTypedef(lh, "ULong64_t", true);
693
694 clang::QualType toSkip = lh.findType("string", cling::LookupHelper::WithDiagnostics);
695 if (!toSkip.isNull()) {
696 if (const clang::TypedefType* TT
697 = llvm::dyn_cast_or_null<clang::TypedefType>(toSkip.getTypePtr()))
698 fConfig.m_toSkip.insert(TT->getDecl());
699 }
700 toSkip = lh.findType("std::string", cling::LookupHelper::WithDiagnostics);
701 if (!toSkip.isNull()) {
702 if (const clang::TypedefType* TT
703 = llvm::dyn_cast_or_null<clang::TypedefType>(toSkip.getTypePtr()))
704 fConfig.m_toSkip.insert(TT->getDecl());
705
706 clang::QualType canon = toSkip->getCanonicalTypeInternal();
707 fConfig.m_toReplace.insert(std::make_pair(canon.getTypePtr(),toSkip.getTypePtr()));
708 }
709}
710
713
714////////////////////////////////////////////////////////////////////////////////
715
716inline bool IsTemplate(const clang::Decl &cl)
717{
718 return (cl.getKind() == clang::Decl::ClassTemplatePartialSpecialization
719 || cl.getKind() == clang::Decl::ClassTemplateSpecialization);
720}
721
722
723////////////////////////////////////////////////////////////////////////////////
724
725const clang::FunctionDecl* ROOT::TMetaUtils::ClassInfo__HasMethod(const clang::DeclContext *cl, const char* name,
726 const cling::Interpreter& interp)
727{
728 clang::Sema* S = &interp.getSema();
729 const clang::NamedDecl* ND = cling::utils::Lookup::Named(S, name, cl);
730 if (ND == (clang::NamedDecl*)-1)
731 return (clang::FunctionDecl*)-1;
732 return llvm::dyn_cast_or_null<clang::FunctionDecl>(ND);
733}
734
735////////////////////////////////////////////////////////////////////////////////
736/// Return the scope corresponding to 'name' or std::'name'
737
738const clang::CXXRecordDecl *
739ROOT::TMetaUtils::ScopeSearch(const char *name, const cling::Interpreter &interp,
740 bool /*diagnose*/, const clang::Type** resultType)
741{
742 const cling::LookupHelper& lh = interp.getLookupHelper();
743 // We have many bogus diagnostics if we allow diagnostics here. Suppress.
744 // FIXME: silence them in the callers.
745 const clang::CXXRecordDecl *result
746 = llvm::dyn_cast_or_null<clang::CXXRecordDecl>
747 (lh.findScope(name, cling::LookupHelper::NoDiagnostics, resultType));
748 if (!result) {
749 std::string std_name("std::");
750 std_name += name;
751 // We have many bogus diagnostics if we allow diagnostics here. Suppress.
752 // FIXME: silence them in the callers.
753 result = llvm::dyn_cast_or_null<clang::CXXRecordDecl>
754 (lh.findScope(std_name, cling::LookupHelper::NoDiagnostics, resultType));
755 }
756 return result;
757}
758
759
760////////////////////////////////////////////////////////////////////////////////
761
762bool ROOT::TMetaUtils::RequireCompleteType(const cling::Interpreter &interp, const clang::CXXRecordDecl *cl)
763{
764 clang::QualType qType(cl->getTypeForDecl(),0);
765 return RequireCompleteType(interp,cl->getLocation(),qType);
766}
767
768////////////////////////////////////////////////////////////////////////////////
769
770bool ROOT::TMetaUtils::RequireCompleteType(const cling::Interpreter &interp, clang::SourceLocation Loc, clang::QualType Type)
771{
772 clang::Sema& S = interp.getCI()->getSema();
773 // Here we might not have an active transaction to handle
774 // the caused instantiation decl.
775 cling::Interpreter::PushTransactionRAII RAII(const_cast<cling::Interpreter*>(&interp));
776 return S.RequireCompleteType(Loc, Type, clang::diag::err_incomplete_type);
777}
778
779////////////////////////////////////////////////////////////////////////////////
780
781bool ROOT::TMetaUtils::IsBase(const clang::CXXRecordDecl *cl, const clang::CXXRecordDecl *base,
782 const clang::CXXRecordDecl *context, const cling::Interpreter &interp)
783{
784 if (!cl || !base) {
785 return false;
786 }
787
788 if (!cl->getDefinition() || !cl->isCompleteDefinition()) {
789 RequireCompleteType(interp,cl);
790 }
791
792 if (!CheckDefinition(cl, context) || !CheckDefinition(base, context)) {
793 return false;
794 }
795
796 if (!base->hasDefinition()) {
797 ROOT::TMetaUtils::Error("IsBase", "Missing definition for class %s\n", base->getName().str().c_str());
798 return false;
799 }
800 return cl->isDerivedFrom(base);
801}
802
803////////////////////////////////////////////////////////////////////////////////
804
805bool ROOT::TMetaUtils::IsBase(const clang::FieldDecl &m, const char* basename, const cling::Interpreter &interp)
806{
807 const clang::CXXRecordDecl* CRD = llvm::dyn_cast<clang::CXXRecordDecl>(ROOT::TMetaUtils::GetUnderlyingRecordDecl(m.getType()));
808 if (!CRD) {
809 return false;
810 }
811
812 const clang::NamedDecl *base
813 = ScopeSearch(basename, interp, true /*diagnose*/, 0);
814
815 if (base) {
816 return IsBase(CRD, llvm::dyn_cast<clang::CXXRecordDecl>( base ),
817 llvm::dyn_cast<clang::CXXRecordDecl>(m.getDeclContext()),interp);
818 }
819 return false;
820}
821
822////////////////////////////////////////////////////////////////////////////////
823
824int ROOT::TMetaUtils::ElementStreamer(std::ostream& finalString,
825 const clang::NamedDecl &forcontext,
826 const clang::QualType &qti,
827 const char *R__t,int rwmode,
828 const cling::Interpreter &interp,
829 const char *tcl)
830{
831 static const clang::CXXRecordDecl *TObject_decl
832 = ROOT::TMetaUtils::ScopeSearch("TObject", interp, true /*diag*/, 0);
833 enum {
834 kBIT_ISTOBJECT = 0x10000000,
835 kBIT_HASSTREAMER = 0x20000000,
836 kBIT_ISSTRING = 0x40000000,
837
838 kBIT_ISPOINTER = 0x00001000,
839 kBIT_ISFUNDAMENTAL = 0x00000020,
840 kBIT_ISENUM = 0x00000008
841 };
842
843 const clang::Type &ti( * qti.getTypePtr() );
844 std::string tiName;
845 ROOT::TMetaUtils::GetQualifiedName(tiName, clang::QualType(&ti,0), forcontext);
846
847 std::string objType(ROOT::TMetaUtils::ShortTypeName(tiName.c_str()));
848
849 const clang::Type *rawtype = ROOT::TMetaUtils::GetUnderlyingType(clang::QualType(&ti,0));
850 std::string rawname;
851 ROOT::TMetaUtils::GetQualifiedName(rawname, clang::QualType(rawtype,0), forcontext);
852
853 clang::CXXRecordDecl *cxxtype = rawtype->getAsCXXRecordDecl() ;
854 int isStre = cxxtype && ROOT::TMetaUtils::ClassInfo__HasMethod(cxxtype,"Streamer",interp);
855 int isTObj = cxxtype && (IsBase(cxxtype,TObject_decl,nullptr,interp) || rawname == "TObject");
856
857 long kase = 0;
858
859 if (ti.isPointerType()) kase |= kBIT_ISPOINTER;
860 if (rawtype->isFundamentalType()) kase |= kBIT_ISFUNDAMENTAL;
861 if (rawtype->isEnumeralType()) kase |= kBIT_ISENUM;
862
863
864 if (isTObj) kase |= kBIT_ISTOBJECT;
865 if (isStre) kase |= kBIT_HASSTREAMER;
866 if (tiName == "string") kase |= kBIT_ISSTRING;
867 if (tiName == "string*") kase |= kBIT_ISSTRING;
868
869
870 if (tcl == 0) {
871 tcl = " internal error in rootcling ";
872 }
873 // if (strcmp(objType,"string")==0) RStl::Instance().GenerateTClassFor( "string", interp, normCtxt );
874
875 if (rwmode == 0) { //Read mode
876
877 if (R__t) finalString << " " << tiName << " " << R__t << ";" << std::endl;
878 switch (kase) {
879
880 case kBIT_ISFUNDAMENTAL:
881 if (!R__t) return 0;
882 finalString << " R__b >> " << R__t << ";" << std::endl;
883 break;
884
885 case kBIT_ISPOINTER|kBIT_ISTOBJECT|kBIT_HASSTREAMER:
886 if (!R__t) return 1;
887 finalString << " " << R__t << " = (" << tiName << ")R__b.ReadObjectAny(" << tcl << ");" << std::endl;
888 break;
889
890 case kBIT_ISENUM:
891 if (!R__t) return 0;
892 // fprintf(fp, " R__b >> (Int_t&)%s;\n",R__t);
893 // On some platforms enums and not 'Int_t' and casting to a reference to Int_t
894 // induces the silent creation of a temporary which is 'filled' __instead of__
895 // the desired enum. So we need to take it one step at a time.
896 finalString << " Int_t readtemp;" << std::endl
897 << " R__b >> readtemp;" << std::endl
898 << " " << R__t << " = static_cast<" << tiName << ">(readtemp);" << std::endl;
899 break;
900
901 case kBIT_HASSTREAMER:
902 case kBIT_HASSTREAMER|kBIT_ISTOBJECT:
903 if (!R__t) return 0;
904 finalString << " " << R__t << ".Streamer(R__b);" << std::endl;
905 break;
906
907 case kBIT_HASSTREAMER|kBIT_ISPOINTER:
908 if (!R__t) return 1;
909 //fprintf(fp, " fprintf(stderr,\"info is %%p %%d\\n\",R__b.GetInfo(),R__b.GetInfo()?R__b.GetInfo()->GetOldVersion():-1);\n");
910 finalString << " if (R__b.GetInfo() && R__b.GetInfo()->GetOldVersion()<=3) {" << std::endl;
911 if (cxxtype && cxxtype->isAbstract()) {
912 finalString << " R__ASSERT(0);// " << objType << " is abstract. We assume that older file could not be produced using this streaming method." << std::endl;
913 } else {
914 finalString << " " << R__t << " = new " << objType << ";" << std::endl
915 << " " << R__t << "->Streamer(R__b);" << std::endl;
916 }
917 finalString << " } else {" << std::endl
918 << " " << R__t << " = (" << tiName << ")R__b.ReadObjectAny(" << tcl << ");" << std::endl
919 << " }" << std::endl;
920 break;
921
922 case kBIT_ISSTRING:
923 if (!R__t) return 0;
924 finalString << " {TString R__str;" << std::endl
925 << " R__str.Streamer(R__b);" << std::endl
926 << " " << R__t << " = R__str.Data();}" << std::endl;
927 break;
928
929 case kBIT_ISSTRING|kBIT_ISPOINTER:
930 if (!R__t) return 0;
931 finalString << " {TString R__str;" << std::endl
932 << " R__str.Streamer(R__b);" << std::endl
933 << " " << R__t << " = new string(R__str.Data());}" << std::endl;
934 break;
935
936 case kBIT_ISPOINTER:
937 if (!R__t) return 1;
938 finalString << " " << R__t << " = (" << tiName << ")R__b.ReadObjectAny(" << tcl << ");" << std::endl;
939 break;
940
941 default:
942 if (!R__t) return 1;
943 finalString << " R__b.StreamObject(&" << R__t << "," << tcl << ");" << std::endl;
944 break;
945 }
946
947 } else { //Write case
948
949 switch (kase) {
950
951 case kBIT_ISFUNDAMENTAL:
952 case kBIT_ISPOINTER|kBIT_ISTOBJECT|kBIT_HASSTREAMER:
953 if (!R__t) return 0;
954 finalString << " R__b << " << R__t << ";" << std::endl;
955 break;
956
957 case kBIT_ISENUM:
958 if (!R__t) return 0;
959 finalString << " { void *ptr_enum = (void*)&" << R__t << ";\n";
960 finalString << " R__b >> *reinterpret_cast<Int_t*>(ptr_enum); }" << std::endl;
961 break;
962
963 case kBIT_HASSTREAMER:
964 case kBIT_HASSTREAMER|kBIT_ISTOBJECT:
965 if (!R__t) return 0;
966 finalString << " ((" << objType << "&)" << R__t << ").Streamer(R__b);" << std::endl;
967 break;
968
969 case kBIT_HASSTREAMER|kBIT_ISPOINTER:
970 if (!R__t) return 1;
971 finalString << " R__b.WriteObjectAny(" << R__t << "," << tcl << ");" << std::endl;
972 break;
973
974 case kBIT_ISSTRING:
975 if (!R__t) return 0;
976 finalString << " {TString R__str(" << R__t << ".c_str());" << std::endl
977 << " R__str.Streamer(R__b);};" << std::endl;
978 break;
979
980 case kBIT_ISSTRING|kBIT_ISPOINTER:
981 if (!R__t) return 0;
982 finalString << " {TString R__str(" << R__t << "->c_str());" << std::endl
983 << " R__str.Streamer(R__b);}" << std::endl;
984 break;
985
986 case kBIT_ISPOINTER:
987 if (!R__t) return 1;
988 finalString << " R__b.WriteObjectAny(" << R__t << "," << tcl <<");" << std::endl;
989 break;
990
991 default:
992 if (!R__t) return 1;
993 finalString << " R__b.StreamObject((" << objType << "*)&" << R__t << "," << tcl << ");" << std::endl;
994 break;
995 }
996 }
997 return 0;
998}
999
1000////////////////////////////////////////////////////////////////////////////////
1001/// Checks if default constructor exists and accessible
1002
1003bool ROOT::TMetaUtils::CheckDefaultConstructor(const clang::CXXRecordDecl* cl, const cling::Interpreter& interpreter)
1004{
1005 clang::CXXRecordDecl* ncCl = const_cast<clang::CXXRecordDecl*>(cl);
1006
1007 // We may induce template instantiation
1008 cling::Interpreter::PushTransactionRAII clingRAII(const_cast<cling::Interpreter*>(&interpreter));
1009
1010 if (auto* Ctor = interpreter.getCI()->getSema().LookupDefaultConstructor(ncCl)) {
1011 if (Ctor->getAccess() == clang::AS_public && !Ctor->isDeleted()) {
1012 return true;
1013 }
1014 }
1015
1016 return false;
1017}
1018
1019
1020////////////////////////////////////////////////////////////////////////////////
1021/// Checks IO constructor - must be public and with specified argument
1022
1024 const char *typeOfArg,
1025 const clang::CXXRecordDecl *expectedArgType,
1026 const cling::Interpreter& interpreter)
1027{
1028 if (typeOfArg && !expectedArgType) {
1029 const cling::LookupHelper& lh = interpreter.getLookupHelper();
1030 // We can not use findScope since the type we are given are usually,
1031 // only forward declared (and findScope explicitly reject them).
1032 clang::QualType instanceType = lh.findType(typeOfArg, cling::LookupHelper::WithDiagnostics);
1033 if (!instanceType.isNull())
1034 expectedArgType = instanceType->getAsCXXRecordDecl();
1035 }
1036
1037 if (!expectedArgType)
1038 return EIOCtorCategory::kAbsent;
1039
1040 // FIXME: We should not iterate here. That costs memory!
1041 cling::Interpreter::PushTransactionRAII clingRAII(const_cast<cling::Interpreter*>(&interpreter));
1042 for (auto iter = cl->ctor_begin(), end = cl->ctor_end(); iter != end; ++iter)
1043 {
1044 if ((iter->getAccess() != clang::AS_public) || (iter->getNumParams() != 1))
1045 continue;
1046
1047 // We can reach this constructor.
1048 clang::QualType argType((*iter->param_begin())->getType());
1049 argType = argType.getDesugaredType(cl->getASTContext());
1050 // Deal with pointers and references: ROOT-7723
1051 auto ioCtorCategory = EIOCtorCategory::kAbsent;
1052 if (argType->isPointerType()) {
1053 ioCtorCategory = EIOCtorCategory::kIOPtrType;
1054 argType = argType->getPointeeType();
1055 } else if (argType->isReferenceType()) {
1056 ioCtorCategory = EIOCtorCategory::kIORefType;
1057 argType = argType.getNonReferenceType();
1058 } else
1059 continue;
1060
1061 argType = argType.getDesugaredType(cl->getASTContext());
1062 const clang::CXXRecordDecl *argDecl = argType->getAsCXXRecordDecl();
1063 if (argDecl) {
1064 if (argDecl->getCanonicalDecl() == expectedArgType->getCanonicalDecl()) {
1065 return ioCtorCategory;
1066 }
1067 } else {
1068 std::string realArg = argType.getAsString();
1069 std::string clarg("class ");
1070 clarg += typeOfArg;
1071 if (realArg == clarg)
1072 return ioCtorCategory;
1073 }
1074 } // for each constructor
1075
1076 return EIOCtorCategory::kAbsent;
1077}
1078
1079
1080////////////////////////////////////////////////////////////////////////////////
1081/// Check if class has constructor of provided type - either default or with single argument
1082
1084 const RConstructorType &ioctortype,
1085 const cling::Interpreter& interpreter)
1086{
1087 const char *arg = ioctortype.GetName();
1088
1089 if (!ioctortype.GetType() && (!arg || !arg[0])) {
1090 // We are looking for a constructor with zero non-default arguments.
1091
1092 return CheckDefaultConstructor(cl, interpreter) ? EIOCtorCategory::kDefault : EIOCtorCategory::kAbsent;
1093 }
1094
1095 return CheckIOConstructor(cl, arg, ioctortype.GetType(), interpreter);
1096}
1097
1098
1099////////////////////////////////////////////////////////////////////////////////
1100
1101const clang::CXXMethodDecl *GetMethodWithProto(const clang::Decl* cinfo,
1102 const char *method, const char *proto,
1103 const cling::Interpreter &interp,
1104 bool diagnose)
1105{
1106 const clang::FunctionDecl* funcD
1107 = interp.getLookupHelper().findFunctionProto(cinfo, method, proto,
1108 diagnose ? cling::LookupHelper::WithDiagnostics
1109 : cling::LookupHelper::NoDiagnostics);
1110 if (funcD)
1111 return llvm::dyn_cast<const clang::CXXMethodDecl>(funcD);
1112
1113 return nullptr;
1114}
1115
1116
1117////////////////////////////////////////////////////////////////////////////////
1118
1119namespace ROOT {
1120 namespace TMetaUtils {
1121 RConstructorType::RConstructorType(const char *type_of_arg, const cling::Interpreter &interp) : fArgTypeName(type_of_arg),fArgType(nullptr)
1122 {
1123 const cling::LookupHelper& lh = interp.getLookupHelper();
1124 // We can not use findScope since the type we are given are usually,
1125 // only forward declared (and findScope explicitly reject them).
1126 clang::QualType instanceType = lh.findType(type_of_arg, cling::LookupHelper::WithDiagnostics);
1127 if (!instanceType.isNull())
1128 fArgType = instanceType->getAsCXXRecordDecl();
1129 }
1130 const char *RConstructorType::GetName() const { return fArgTypeName.c_str(); }
1131 const clang::CXXRecordDecl *RConstructorType::GetType() const { return fArgType; }
1132 }
1133}
1134
1135////////////////////////////////////////////////////////////////////////////////
1136/// return true if we can find an constructor calleable without any arguments
1137/// or with one the IOCtor special types.
1138
1139bool ROOT::TMetaUtils::HasIOConstructor(const clang::CXXRecordDecl *cl,
1140 std::string& arg,
1141 const RConstructorTypes& ctorTypes,
1142 const cling::Interpreter &interp)
1143{
1144 if (cl->isAbstract()) return false;
1145
1146 for (auto & ctorType : ctorTypes) {
1147
1148 auto ioCtorCat = ROOT::TMetaUtils::CheckConstructor(cl, ctorType, interp);
1149
1150 if (EIOCtorCategory::kAbsent == ioCtorCat)
1151 continue;
1152
1153 std::string proto( ctorType.GetName() );
1154 bool defaultCtor = proto.empty();
1155 if (defaultCtor) {
1156 arg.clear();
1157 } else {
1158 // I/O constructors can take pointers or references to ctorTypes
1159 proto += " *";
1160 if (EIOCtorCategory::kIOPtrType == ioCtorCat) {
1161 arg = "( ("; //(MyType*)nullptr
1162 } else if (EIOCtorCategory::kIORefType == ioCtorCat) {
1163 arg = "( *("; //*(MyType*)nullptr
1164 }
1165 arg += proto;
1166 arg += ")nullptr )";
1167 }
1168 // Check for private operator new
1169 const clang::CXXMethodDecl *method
1170 = GetMethodWithProto(cl, "operator new", "size_t", interp,
1171 cling::LookupHelper::NoDiagnostics);
1172 if (method && method->getAccess() != clang::AS_public) {
1173 // The non-public op new is not going to improve for other c'tors.
1174 return false;
1175 }
1176
1177 // This one looks good!
1178 return true;
1179 }
1180 return false;
1181}
1182
1183////////////////////////////////////////////////////////////////////////////////
1184
1185bool ROOT::TMetaUtils::NeedDestructor(const clang::CXXRecordDecl *cl,
1186 const cling::Interpreter& interp)
1187{
1188 if (!cl) return false;
1189
1190 if (cl->hasUserDeclaredDestructor()) {
1191
1192 cling::Interpreter::PushTransactionRAII clingRAII(const_cast<cling::Interpreter*>(&interp));
1193 clang::CXXDestructorDecl *dest = cl->getDestructor();
1194 if (dest) {
1195 return (dest->getAccess() == clang::AS_public);
1196 } else {
1197 return true; // no destructor, so let's assume it means default?
1198 }
1199 }
1200 return true;
1201}
1202
1203////////////////////////////////////////////////////////////////////////////////
1204/// Return true, if the function (defined by the name and prototype) exists and is public
1205
1206bool ROOT::TMetaUtils::CheckPublicFuncWithProto(const clang::CXXRecordDecl *cl,
1207 const char *methodname,
1208 const char *proto,
1209 const cling::Interpreter &interp,
1210 bool diagnose)
1211{
1212 const clang::CXXMethodDecl *method
1213 = GetMethodWithProto(cl,methodname,proto, interp,
1214 diagnose ? cling::LookupHelper::WithDiagnostics
1215 : cling::LookupHelper::NoDiagnostics);
1216 return (method && method->getAccess() == clang::AS_public);
1217}
1218
1219////////////////////////////////////////////////////////////////////////////////
1220/// Return true if the class has a method DirectoryAutoAdd(TDirectory *)
1221
1222bool ROOT::TMetaUtils::HasDirectoryAutoAdd(const clang::CXXRecordDecl *cl, const cling::Interpreter &interp)
1223{
1224 // Detect if the class has a DirectoryAutoAdd
1225
1226 // Detect if the class or one of its parent has a DirectoryAutoAdd
1227 const char *proto = "TDirectory*";
1228 const char *name = "DirectoryAutoAdd";
1229
1230 return CheckPublicFuncWithProto(cl,name,proto,interp, false /*diags*/);
1231}
1232
1233
1234////////////////////////////////////////////////////////////////////////////////
1235/// Return true if the class has a method Merge(TCollection*,TFileMergeInfo*)
1236
1237bool ROOT::TMetaUtils::HasNewMerge(const clang::CXXRecordDecl *cl, const cling::Interpreter &interp)
1238{
1239 // Detect if the class has a 'new' Merge function.
1240
1241 // Detect if the class or one of its parent has a DirectoryAutoAdd
1242 const char *proto = "TCollection*,TFileMergeInfo*";
1243 const char *name = "Merge";
1244
1245 return CheckPublicFuncWithProto(cl,name,proto,interp, false /*diags*/);
1246}
1247
1248////////////////////////////////////////////////////////////////////////////////
1249/// Return true if the class has a method Merge(TCollection*)
1250
1251bool ROOT::TMetaUtils::HasOldMerge(const clang::CXXRecordDecl *cl, const cling::Interpreter &interp)
1252{
1253 // Detect if the class has an old fashion Merge function.
1254
1255 // Detect if the class or one of its parent has a DirectoryAutoAdd
1256 const char *proto = "TCollection*";
1257 const char *name = "Merge";
1258
1259 return CheckPublicFuncWithProto(cl,name,proto, interp, false /*diags*/);
1260}
1261
1262
1263////////////////////////////////////////////////////////////////////////////////
1264/// Return true if the class has a method ResetAfterMerge(TFileMergeInfo *)
1265
1266bool ROOT::TMetaUtils::HasResetAfterMerge(const clang::CXXRecordDecl *cl, const cling::Interpreter &interp)
1267{
1268 // Detect if the class has a 'new' Merge function.
1269 // bool hasMethod = cl.HasMethod("DirectoryAutoAdd");
1270
1271 // Detect if the class or one of its parent has a DirectoryAutoAdd
1272 const char *proto = "TFileMergeInfo*";
1273 const char *name = "ResetAfterMerge";
1274
1275 return CheckPublicFuncWithProto(cl,name,proto, interp, false /*diags*/);
1276}
1277
1278
1279////////////////////////////////////////////////////////////////////////////////
1280/// Return true if the class has a custom member function streamer.
1281
1283 const clang::CXXRecordDecl* clxx,
1284 const cling::Interpreter &interp,
1285 const TNormalizedCtxt &normCtxt)
1286{
1287 static const char *proto = "TBuffer&";
1288
1289 const clang::CXXMethodDecl *method
1290 = GetMethodWithProto(clxx,"Streamer",proto, interp,
1291 cling::LookupHelper::NoDiagnostics);
1292 const clang::DeclContext *clxx_as_context = llvm::dyn_cast<clang::DeclContext>(clxx);
1293
1294 return (method && method->getDeclContext() == clxx_as_context
1295 && ( cl.RequestNoStreamer() || !cl.RequestStreamerInfo()));
1296}
1297
1298////////////////////////////////////////////////////////////////////////////////
1299/// Return true if the class has a custom member function streamer.
1300
1302 const clang::CXXRecordDecl* clxx,
1303 const cling::Interpreter &interp,
1304 const TNormalizedCtxt &normCtxt)
1305{
1306 static const char *proto = "TBuffer&,TClass*";
1307
1308 const clang::CXXMethodDecl *method
1309 = GetMethodWithProto(clxx,"Streamer",proto, interp,
1310 cling::LookupHelper::NoDiagnostics);
1311 const clang::DeclContext *clxx_as_context = llvm::dyn_cast<clang::DeclContext>(clxx);
1312
1313 return (method && method->getDeclContext() == clxx_as_context
1314 && ( cl.RequestNoStreamer() || !cl.RequestStreamerInfo()));
1315}
1316
1317
1318////////////////////////////////////////////////////////////////////////////////
1319/// Main implementation relying on GetFullyQualifiedTypeName
1320/// All other GetQualifiedName functions leverage this one except the
1321/// one for namespaces.
1322
1323void ROOT::TMetaUtils::GetQualifiedName(std::string &qual_name, const clang::QualType &type, const clang::NamedDecl &forcontext)
1324{
1325 ROOT::TMetaUtils::GetFullyQualifiedTypeName(qual_name, type, forcontext.getASTContext());
1326}
1327
1328//----
1329std::string ROOT::TMetaUtils::GetQualifiedName(const clang::QualType &type, const clang::NamedDecl &forcontext)
1330{
1331 std::string result;
1333 type,
1334 forcontext);
1335 return result;
1336}
1337
1338
1339////////////////////////////////////////////////////////////////////////////////
1340
1341void ROOT::TMetaUtils::GetQualifiedName(std::string& qual_type, const clang::Type &type, const clang::NamedDecl &forcontext)
1342{
1343 clang::QualType qualType(&type,0);
1345 qualType,
1346 forcontext);
1347}
1348
1349//---
1350std::string ROOT::TMetaUtils::GetQualifiedName(const clang::Type &type, const clang::NamedDecl &forcontext)
1351{
1352 std::string result;
1354 type,
1355 forcontext);
1356 return result;
1357}
1358
1359// //______________________________________________________________________________
1360// void ROOT::TMetaUtils::GetQualifiedName(std::string &qual_name, const clang::NamespaceDecl &cl)
1361// {
1362// GetQualifiedName(qual_name,cl);
1363// }
1364//
1365// //----
1366// std::string ROOT::TMetaUtils::GetQualifiedName(const clang::NamespaceDecl &cl){
1367// return GetQualifiedName(cl);
1368// }
1369
1370////////////////////////////////////////////////////////////////////////////////
1371/// This implementation does not rely on GetFullyQualifiedTypeName
1372
1373void ROOT::TMetaUtils::GetQualifiedName(std::string &qual_name, const clang::NamedDecl &cl)
1374{
1375 llvm::raw_string_ostream stream(qual_name);
1376 clang::PrintingPolicy policy( cl.getASTContext().getPrintingPolicy() );
1377 policy.SuppressTagKeyword = true; // Never get the class or struct keyword
1378 policy.SuppressUnwrittenScope = true; // Don't write the inline or anonymous namespace names.
1379
1380 cl.getNameForDiagnostic(stream,policy,true);
1381 stream.flush(); // flush to string.
1382
1383 if ( qual_name == "(anonymous " ) {
1384 size_t pos = qual_name.find(':');
1385 qual_name.erase(0,pos+2);
1386 }
1387}
1388
1389//----
1390std::string ROOT::TMetaUtils::GetQualifiedName(const clang::NamedDecl &cl){
1391 std::string result;
1393 return result;
1394}
1395
1396
1397////////////////////////////////////////////////////////////////////////////////
1398
1399void ROOT::TMetaUtils::GetQualifiedName(std::string &qual_name, const clang::RecordDecl &recordDecl)
1400{
1401 const clang::Type* declType ( recordDecl.getTypeForDecl() );
1402 clang::QualType qualType(declType,0);
1404 qualType,
1405 recordDecl);
1406}
1407
1408//----
1409std::string ROOT::TMetaUtils::GetQualifiedName(const clang::RecordDecl &recordDecl)
1410{
1411 std::string result;
1413 return result;
1414}
1415
1416////////////////////////////////////////////////////////////////////////////////
1417
1419{
1420 ROOT::TMetaUtils::GetQualifiedName(qual_name, *annotated.GetRecordDecl());
1421}
1422
1423//----
1425{
1426 std::string result;
1428 return result;
1429}
1430
1431////////////////////////////////////////////////////////////////////////////////
1432/// Create the data member name-type map for given class
1433
1434void ROOT::TMetaUtils::CreateNameTypeMap(const clang::CXXRecordDecl &cl, ROOT::MembersTypeMap_t& nameType)
1435{
1436 std::stringstream dims;
1437 std::string typenameStr;
1438
1439 const clang::ASTContext& astContext = cl.getASTContext();
1440
1441 // Loop over the non static data member.
1442 for(clang::RecordDecl::field_iterator field_iter = cl.field_begin(), end = cl.field_end();
1443 field_iter != end;
1444 ++field_iter){
1445 // The CINT based code was filtering away static variables (they are not part of
1446 // the list starting with field_begin in clang), and const enums (which should
1447 // also not be part of this list).
1448 // It was also filtering out the 'G__virtualinfo' artificial member.
1449
1450 typenameStr.clear();
1451 dims.str("");
1452 dims.clear();
1453
1454 clang::QualType fieldType(field_iter->getType());
1455 if (fieldType->isConstantArrayType()) {
1456 const clang::ConstantArrayType *arrayType = llvm::dyn_cast<clang::ConstantArrayType>(fieldType.getTypePtr());
1457 while (arrayType) {
1458 dims << "[" << arrayType->getSize().getLimitedValue() << "]";
1459 fieldType = arrayType->getElementType();
1460 arrayType = llvm::dyn_cast<clang::ConstantArrayType>(arrayType->getArrayElementTypeNoTypeQual());
1461 }
1462 }
1463
1464 GetFullyQualifiedTypeName(typenameStr, fieldType, astContext);
1465 nameType[field_iter->getName().str()] = ROOT::Internal::TSchemaType(typenameStr.c_str(),dims.str().c_str());
1466 }
1467
1468 // And now the base classes
1469 // We also need to look at the base classes.
1470 for(clang::CXXRecordDecl::base_class_const_iterator iter = cl.bases_begin(), end = cl.bases_end();
1471 iter != end;
1472 ++iter){
1473 std::string basename( iter->getType()->getAsCXXRecordDecl()->getNameAsString() ); // Intentionally using only the unqualified name.
1474 nameType[basename] = ROOT::Internal::TSchemaType(basename.c_str(),"");
1475 }
1476}
1477
1478////////////////////////////////////////////////////////////////////////////////
1479
1480const clang::FunctionDecl *ROOT::TMetaUtils::GetFuncWithProto(const clang::Decl* cinfo,
1481 const char *method,
1482 const char *proto,
1483 const cling::Interpreter &interp,
1484 bool diagnose)
1485{
1486 return interp.getLookupHelper().findFunctionProto(cinfo, method, proto,
1487 diagnose ? cling::LookupHelper::WithDiagnostics
1488 : cling::LookupHelper::NoDiagnostics);
1489}
1490
1491////////////////////////////////////////////////////////////////////////////////
1492/// It looks like the template specialization decl actually contains _less_ information
1493/// on the location of the code than the decl (in case where there is forward declaration,
1494/// that is what the specialization points to.
1495///
1496/// const clang::CXXRecordDecl* clxx = llvm::dyn_cast<clang::CXXRecordDecl>(decl);
1497/// if (clxx) {
1498/// switch(clxx->getTemplateSpecializationKind()) {
1499/// case clang::TSK_Undeclared:
1500/// // We want the default behavior
1501/// break;
1502/// case clang::TSK_ExplicitInstantiationDeclaration:
1503/// case clang::TSK_ExplicitInstantiationDefinition:
1504/// case clang::TSK_ImplicitInstantiation: {
1505/// // We want the location of the template declaration:
1506/// const clang::ClassTemplateSpecializationDecl *tmplt_specialization = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl> (clxx);
1507/// if (tmplt_specialization) {
1508/// return GetLineNumber(const_cast< clang::ClassTemplateSpecializationDecl *>(tmplt_specialization)->getSpecializedTemplate());
1509/// }
1510/// break;
1511/// }
1512/// case clang::TSK_ExplicitSpecialization:
1513/// // We want the default behavior
1514/// break;
1515/// default:
1516/// break;
1517/// }
1518/// }
1519
1520long ROOT::TMetaUtils::GetLineNumber(const clang::Decl *decl)
1521{
1522 clang::SourceLocation sourceLocation = decl->getLocation();
1523 clang::SourceManager& sourceManager = decl->getASTContext().getSourceManager();
1524
1525 if (!sourceLocation.isValid() ) {
1526 return -1;
1527 }
1528
1529 if (!sourceLocation.isFileID()) {
1530 sourceLocation = sourceManager.getExpansionRange(sourceLocation).getEnd();
1531 }
1532
1533 if (sourceLocation.isValid() && sourceLocation.isFileID()) {
1534 return sourceManager.getLineNumber(sourceManager.getFileID(sourceLocation),sourceManager.getFileOffset(sourceLocation));
1535 }
1536 else {
1537 return -1;
1538 }
1539}
1540
1541////////////////////////////////////////////////////////////////////////////////
1542/// Return true if the type is a Double32_t or Float16_t or
1543/// is a instance template that depends on Double32_t or Float16_t.
1544
1545bool ROOT::TMetaUtils::hasOpaqueTypedef(clang::QualType instanceType, const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt)
1546{
1547 while (llvm::isa<clang::PointerType>(instanceType.getTypePtr())
1548 || llvm::isa<clang::ReferenceType>(instanceType.getTypePtr()))
1549 {
1550 instanceType = instanceType->getPointeeType();
1551 }
1552
1553 const clang::ElaboratedType* etype
1554 = llvm::dyn_cast<clang::ElaboratedType>(instanceType.getTypePtr());
1555 if (etype) {
1556 instanceType = clang::QualType(etype->getNamedType().getTypePtr(),0);
1557 }
1558
1559 // There is no typedef to worried about, except for the opaque ones.
1560
1561 // Technically we should probably used our own list with just
1562 // Double32_t and Float16_t
1563 if (normCtxt.GetTypeWithAlternative().count(instanceType.getTypePtr())) {
1564 return true;
1565 }
1566
1567
1568 bool result = false;
1569 const clang::CXXRecordDecl* clxx = instanceType->getAsCXXRecordDecl();
1570 if (clxx && clxx->getTemplateSpecializationKind() != clang::TSK_Undeclared) {
1571 // do the template thing.
1572 const clang::TemplateSpecializationType* TST
1573 = llvm::dyn_cast<const clang::TemplateSpecializationType>(instanceType.getTypePtr());
1574 if (TST==0) {
1575 // std::string type_name;
1576 // type_name = GetQualifiedName( instanceType, *clxx );
1577 // fprintf(stderr,"ERROR: Could not findS TST for %s\n",type_name.c_str());
1578 return false;
1579 }
1580 for(clang::TemplateSpecializationType::iterator
1581 I = TST->begin(), E = TST->end();
1582 I!=E; ++I)
1583 {
1584 if (I->getKind() == clang::TemplateArgument::Type) {
1585 // std::string arg;
1586 // arg = GetQualifiedName( I->getAsType(), *clxx );
1587 // fprintf(stderr,"DEBUG: looking at %s\n", arg.c_str());
1588 result |= ROOT::TMetaUtils::hasOpaqueTypedef(I->getAsType(), normCtxt);
1589 }
1590 }
1591 }
1592 return result;
1593}
1594
1595////////////////////////////////////////////////////////////////////////////////
1596/// Return true if any of the argument is or contains a double32.
1597
1599 const cling::Interpreter &interp,
1600 const TNormalizedCtxt &normCtxt)
1601{
1602 const clang::CXXRecordDecl *clxx = llvm::dyn_cast<clang::CXXRecordDecl>(cl.GetRecordDecl());
1603 if (!clxx || clxx->getTemplateSpecializationKind() == clang::TSK_Undeclared) return false;
1604
1605 clang::QualType instanceType = interp.getLookupHelper().findType(cl.GetNormalizedName(),
1606 cling::LookupHelper::WithDiagnostics);
1607 if (instanceType.isNull()) {
1608 //Error(0,"Could not find the clang::Type for %s\n",cl.GetNormalizedName());
1609 return false;
1610 }
1611
1612 return ROOT::TMetaUtils::hasOpaqueTypedef(instanceType, normCtxt);
1613}
1614
1615////////////////////////////////////////////////////////////////////////////////
1616/// Extract attr string
1617
1618int ROOT::TMetaUtils::extractAttrString(clang::Attr* attribute, std::string& attrString)
1619{
1620 clang::AnnotateAttr* annAttr = clang::dyn_cast<clang::AnnotateAttr>(attribute);
1621 if (!annAttr) {
1622 //TMetaUtils::Error(0,"Could not cast Attribute to AnnotatedAttribute\n");
1623 return 1;
1624 }
1625 attrString = annAttr->getAnnotation();
1626 return 0;
1627}
1628
1629////////////////////////////////////////////////////////////////////////////////
1630
1631int ROOT::TMetaUtils::extractPropertyNameValFromString(const std::string attributeStr,std::string& attrName, std::string& attrValue)
1632{
1633 // if separator found, extract name and value
1634 size_t substrFound (attributeStr.find(propNames::separator));
1635 if (substrFound==std::string::npos) {
1636 //TMetaUtils::Error(0,"Could not find property name-value separator (%s)\n",ROOT::TMetaUtils::PropertyNameValSeparator.c_str());
1637 return 1;
1638 }
1639 size_t EndPart1 = attributeStr.find_first_of(propNames::separator) ;
1640 attrName = attributeStr.substr(0, EndPart1);
1641 const int separatorLength(propNames::separator.size());
1642 attrValue = attributeStr.substr(EndPart1 + separatorLength);
1643 return 0;
1644}
1645
1646////////////////////////////////////////////////////////////////////////////////
1647
1648int ROOT::TMetaUtils::extractPropertyNameVal(clang::Attr* attribute, std::string& attrName, std::string& attrValue)
1649{
1650 std::string attrString;
1651 int ret = extractAttrString(attribute, attrString);
1652 if (0!=ret) return ret;
1653 return extractPropertyNameValFromString(attrString, attrName,attrValue);
1654}
1655
1656////////////////////////////////////////////////////////////////////////////////
1657/// This routine counts on the "propName<separator>propValue" format
1658
1660 const std::string& propName,
1661 std::string& propValue)
1662{
1663 for (clang::Decl::attr_iterator attrIt = decl.attr_begin();
1664 attrIt!=decl.attr_end();++attrIt){
1665 clang::AnnotateAttr* annAttr = clang::dyn_cast<clang::AnnotateAttr>(*attrIt);
1666 if (!annAttr) continue;
1667
1668 llvm::StringRef attribute = annAttr->getAnnotation();
1669 std::pair<llvm::StringRef,llvm::StringRef> split = attribute.split(propNames::separator.c_str());
1670 if (split.first != propName.c_str()) continue;
1671 else {
1672 propValue = split.second;
1673 return true;
1674 }
1675 }
1676 return false;
1677}
1678
1679////////////////////////////////////////////////////////////////////////////////
1680/// This routine counts on the "propName<separator>propValue" format
1681
1683 const std::string& propName,
1684 int& propValue)
1685{
1686 for (clang::Decl::attr_iterator attrIt = decl.attr_begin();
1687 attrIt!=decl.attr_end();++attrIt){
1688 clang::AnnotateAttr* annAttr = clang::dyn_cast<clang::AnnotateAttr>(*attrIt);
1689 if (!annAttr) continue;
1690
1691 llvm::StringRef attribute = annAttr->getAnnotation();
1692 std::pair<llvm::StringRef,llvm::StringRef> split = attribute.split(propNames::separator.c_str());
1693 if (split.first != propName.c_str()) continue;
1694 else {
1695 return split.second.getAsInteger(10,propValue);
1696 }
1697 }
1698 return false;
1699}
1700
1701////////////////////////////////////////////////////////////////////////////////
1702/// FIXME: a function of 450+ lines!
1703
1704void ROOT::TMetaUtils::WriteClassInit(std::ostream& finalString,
1705 const AnnotatedRecordDecl &cl,
1706 const clang::CXXRecordDecl *decl,
1707 const cling::Interpreter &interp,
1708 const TNormalizedCtxt &normCtxt,
1709 const RConstructorTypes& ctorTypes,
1710 bool& needCollectionProxy)
1711{
1712 std::string classname = TClassEdit::GetLong64_Name(cl.GetNormalizedName());
1713
1714 std::string mappedname;
1715 ROOT::TMetaUtils::GetCppName(mappedname,classname.c_str());
1716 std::string csymbol = classname;
1717 std::string args;
1718
1719 if ( ! TClassEdit::IsStdClass( classname.c_str() ) ) {
1720
1721 // Prefix the full class name with '::' except for the STL
1722 // containers and std::string. This is to request the
1723 // real class instead of the class in the namespace ROOT::Shadow
1724 csymbol.insert(0,"::");
1725 }
1726
1727 int stl = TClassEdit::IsSTLCont(classname);
1728 bool bset = TClassEdit::IsSTLBitset(classname.c_str());
1729
1730 bool isStd = TMetaUtils::IsStdClass(*decl);
1731 const cling::LookupHelper& lh = interp.getLookupHelper();
1732 bool isString = TMetaUtils::IsOfType(*decl,"std::string",lh);
1733
1734 bool isStdNotString = isStd && !isString;
1735
1736 finalString << "namespace ROOT {" << "\n";
1737
1738 if (!ClassInfo__HasMethod(decl,"Dictionary",interp) || IsTemplate(*decl))
1739 {
1740 finalString << " static TClass *" << mappedname.c_str() << "_Dictionary();\n"
1741 << " static void " << mappedname.c_str() << "_TClassManip(TClass*);\n";
1742
1743
1744 }
1745
1746 if (HasIOConstructor(decl, args, ctorTypes, interp)) {
1747 finalString << " static void *new_" << mappedname.c_str() << "(void *p = nullptr);" << "\n";
1748
1749 if (args.size()==0 && NeedDestructor(decl, interp))
1750 {
1751 finalString << " static void *newArray_";
1752 finalString << mappedname.c_str();
1753 finalString << "(Long_t size, void *p);";
1754 finalString << "\n";
1755 }
1756 }
1757
1758 if (NeedDestructor(decl, interp)) {
1759 finalString << " static void delete_" << mappedname.c_str() << "(void *p);" << "\n" << " static void deleteArray_" << mappedname.c_str() << "(void *p);" << "\n" << " static void destruct_" << mappedname.c_str() << "(void *p);" << "\n";
1760 }
1761 if (HasDirectoryAutoAdd(decl, interp)) {
1762 finalString << " static void directoryAutoAdd_" << mappedname.c_str() << "(void *obj, TDirectory *dir);" << "\n";
1763 }
1764 if (HasCustomStreamerMemberFunction(cl, decl, interp, normCtxt)) {
1765 finalString << " static void streamer_" << mappedname.c_str() << "(TBuffer &buf, void *obj);" << "\n";
1766 }
1767 if (HasCustomConvStreamerMemberFunction(cl, decl, interp, normCtxt)) {
1768 finalString << " static void conv_streamer_" << mappedname.c_str() << "(TBuffer &buf, void *obj, const TClass*);" << "\n";
1769 }
1770 if (HasNewMerge(decl, interp) || HasOldMerge(decl, interp)) {
1771 finalString << " static Long64_t merge_" << mappedname.c_str() << "(void *obj, TCollection *coll,TFileMergeInfo *info);" << "\n";
1772 }
1773 if (HasResetAfterMerge(decl, interp)) {
1774 finalString << " static void reset_" << mappedname.c_str() << "(void *obj, TFileMergeInfo *info);" << "\n";
1775 }
1776
1777 //--------------------------------------------------------------------------
1778 // Check if we have any schema evolution rules for this class
1779 /////////////////////////////////////////////////////////////////////////////
1780
1781 ROOT::SchemaRuleClassMap_t::iterator rulesIt1 = ROOT::gReadRules.find( classname.c_str() );
1782 ROOT::SchemaRuleClassMap_t::iterator rulesIt2 = ROOT::gReadRawRules.find( classname.c_str() );
1783
1784 ROOT::MembersTypeMap_t nameTypeMap;
1785 CreateNameTypeMap( *decl, nameTypeMap ); // here types for schema evo are written
1786
1787 //--------------------------------------------------------------------------
1788 // Process the read rules
1789 /////////////////////////////////////////////////////////////////////////////
1790
1791 if( rulesIt1 != ROOT::gReadRules.end() ) {
1792 int i = 0;
1793 finalString << "\n // Schema evolution read functions\n";
1794 std::list<ROOT::SchemaRuleMap_t>::iterator rIt = rulesIt1->second.begin();
1795 while( rIt != rulesIt1->second.end() ) {
1796
1797 //--------------------------------------------------------------------
1798 // Check if the rules refer to valid data members
1799 ///////////////////////////////////////////////////////////////////////
1800
1801 std::string error_string;
1802 if( !HasValidDataMembers( *rIt, nameTypeMap, error_string ) ) {
1803 Warning(0, "%s", error_string.c_str());
1804 rIt = rulesIt1->second.erase(rIt);
1805 continue;
1806 }
1807
1808 //---------------------------------------------------------------------
1809 // Write the conversion function if necessary
1810 ///////////////////////////////////////////////////////////////////////
1811
1812 if( rIt->find( "code" ) != rIt->end() ) {
1813 WriteReadRuleFunc( *rIt, i++, mappedname, nameTypeMap, finalString );
1814 }
1815 ++rIt;
1816 }
1817 }
1818
1819
1820
1821
1822 //--------------------------------------------------------------------------
1823 // Process the read raw rules
1824 /////////////////////////////////////////////////////////////////////////////
1825
1826 if( rulesIt2 != ROOT::gReadRawRules.end() ) {
1827 int i = 0;
1828 finalString << "\n // Schema evolution read raw functions\n";
1829 std::list<ROOT::SchemaRuleMap_t>::iterator rIt = rulesIt2->second.begin();
1830 while( rIt != rulesIt2->second.end() ) {
1831
1832 //--------------------------------------------------------------------
1833 // Check if the rules refer to valid data members
1834 ///////////////////////////////////////////////////////////////////////
1835
1836 std::string error_string;
1837 if( !HasValidDataMembers( *rIt, nameTypeMap, error_string ) ) {
1838 Warning(0, "%s", error_string.c_str());
1839 rIt = rulesIt2->second.erase(rIt);
1840 continue;
1841 }
1842
1843 //---------------------------------------------------------------------
1844 // Write the conversion function
1845 ///////////////////////////////////////////////////////////////////////
1846
1847 if( rIt->find( "code" ) == rIt->end() )
1848 continue;
1849
1850 WriteReadRawRuleFunc( *rIt, i++, mappedname, nameTypeMap, finalString );
1851 ++rIt;
1852 }
1853 }
1854
1855 finalString << "\n" << " // Function generating the singleton type initializer" << "\n";
1856
1857 finalString << " static TGenericClassInfo *GenerateInitInstanceLocal(const " << csymbol << "*)" << "\n" << " {" << "\n";
1858
1859 finalString << " " << csymbol << " *ptr = nullptr;" << "\n";
1860
1861 //fprintf(fp, " static ::ROOT::ClassInfo< %s > \n",classname.c_str());
1862 if (ClassInfo__HasMethod(decl,"IsA",interp) ) {
1863 finalString << " static ::TVirtualIsAProxy* isa_proxy = new ::TInstrumentedIsAProxy< " << csymbol << " >(nullptr);" << "\n";
1864 }
1865 else {
1866 finalString << " static ::TVirtualIsAProxy* isa_proxy = new ::TIsAProxy(typeid(" << csymbol << "));" << "\n";
1867 }
1868 finalString << " static ::ROOT::TGenericClassInfo " << "\n" << " instance(\"" << classname.c_str() << "\", ";
1869
1870 if (ClassInfo__HasMethod(decl,"Class_Version",interp)) {
1871 finalString << csymbol << "::Class_Version(), ";
1872 } else if (bset) {
1873 finalString << "2, "; // bitset 'version number'
1874 } else if (stl) {
1875 finalString << "-2, "; // "::TStreamerInfo::Class_Version(), ";
1876 } else if( cl.HasClassVersion() ) {
1877 finalString << cl.RequestedVersionNumber() << ", ";
1878 } else { // if (cl_input.RequestStreamerInfo()) {
1879
1880 // Need to find out if the operator>> is actually defined for this class.
1881 static const char *versionFunc = "GetClassVersion";
1882 // int ncha = strlen(classname.c_str())+strlen(versionFunc)+5;
1883 // char *funcname= new char[ncha];
1884 // snprintf(funcname,ncha,"%s<%s >",versionFunc,classname.c_str());
1885 std::string proto = classname + "*";
1886 const clang::Decl* ctxt = llvm::dyn_cast<clang::Decl>((*cl).getDeclContext());
1887 const clang::FunctionDecl *methodinfo
1888 = ROOT::TMetaUtils::GetFuncWithProto(ctxt, versionFunc, proto.c_str(),
1889 interp, cling::LookupHelper::NoDiagnostics);
1890 // delete [] funcname;
1891
1892 if (methodinfo &&
1893 ROOT::TMetaUtils::GetFileName(*methodinfo, interp).find("Rtypes.h") == llvm::StringRef::npos) {
1894
1895 // GetClassVersion was defined in the header file.
1896 //fprintf(fp, "GetClassVersion((%s *)0x0), ",classname.c_str());
1897 finalString << "GetClassVersion< ";
1898 finalString << classname.c_str();
1899 finalString << " >(), ";
1900 }
1901 //static char temporary[1024];
1902 //sprintf(temporary,"GetClassVersion<%s>( (%s *) 0x0 )",classname.c_str(),classname.c_str());
1903 //fprintf(stderr,"DEBUG: %s has value %d\n",classname.c_str(),(int)G__int(G__calc(temporary)));
1904 }
1905
1906 std::string filename = ROOT::TMetaUtils::GetFileName(*cl, interp);
1907 if (filename.length() > 0) {
1908 for (unsigned int i=0; i<filename.length(); i++) {
1909 if (filename[i]=='\\') filename[i]='/';
1910 }
1911 }
1912 finalString << "\"" << filename << "\", " << ROOT::TMetaUtils::GetLineNumber(cl)
1913 << "," << "\n" << " typeid(" << csymbol
1914 << "), ::ROOT::Internal::DefineBehavior(ptr, ptr)," << "\n" << " ";
1915
1916 if (ClassInfo__HasMethod(decl,"Dictionary",interp) && !IsTemplate(*decl)) {
1917 finalString << "&" << csymbol << "::Dictionary, ";
1918 } else {
1919 finalString << "&" << mappedname << "_Dictionary, ";
1920 }
1921
1922 enum {
1923 TClassTable__kHasCustomStreamerMember = 0x10 // See TClassTable.h
1924 };
1925
1926 Int_t rootflag = cl.RootFlag();
1927 if (HasCustomStreamerMemberFunction(cl, decl, interp, normCtxt)) {
1928 rootflag = rootflag | TClassTable__kHasCustomStreamerMember;
1929 }
1930 finalString << "isa_proxy, " << rootflag << "," << "\n" << " sizeof(" << csymbol << ") );" << "\n";
1931 if (HasIOConstructor(decl, args, ctorTypes, interp)) {
1932 finalString << " instance.SetNew(&new_" << mappedname.c_str() << ");" << "\n";
1933 if (args.size()==0 && NeedDestructor(decl, interp))
1934 finalString << " instance.SetNewArray(&newArray_" << mappedname.c_str() << ");" << "\n";
1935 }
1936 if (NeedDestructor(decl, interp)) {
1937 finalString << " instance.SetDelete(&delete_" << mappedname.c_str() << ");" << "\n" << " instance.SetDeleteArray(&deleteArray_" << mappedname.c_str() << ");" << "\n" << " instance.SetDestructor(&destruct_" << mappedname.c_str() << ");" << "\n";
1938 }
1939 if (HasDirectoryAutoAdd(decl, interp)) {
1940 finalString << " instance.SetDirectoryAutoAdd(&directoryAutoAdd_" << mappedname.c_str() << ");" << "\n";
1941 }
1942 if (HasCustomStreamerMemberFunction(cl, decl, interp, normCtxt)) {
1943 // We have a custom member function streamer or an older (not StreamerInfo based) automatic streamer.
1944 finalString << " instance.SetStreamerFunc(&streamer_" << mappedname.c_str() << ");" << "\n";
1945 }
1946 if (HasCustomConvStreamerMemberFunction(cl, decl, interp, normCtxt)) {
1947 // We have a custom member function streamer or an older (not StreamerInfo based) automatic streamer.
1948 finalString << " instance.SetConvStreamerFunc(&conv_streamer_" << mappedname.c_str() << ");" << "\n";
1949 }
1950 if (HasNewMerge(decl, interp) || HasOldMerge(decl, interp)) {
1951 finalString << " instance.SetMerge(&merge_" << mappedname.c_str() << ");" << "\n";
1952 }
1953 if (HasResetAfterMerge(decl, interp)) {
1954 finalString << " instance.SetResetAfterMerge(&reset_" << mappedname.c_str() << ");" << "\n";
1955 }
1956 if (bset) {
1957 finalString << " instance.AdoptCollectionProxyInfo(TCollectionProxyInfo::Generate(TCollectionProxyInfo::" << "Pushback" << "<Internal::TStdBitsetHelper< " << classname.c_str() << " > >()));" << "\n";
1958
1959 needCollectionProxy = true;
1960 } else if (stl != 0 &&
1961 ((stl > 0 && stl<ROOT::kSTLend) || (stl < 0 && stl>-ROOT::kSTLend)) && // is an stl container
1962 (stl != ROOT::kSTLbitset && stl !=-ROOT::kSTLbitset) ){ // is no bitset
1963 int idx = classname.find("<");
1964 int stlType = (idx!=(int)std::string::npos) ? TClassEdit::STLKind(classname.substr(0,idx)) : 0;
1965 const char* methodTCP=0;
1966 switch(stlType) {
1967 case ROOT::kSTLvector:
1968 case ROOT::kSTLlist:
1969 case ROOT::kSTLdeque:
1970 case ROOT::kROOTRVec:
1971 methodTCP="Pushback";
1972 break;
1974 methodTCP="Pushfront";
1975 break;
1976 case ROOT::kSTLmap:
1977 case ROOT::kSTLmultimap:
1980 methodTCP="MapInsert";
1981 break;
1982 case ROOT::kSTLset:
1983 case ROOT::kSTLmultiset:
1986 methodTCP="Insert";
1987 break;
1988 }
1989 // FIXME Workaround: for the moment we do not generate coll proxies with unique ptrs since
1990 // they imply copies and therefore do not compile.
1991 auto classNameForIO = TClassEdit::GetNameForIO(classname);
1992 finalString << " instance.AdoptCollectionProxyInfo(TCollectionProxyInfo::Generate(TCollectionProxyInfo::" << methodTCP << "< " << classNameForIO.c_str() << " >()));" << "\n";
1993
1994 needCollectionProxy = true;
1995 }
1996
1997 //---------------------------------------------------------------------------
1998 // Register Alternate spelling of the class name.
1999 /////////////////////////////////////////////////////////////////////////////
2000
2001 if (cl.GetRequestedName()[0] && classname != cl.GetRequestedName()) {
2002 finalString << "\n" << " ::ROOT::AddClassAlternate(\""
2003 << classname << "\",\"" << cl.GetRequestedName() << "\");\n";
2004 }
2005
2006 if (!cl.GetDemangledTypeInfo().empty()
2007 && cl.GetDemangledTypeInfo() != classname
2008 && cl.GetDemangledTypeInfo() != cl.GetRequestedName()) {
2009 finalString << "\n" << " ::ROOT::AddClassAlternate(\""
2010 << classname << "\",\"" << cl.GetDemangledTypeInfo() << "\");\n";
2011
2012 }
2013
2014 //---------------------------------------------------------------------------
2015 // Pass the schema evolution rules to TGenericClassInfo
2016 /////////////////////////////////////////////////////////////////////////////
2017
2018 if( (rulesIt1 != ROOT::gReadRules.end() && rulesIt1->second.size()>0) || (rulesIt2 != ROOT::gReadRawRules.end() && rulesIt2->second.size()>0) ) {
2019 finalString << "\n" << " ::ROOT::Internal::TSchemaHelper* rule;" << "\n";
2020 }
2021
2022 if( rulesIt1 != ROOT::gReadRules.end() ) {
2023 finalString << "\n" << " // the io read rules" << "\n" << " std::vector<::ROOT::Internal::TSchemaHelper> readrules(" << rulesIt1->second.size() << ");" << "\n";
2024 ROOT::WriteSchemaList( rulesIt1->second, "readrules", finalString );
2025 finalString << " instance.SetReadRules( readrules );" << "\n";
2026 }
2027
2028 if( rulesIt2 != ROOT::gReadRawRules.end() ) {
2029 finalString << "\n" << " // the io read raw rules" << "\n" << " std::vector<::ROOT::Internal::TSchemaHelper> readrawrules(" << rulesIt2->second.size() << ");" << "\n";
2030 ROOT::WriteSchemaList( rulesIt2->second, "readrawrules", finalString );
2031 finalString << " instance.SetReadRawRules( readrawrules );" << "\n";
2032 }
2033
2034 finalString << " return &instance;" << "\n" << " }" << "\n";
2035
2036 if (!isStdNotString && !ROOT::TMetaUtils::hasOpaqueTypedef(cl, interp, normCtxt)) {
2037 // The GenerateInitInstance for STL are not unique and should not be externally accessible
2038 finalString << " TGenericClassInfo *GenerateInitInstance(const " << csymbol << "*)" << "\n" << " {\n return GenerateInitInstanceLocal(static_cast<" << csymbol << "*>(nullptr));\n }" << "\n";
2039 }
2040
2041 finalString << " // Static variable to force the class initialization" << "\n";
2042 // must be one long line otherwise UseDummy does not work
2043
2044
2045 finalString << " static ::ROOT::TGenericClassInfo *_R__UNIQUE_DICT_(Init) = GenerateInitInstanceLocal(static_cast<const " << csymbol << "*>(nullptr)); R__UseDummy(_R__UNIQUE_DICT_(Init));" << "\n";
2046
2047 if (!ClassInfo__HasMethod(decl,"Dictionary",interp) || IsTemplate(*decl)) {
2048 finalString << "\n" << " // Dictionary for non-ClassDef classes" << "\n"
2049 << " static TClass *" << mappedname << "_Dictionary() {\n"
2050 << " TClass* theClass ="
2051 << "::ROOT::GenerateInitInstanceLocal(static_cast<const " << csymbol << "*>(nullptr))->GetClass();\n"
2052 << " " << mappedname << "_TClassManip(theClass);\n";
2053 finalString << " return theClass;\n";
2054 finalString << " }\n\n";
2055
2056 // Now manipulate tclass in order to percolate the properties expressed as
2057 // annotations of the decls.
2058 std::string manipString;
2059 std::string attribute_s;
2060 std::string attrName, attrValue;
2061 // Class properties
2062 bool attrMapExtracted = false;
2063 if (decl->hasAttrs()){
2064 // Loop on the attributes
2065 for (clang::Decl::attr_iterator attrIt = decl->attr_begin();
2066 attrIt!=decl->attr_end();++attrIt){
2067 if ( 0!=ROOT::TMetaUtils::extractAttrString(*attrIt,attribute_s)){
2068 continue;
2069 }
2070 if (0!=ROOT::TMetaUtils::extractPropertyNameValFromString(attribute_s, attrName, attrValue)){
2071 continue;
2072 }
2073 if (attrName == "name" ||
2074 attrName == "pattern" ||
2075 attrName == "rootmap") continue;
2076 // A general property
2077 // 1) We need to create the property map (in the gen code)
2078 // 2) we need to take out the map (in the gen code)
2079 // 3) We need to bookkep the fact that the map is created and out (in this source)
2080 // 4) We fill the map (in the gen code)
2081 if (!attrMapExtracted){
2082 manipString+=" theClass->CreateAttributeMap();\n";
2083 manipString+=" TDictAttributeMap* attrMap( theClass->GetAttributeMap() );\n";
2084 attrMapExtracted=true;
2085 }
2086 manipString+=" attrMap->AddProperty(\""+attrName +"\",\""+attrValue+"\");\n";
2087 }
2088 } // end of class has properties
2089
2090 // Member properties
2091 // Loop on declarations inside the class, including data members
2092 for(clang::CXXRecordDecl::decl_iterator internalDeclIt = decl->decls_begin();
2093 internalDeclIt != decl->decls_end(); ++internalDeclIt){
2094 if (!(!(*internalDeclIt)->isImplicit()
2095 && (clang::isa<clang::FieldDecl>(*internalDeclIt) ||
2096 clang::isa<clang::VarDecl>(*internalDeclIt)))) continue; // Check if it's a var or a field
2097
2098 // Now let's check the attributes of the var/field
2099 if (!internalDeclIt->hasAttrs()) continue;
2100
2101 attrMapExtracted = false;
2102 bool memberPtrCreated = false;
2103
2104 for (clang::Decl::attr_iterator attrIt = internalDeclIt->attr_begin();
2105 attrIt!=internalDeclIt->attr_end();++attrIt){
2106
2107 // Get the attribute as string
2108 if ( 0!=ROOT::TMetaUtils::extractAttrString(*attrIt,attribute_s)){
2109 continue;
2110 }
2111
2112 // Check the name of the decl
2113 clang::NamedDecl* namedInternalDecl = clang::dyn_cast<clang::NamedDecl> (*internalDeclIt);
2114 if (!namedInternalDecl) {
2115 TMetaUtils::Error(0,"Cannot convert field declaration to clang::NamedDecl");
2116 continue;
2117 };
2118 const std::string memberName(namedInternalDecl->getName());
2119 const std::string cppMemberName="theMember_"+memberName;
2120
2121 // Prepare a string to get the data member, it can be used later.
2122 const std::string dataMemberCreation= " TDataMember* "+cppMemberName+" = theClass->GetDataMember(\""+memberName+"\");\n";
2123
2124 // Let's now attack regular properties
2125
2126 if (0!=ROOT::TMetaUtils::extractPropertyNameValFromString(attribute_s, attrName, attrValue)){
2127 continue;
2128 }
2129
2130 // Skip these
2131 if (attrName == propNames::comment ||
2132 attrName == propNames::iotype ||
2133 attrName == propNames::ioname ) continue;
2134
2135 if (!memberPtrCreated){
2136 manipString+=dataMemberCreation;
2137 memberPtrCreated=true;
2138 }
2139
2140 if (!attrMapExtracted){
2141 manipString+=" "+cppMemberName+"->CreateAttributeMap();\n";
2142 manipString+=" TDictAttributeMap* memberAttrMap_"+memberName+"( theMember_"+memberName+"->GetAttributeMap() );\n";
2143 attrMapExtracted=true;
2144 }
2145
2146 manipString+=" memberAttrMap_"+memberName+"->AddProperty(\""+attrName +"\",\""+attrValue+"\");\n";
2147
2148
2149 } // End loop on attributes
2150 } // End loop on internal declarations
2151
2152
2153 finalString << " static void " << mappedname << "_TClassManip(TClass* " << (manipString.empty() ? "":"theClass") << "){\n"
2154 << manipString
2155 << " }\n\n";
2156 } // End of !ClassInfo__HasMethod(decl,"Dictionary") || IsTemplate(*decl))
2157
2158 finalString << "} // end of namespace ROOT" << "\n" << "\n";
2159}
2160
2161////////////////////////////////////////////////////////////////////////////////
2162/// Return true if one of the class' enclosing scope is a namespace and
2163/// set fullname to the fully qualified name,
2164/// clsname to the name within a namespace
2165/// and nsname to the namespace fully qualified name.
2166
2168 std::string &clsname,
2169 std::string &nsname,
2170 const clang::CXXRecordDecl *cl)
2171{
2172 fullname.clear();
2173 nsname.clear();
2174
2176 clsname = fullname;
2177
2178 // Inline namespace are stripped from the normalized name, we need to
2179 // strip it from the prefix we want to remove.
2180 auto ctxt = cl->getEnclosingNamespaceContext();
2181 while(ctxt && ctxt!=cl && ctxt->isInlineNamespace()) {
2182 ctxt = ctxt->getParent();
2183 }
2184 if (ctxt) {
2185 const clang::NamedDecl *namedCtxt = llvm::dyn_cast<clang::NamedDecl>(ctxt);
2186 if (namedCtxt && namedCtxt!=cl) {
2187 const clang::NamespaceDecl *nsdecl = llvm::dyn_cast<clang::NamespaceDecl>(namedCtxt);
2188 if (nsdecl != 0 && !nsdecl->isAnonymousNamespace()) {
2189 ROOT::TMetaUtils::GetQualifiedName(nsname,*nsdecl);
2190 clsname.erase (0, nsname.size() + 2);
2191 return true;
2192 }
2193 }
2194 }
2195 return false;
2196}
2197
2198////////////////////////////////////////////////////////////////////////////////
2199
2200const clang::DeclContext *GetEnclosingSpace(const clang::RecordDecl &cl)
2201{
2202 const clang::DeclContext *ctxt = cl.getDeclContext();
2203 while(ctxt && !ctxt->isNamespace()) {
2204 ctxt = ctxt->getParent();
2205 }
2206 return ctxt;
2207}
2208
2209////////////////////////////////////////////////////////////////////////////////
2210/// Write all the necessary opening part of the namespace and
2211/// return the number of closing brackets needed
2212/// For example for Space1::Space2
2213/// we write: namespace Space1 { namespace Space2 {
2214/// and return 2.
2215
2216int ROOT::TMetaUtils::WriteNamespaceHeader(std::ostream &out, const clang::DeclContext *ctxt)
2217{
2218 int closing_brackets = 0;
2219
2220 //fprintf(stderr,"DEBUG: in WriteNamespaceHeader for %s with %s\n",
2221 // cl.Fullname(),namespace_obj.Fullname());
2222 if (ctxt && ctxt->isNamespace()) {
2223 closing_brackets = WriteNamespaceHeader(out,ctxt->getParent());
2224 const clang::NamespaceDecl *ns = llvm::dyn_cast<clang::NamespaceDecl>(ctxt);
2225 if (ns) {
2226 for (int indent = 0; indent < closing_brackets; ++indent)
2227 out << " ";
2228 if (ns->isInline())
2229 out << "inline ";
2230 out << "namespace " << ns->getNameAsString() << " {" << std::endl;
2231 closing_brackets++;
2232 }
2233 }
2234
2235 return closing_brackets;
2236}
2237
2238////////////////////////////////////////////////////////////////////////////////
2239
2240int ROOT::TMetaUtils::WriteNamespaceHeader(std::ostream &out, const clang::RecordDecl *cl)
2241{
2242 return WriteNamespaceHeader(out, GetEnclosingSpace(*cl));
2243}
2244
2245////////////////////////////////////////////////////////////////////////////////
2246
2247bool ROOT::TMetaUtils::NeedTemplateKeyword(const clang::CXXRecordDecl *cl)
2248{
2249 clang::TemplateSpecializationKind kind = cl->getTemplateSpecializationKind();
2250 if (kind == clang::TSK_Undeclared ) {
2251 // Note a template;
2252 return false;
2253 } else if (kind == clang::TSK_ExplicitSpecialization) {
2254 // This is a specialized templated class
2255 return false;
2256 } else {
2257 // This is an automatically or explicitly instantiated templated class.
2258 return true;
2259 }
2260}
2261
2262////////////////////////////////////////////////////////////////////////////////
2263/// return true if we can find a custom operator new with placement
2264
2265bool ROOT::TMetaUtils::HasCustomOperatorNewPlacement(const char *which, const clang::RecordDecl &cl, const cling::Interpreter &interp)
2266{
2267 const char *name = which;
2268 const char *proto = "size_t";
2269 const char *protoPlacement = "size_t,void*";
2270
2271 // First search in the enclosing namespaces
2272 const clang::FunctionDecl *operatornew
2273 = ROOT::TMetaUtils::GetFuncWithProto(llvm::dyn_cast<clang::Decl>(cl.getDeclContext()),
2274 name, proto, interp,
2275 cling::LookupHelper::NoDiagnostics);
2276 const clang::FunctionDecl *operatornewPlacement
2277 = ROOT::TMetaUtils::GetFuncWithProto(llvm::dyn_cast<clang::Decl>(cl.getDeclContext()),
2278 name, protoPlacement, interp,
2279 cling::LookupHelper::NoDiagnostics);
2280
2281 const clang::DeclContext *ctxtnew = 0;
2282 const clang::DeclContext *ctxtnewPlacement = 0;
2283
2284 if (operatornew) {
2285 ctxtnew = operatornew->getParent();
2286 }
2287 if (operatornewPlacement) {
2288 ctxtnewPlacement = operatornewPlacement->getParent();
2289 }
2290
2291 // Then in the class and base classes
2292 operatornew = ROOT::TMetaUtils::GetFuncWithProto(&cl, name, proto, interp,
2293 false /*diags*/);
2294 operatornewPlacement
2295 = ROOT::TMetaUtils::GetFuncWithProto(&cl, name, protoPlacement, interp,
2296 false /*diags*/);
2297
2298 if (operatornew) {
2299 ctxtnew = operatornew->getParent();
2300 }
2301 if (operatornewPlacement) {
2302 ctxtnewPlacement = operatornewPlacement->getParent();
2303 }
2304
2305 if (ctxtnewPlacement == 0) {
2306 return false;
2307 }
2308 if (ctxtnew == 0) {
2309 // Only a new with placement, no hiding
2310 return true;
2311 }
2312 // Both are non zero
2313 if (ctxtnew == ctxtnewPlacement) {
2314 // Same declaration ctxt, no hiding
2315 return true;
2316 }
2317 const clang::CXXRecordDecl* clnew = llvm::dyn_cast<clang::CXXRecordDecl>(ctxtnew);
2318 const clang::CXXRecordDecl* clnewPlacement = llvm::dyn_cast<clang::CXXRecordDecl>(ctxtnewPlacement);
2319 if (clnew == 0 && clnewPlacement == 0) {
2320 // They are both in different namespaces, I am not sure of the rules.
2321 // we probably ought to find which one is closest ... for now bail
2322 // (because rootcling was also bailing on that).
2323 return true;
2324 }
2325 if (clnew != 0 && clnewPlacement == 0) {
2326 // operator new is class method hiding the outer scope operator new with placement.
2327 return false;
2328 }
2329 if (clnew == 0 && clnewPlacement != 0) {
2330 // operator new is a not class method and can not hide new with placement which is a method
2331 return true;
2332 }
2333 // Both are class methods
2334 if (clnew->isDerivedFrom(clnewPlacement)) {
2335 // operator new is in a more derived part of the hierarchy, it is hiding operator new with placement.
2336 return false;
2337 }
2338 // operator new with placement is in a more derived part of the hierarchy, it can't be hidden by operator new.
2339 return true;
2340}
2341
2342////////////////////////////////////////////////////////////////////////////////
2343/// return true if we can find a custom operator new with placement
2344
2345bool ROOT::TMetaUtils::HasCustomOperatorNewPlacement(const clang::RecordDecl &cl, const cling::Interpreter &interp)
2346{
2347 return HasCustomOperatorNewPlacement("operator new",cl, interp);
2348}
2349
2350////////////////////////////////////////////////////////////////////////////////
2351/// return true if we can find a custom operator new with placement
2352
2353bool ROOT::TMetaUtils::HasCustomOperatorNewArrayPlacement(const clang::RecordDecl &cl, const cling::Interpreter &interp)
2354{
2355 return HasCustomOperatorNewPlacement("operator new[]",cl, interp);
2356}
2357
2358////////////////////////////////////////////////////////////////////////////////
2359/// std::string NormalizedName;
2360/// GetNormalizedName(NormalizedName, decl->getASTContext().getTypeDeclType(decl), interp, normCtxt);
2361
2362void ROOT::TMetaUtils::WriteAuxFunctions(std::ostream& finalString,
2363 const AnnotatedRecordDecl &cl,
2364 const clang::CXXRecordDecl *decl,
2365 const cling::Interpreter &interp,
2366 const RConstructorTypes& ctorTypes,
2367 const TNormalizedCtxt &normCtxt)
2368{
2369 std::string classname = TClassEdit::GetLong64_Name(cl.GetNormalizedName());
2370
2371 std::string mappedname;
2372 ROOT::TMetaUtils::GetCppName(mappedname,classname.c_str());
2373
2374 // Write the functions that are need for the TGenericClassInfo.
2375 // This includes
2376 // IsA
2377 // operator new
2378 // operator new[]
2379 // operator delete
2380 // operator delete[]
2381
2382 ROOT::TMetaUtils::GetCppName(mappedname,classname.c_str());
2383
2384 if ( ! TClassEdit::IsStdClass( classname.c_str() ) ) {
2385
2386 // Prefix the full class name with '::' except for the STL
2387 // containers and std::string. This is to request the
2388 // real class instead of the class in the namespace ROOT::Shadow
2389 classname.insert(0,"::");
2390 }
2391
2392 finalString << "namespace ROOT {" << "\n";
2393
2394 std::string args;
2395 if (HasIOConstructor(decl, args, ctorTypes, interp)) {
2396 // write the constructor wrapper only for concrete classes
2397 finalString << " // Wrappers around operator new" << "\n";
2398 finalString << " static void *new_" << mappedname.c_str() << "(void *p) {" << "\n" << " return p ? ";
2399 if (HasCustomOperatorNewPlacement(*decl, interp)) {
2400 finalString << "new(p) ";
2401 finalString << classname.c_str();
2402 finalString << args;
2403 finalString << " : ";
2404 } else {
2405 finalString << "::new((::ROOT::Internal::TOperatorNewHelper*)p) ";
2406 finalString << classname.c_str();
2407 finalString << args;
2408 finalString << " : ";
2409 }
2410 finalString << "new " << classname.c_str() << args << ";" << "\n";
2411 finalString << " }" << "\n";
2412
2413 if (args.size()==0 && NeedDestructor(decl, interp)) {
2414 // Can not can newArray if the destructor is not public.
2415 finalString << " static void *newArray_";
2416 finalString << mappedname.c_str();
2417 finalString << "(Long_t nElements, void *p) {";
2418 finalString << "\n";
2419 finalString << " return p ? ";
2420 if (HasCustomOperatorNewArrayPlacement(*decl, interp)) {
2421 finalString << "new(p) ";
2422 finalString << classname.c_str();
2423 finalString << "[nElements] : ";
2424 } else {
2425 finalString << "::new((::ROOT::Internal::TOperatorNewHelper*)p) ";
2426 finalString << classname.c_str();
2427 finalString << "[nElements] : ";
2428 }
2429 finalString << "new ";
2430 finalString << classname.c_str();
2431 finalString << "[nElements];";
2432 finalString << "\n";
2433 finalString << " }";
2434 finalString << "\n";
2435 }
2436 }
2437
2438 if (NeedDestructor(decl, interp)) {
2439 finalString << " // Wrapper around operator delete" << "\n" << " static void delete_" << mappedname.c_str() << "(void *p) {" << "\n" << " delete (static_cast<" << classname.c_str() << "*>(p));" << "\n" << " }" << "\n" << " static void deleteArray_" << mappedname.c_str() << "(void *p) {" << "\n" << " delete [] (static_cast<" << classname.c_str() << "*>(p));" << "\n" << " }" << "\n" << " static void destruct_" << mappedname.c_str() << "(void *p) {" << "\n" << " typedef " << classname.c_str() << " current_t;" << "\n" << " (static_cast<current_t*>(p))->~current_t();" << "\n" << " }" << "\n";
2440 }
2441
2442 if (HasDirectoryAutoAdd(decl, interp)) {
2443 finalString << " // Wrapper around the directory auto add." << "\n" << " static void directoryAutoAdd_" << mappedname.c_str() << "(void *p, TDirectory *dir) {" << "\n" << " ((" << classname.c_str() << "*)p)->DirectoryAutoAdd(dir);" << "\n" << " }" << "\n";
2444 }
2445
2446 if (HasCustomStreamerMemberFunction(cl, decl, interp, normCtxt)) {
2447 finalString << " // Wrapper around a custom streamer member function." << "\n" << " static void streamer_" << mappedname.c_str() << "(TBuffer &buf, void *obj) {" << "\n" << " ((" << classname.c_str() << "*)obj)->" << classname.c_str() << "::Streamer(buf);" << "\n" << " }" << "\n";
2448 }
2449
2450 if (HasCustomConvStreamerMemberFunction(cl, decl, interp, normCtxt)) {
2451 finalString << " // Wrapper around a custom streamer member function." << "\n" << " static void conv_streamer_" << mappedname.c_str() << "(TBuffer &buf, void *obj, const TClass *onfile_class) {" << "\n" << " ((" << classname.c_str() << "*)obj)->" << classname.c_str() << "::Streamer(buf,onfile_class);" << "\n" << " }" << "\n";
2452 }
2453
2454 if (HasNewMerge(decl, interp)) {
2455 finalString << " // Wrapper around the merge function." << "\n" << " static Long64_t merge_" << mappedname.c_str() << "(void *obj,TCollection *coll,TFileMergeInfo *info) {" << "\n" << " return ((" << classname.c_str() << "*)obj)->Merge(coll,info);" << "\n" << " }" << "\n";
2456 } else if (HasOldMerge(decl, interp)) {
2457 finalString << " // Wrapper around the merge function." << "\n" << " static Long64_t merge_" << mappedname.c_str() << "(void *obj,TCollection *coll,TFileMergeInfo *) {" << "\n" << " return ((" << classname.c_str() << "*)obj)->Merge(coll);" << "\n" << " }" << "\n";
2458 }
2459
2460 if (HasResetAfterMerge(decl, interp)) {
2461 finalString << " // Wrapper around the Reset function." << "\n" << " static void reset_" << mappedname.c_str() << "(void *obj,TFileMergeInfo *info) {" << "\n" << " ((" << classname.c_str() << "*)obj)->ResetAfterMerge(info);" << "\n" << " }" << "\n";
2462 }
2463 finalString << "} // end of namespace ROOT for class " << classname.c_str() << "\n" << "\n";
2464}
2465
2466////////////////////////////////////////////////////////////////////////////////
2467/// Write interface function for STL members
2468
2470 const cling::Interpreter &interp,
2471 const TNormalizedCtxt &normCtxt)
2472{
2473 std::string a;
2474 std::string clName;
2476 int version = ROOT::TMetaUtils::GetClassVersion(cl.GetRecordDecl(),interp);
2477 if (version == 0) return;
2478 if (version < 0 && !(cl.RequestStreamerInfo()) ) return;
2479
2480
2481 const clang::CXXRecordDecl *clxx = llvm::dyn_cast<clang::CXXRecordDecl>(cl.GetRecordDecl());
2482 if (clxx == 0) return;
2483
2484 // We also need to look at the base classes.
2485 for(clang::CXXRecordDecl::base_class_const_iterator iter = clxx->bases_begin(), end = clxx->bases_end();
2486 iter != end;
2487 ++iter)
2488 {
2489 int k = ROOT::TMetaUtils::IsSTLContainer(*iter);
2490 if (k!=0) {
2491 Internal::RStl::Instance().GenerateTClassFor( iter->getType(), interp, normCtxt);
2492 }
2493 }
2494
2495 // Loop over the non static data member.
2496 for(clang::RecordDecl::field_iterator field_iter = clxx->field_begin(), end = clxx->field_end();
2497 field_iter != end;
2498 ++field_iter)
2499 {
2500 std::string mTypename;
2501 ROOT::TMetaUtils::GetQualifiedName(mTypename, field_iter->getType(), *clxx);
2502
2503 //member is a string
2504 {
2505 const char*shortTypeName = ROOT::TMetaUtils::ShortTypeName(mTypename.c_str());
2506 if (!strcmp(shortTypeName, "string")) {
2507 continue;
2508 }
2509 }
2510
2511 if (!ROOT::TMetaUtils::IsStreamableObject(**field_iter, interp)) continue;
2512
2513 int k = ROOT::TMetaUtils::IsSTLContainer( **field_iter );
2514 if (k!=0) {
2515 // fprintf(stderr,"Add %s which is also",m.Type()->Name());
2516 // fprintf(stderr," %s\n",R__TrueName(**field_iter) );
2517 clang::QualType utype(ROOT::TMetaUtils::GetUnderlyingType(field_iter->getType()),0);
2518 Internal::RStl::Instance().GenerateTClassFor(utype, interp, normCtxt);
2519 }
2520 }
2521}
2522
2523////////////////////////////////////////////////////////////////////////////////
2524/// TrueName strips the typedefs and array dimensions.
2525
2526std::string ROOT::TMetaUtils::TrueName(const clang::FieldDecl &m)
2527{
2528 const clang::Type *rawtype = m.getType()->getCanonicalTypeInternal().getTypePtr();
2529 if (rawtype->isArrayType()) {
2530 rawtype = rawtype->getBaseElementTypeUnsafe ();
2531 }
2532
2533 std::string result;
2534 ROOT::TMetaUtils::GetQualifiedName(result, clang::QualType(rawtype,0), m);
2535 return result;
2536}
2537
2538////////////////////////////////////////////////////////////////////////////////
2539/// Return the version number of the class or -1
2540/// if the function Class_Version does not exist.
2541
2542int ROOT::TMetaUtils::GetClassVersion(const clang::RecordDecl *cl, const cling::Interpreter& interp)
2543{
2544 const clang::CXXRecordDecl* CRD = llvm::dyn_cast<clang::CXXRecordDecl>(cl);
2545 if (!CRD) {
2546 // Must be an enum or namespace.
2547 // FIXME: Make it work for a namespace!
2548 return -1;
2549 }
2550 const clang::FunctionDecl* funcCV = ROOT::TMetaUtils::ClassInfo__HasMethod(CRD,"Class_Version",interp);
2551
2552 // if we have no Class_Info() return -1.
2553 if (!funcCV) return -1;
2554
2555 // if we have many Class_Info() (?!) return 1.
2556 if (funcCV == (clang::FunctionDecl*)-1) return 1;
2557
2558 return GetTrivialIntegralReturnValue(funcCV, interp).second;
2559}
2560
2561////////////////////////////////////////////////////////////////////////////////
2562/// If the function contains 'just': return SomeValue;
2563/// this routine will extract this value and return it.
2564/// The first element is set to true we have the body of the function and it
2565/// is indeed a trivial function with just a return of a value.
2566/// The second element contains the value (or -1 is case of failure)
2567
2568std::pair<bool, int>
2569ROOT::TMetaUtils::GetTrivialIntegralReturnValue(const clang::FunctionDecl *funcCV, const cling::Interpreter &interp)
2570{
2571 using res_t = std::pair<bool, int>;
2572
2573 const clang::CompoundStmt* FuncBody
2574 = llvm::dyn_cast_or_null<clang::CompoundStmt>(funcCV->getBody());
2575 if (!FuncBody)
2576 return res_t{false, -1};
2577 if (FuncBody->size() != 1) {
2578 // This is a non-ClassDef(), complex function - it might depend on state
2579 // and thus we'll need the runtime and cannot determine the result
2580 // statically.
2581 return res_t{false, -1};
2582 }
2583 const clang::ReturnStmt* RetStmt
2584 = llvm::dyn_cast<clang::ReturnStmt>(FuncBody->body_back());
2585 if (!RetStmt)
2586 return res_t{false, -1};
2587 const clang::Expr* RetExpr = RetStmt->getRetValue();
2588 // ClassDef controls the content of Class_Version() but not the return
2589 // expression which is CPP expanded from what the user provided as second
2590 // ClassDef argument. It's usually just be an integer literal but it could
2591 // also be an enum or a variable template for all we know.
2592 // Go through ICE to be more general.
2593 llvm::APSInt RetRes;
2594 if (!RetExpr->isIntegerConstantExpr(RetRes, funcCV->getASTContext()))
2595 return res_t{false, -1};
2596 if (RetRes.isSigned()) {
2597 return res_t{true, (Version_t)RetRes.getSExtValue()};
2598 }
2599 // else
2600 return res_t{true, (Version_t)RetRes.getZExtValue()};
2601}
2602
2603////////////////////////////////////////////////////////////////////////////////
2604/// Is this an STL container.
2605
2607{
2608 return TMetaUtils::IsSTLCont(*annotated.GetRecordDecl());
2609}
2610
2611////////////////////////////////////////////////////////////////////////////////
2612/// Is this an STL container?
2613
2615{
2616 clang::QualType type = m.getType();
2617 clang::RecordDecl *decl = ROOT::TMetaUtils::GetUnderlyingRecordDecl(type);
2618
2619 if (decl) return TMetaUtils::IsSTLCont(*decl);
2620 else return ROOT::kNotSTL;
2621}
2622
2623////////////////////////////////////////////////////////////////////////////////
2624/// Is this an STL container?
2625
2626int ROOT::TMetaUtils::IsSTLContainer(const clang::CXXBaseSpecifier &base)
2627{
2628 clang::QualType type = base.getType();
2629 clang::RecordDecl *decl = ROOT::TMetaUtils::GetUnderlyingRecordDecl(type);
2630
2631 if (decl) return TMetaUtils::IsSTLCont(*decl);
2632 else return ROOT::kNotSTL;
2633}
2634
2635////////////////////////////////////////////////////////////////////////////////
2636/// Calls the given lambda on every header in the given module.
2637/// includeDirectlyUsedModules designates if the foreach should also loop over
2638/// the headers in all modules that are directly used via a `use` declaration
2639/// in the modulemap.
2640void ROOT::TMetaUtils::foreachHeaderInModule(const clang::Module &module,
2641 const std::function<void(const clang::Module::Header &)> &closure,
2642 bool includeDirectlyUsedModules)
2643{
2644 // Iterates over all headers in a module and calls the closure on each.
2645
2646 // FIXME: We currently have to hardcode '4' to do this. Maybe we
2647 // will have a nicer way to do this in the future.
2648 // NOTE: This is on purpose '4', not '5' which is the size of the
2649 // vector. The last element is the list of excluded headers which we
2650 // obviously don't want to check here.
2651 const std::size_t publicHeaderIndex = 4;
2652
2653 // Integrity check in case this array changes its size at some point.
2654 const std::size_t maxArrayLength = ((sizeof module.Headers) / (sizeof *module.Headers));
2655 static_assert(publicHeaderIndex + 1 == maxArrayLength,
2656 "'Headers' has changed it's size, we need to update publicHeaderIndex");
2657
2658 // Make a list of modules and submodules that we can check for headers.
2659 // We use a SetVector to prevent an infinite loop in unlikely case the
2660 // modules somehow are messed up and don't form a tree...
2661 llvm::SetVector<const clang::Module *> modules;
2662 modules.insert(&module);
2663 for (size_t i = 0; i < modules.size(); ++i) {
2664 const clang::Module *M = modules[i];
2665 for (const clang::Module *subModule : M->submodules())
2666 modules.insert(subModule);
2667 }
2668
2669 for (const clang::Module *m : modules) {
2670 if (includeDirectlyUsedModules) {
2671 for (clang::Module *used : m->DirectUses) {
2672 foreachHeaderInModule(*used, closure, true);
2673 }
2674 }
2675
2676 for (std::size_t i = 0; i < publicHeaderIndex; i++) {
2677 auto &headerList = m->Headers[i];
2678 for (const clang::Module::Header &moduleHeader : headerList) {
2679 closure(moduleHeader);
2680 }
2681 }
2682 }
2683}
2684
2685////////////////////////////////////////////////////////////////////////////////
2686/// Return the absolute type of typeDesc.
2687/// E.g.: typeDesc = "class TNamed**", returns "TNamed".
2688/// we remove * and const keywords. (we do not want to remove & ).
2689/// You need to use the result immediately before it is being overwritten.
2690
2691const char *ROOT::TMetaUtils::ShortTypeName(const char *typeDesc)
2692{
2693 static char t[4096];
2694 static const char* constwd = "const ";
2695 static const char* constwdend = "const";
2696
2697 const char *s;
2698 char *p=t;
2699 int lev=0;
2700 for (s=typeDesc;*s;s++) {
2701 if (*s=='<') lev++;
2702 if (*s=='>') lev--;
2703 if (lev==0 && *s=='*') continue;
2704 if (lev==0 && (strncmp(constwd,s,strlen(constwd))==0
2705 ||strcmp(constwdend,s)==0 ) ) {
2706 s+=strlen(constwd)-1; // -1 because the loop adds 1
2707 continue;
2708 }
2709 if (lev==0 && *s==' ' && *(s+1)!='*') { p = t; continue;}
2710 if (p - t > (long)sizeof(t)) {
2711 printf("ERROR (rootcling): type name too long for StortTypeName: %s\n",
2712 typeDesc);
2713 p[0] = 0;
2714 return t;
2715 }
2716 *p++ = *s;
2717 }
2718 p[0]=0;
2719
2720 return t;
2721}
2722
2723bool ROOT::TMetaUtils::IsStreamableObject(const clang::FieldDecl &m,
2724 const cling::Interpreter& interp)
2725{
2727
2728 // Transient
2729 if (!comment.empty() && comment[0] == '!')
2730 return false;
2731
2732 clang::QualType type = m.getType();
2733
2734 if (type->isReferenceType()) {
2735 // Reference can not be streamed.
2736 return false;
2737 }
2738
2739 std::string mTypeName = type.getAsString(m.getASTContext().getPrintingPolicy());
2740 if (!strcmp(mTypeName.c_str(), "string") || !strcmp(mTypeName.c_str(), "string*")) {
2741 return true;
2742 }
2743 if (!strcmp(mTypeName.c_str(), "std::string") || !strcmp(mTypeName.c_str(), "std::string*")) {
2744 return true;
2745 }
2746
2748 return true;
2749 }
2750
2751 const clang::Type *rawtype = type.getTypePtr()->getBaseElementTypeUnsafe ();
2752
2753 if (rawtype->isPointerType()) {
2754 //Get to the 'raw' type.
2755 clang::QualType pointee;
2756 while ( (pointee = rawtype->getPointeeType()) , pointee.getTypePtrOrNull() && pointee.getTypePtr() != rawtype)
2757 {
2758 rawtype = pointee.getTypePtr();
2759 }
2760 }
2761
2762 if (rawtype->isFundamentalType() || rawtype->isEnumeralType()) {
2763 // not an ojbect.
2764 return false;
2765 }
2766
2767 const clang::CXXRecordDecl *cxxdecl = rawtype->getAsCXXRecordDecl();
2768 if (cxxdecl && ROOT::TMetaUtils::ClassInfo__HasMethod(cxxdecl,"Streamer", interp)) {
2769 if (!(ROOT::TMetaUtils::ClassInfo__HasMethod(cxxdecl,"Class_Version", interp))) return true;
2770 int version = ROOT::TMetaUtils::GetClassVersion(cxxdecl,interp);
2771 if (version > 0) return true;
2772 }
2773 return false;
2774}
2775
2776////////////////////////////////////////////////////////////////////////////////
2777/// Return the absolute type of typeDesc.
2778/// E.g.: typeDesc = "class TNamed**", returns "TNamed".
2779/// we remove * and const keywords. (we do not want to remove & ).
2780/// You need to use the result immediately before it is being overwritten.
2781
2782std::string ROOT::TMetaUtils::ShortTypeName(const clang::FieldDecl &m)
2783{
2784 const clang::Type *rawtype = m.getType().getTypePtr();
2785
2786 //Get to the 'raw' type.
2787 clang::QualType pointee;
2788 while ( rawtype->isPointerType() && ((pointee = rawtype->getPointeeType()) , pointee.getTypePtrOrNull()) && pointee.getTypePtr() != rawtype)
2789 {
2790 rawtype = pointee.getTypePtr();
2791 }
2792
2793 std::string result;
2794 ROOT::TMetaUtils::GetQualifiedName(result, clang::QualType(rawtype,0), m);
2795 return result;
2796}
2797
2798////////////////////////////////////////////////////////////////////////////////
2799
2800clang::RecordDecl *ROOT::TMetaUtils::GetUnderlyingRecordDecl(clang::QualType type)
2801{
2803
2804 if (rawtype->isFundamentalType() || rawtype->isEnumeralType()) {
2805 // not an object.
2806 return nullptr;
2807 }
2808 return rawtype->getAsCXXRecordDecl();
2809}
2810
2811////////////////////////////////////////////////////////////////////////////////
2812/// Generate the code of the class
2813/// If the requestor is genreflex, request the new streamer format
2814
2816 const AnnotatedRecordDecl &cl,
2817 const cling::Interpreter &interp,
2818 const TNormalizedCtxt &normCtxt,
2819 std::ostream& dictStream,
2820 const RConstructorTypes& ctorTypes,
2821 bool isGenreflex=false)
2822{
2823 const clang::CXXRecordDecl* decl = llvm::dyn_cast<clang::CXXRecordDecl>(cl.GetRecordDecl());
2824
2825 if (!decl || !decl->isCompleteDefinition()) {
2826 return;
2827 }
2828
2829 std::string fullname;
2831 if (TClassEdit::IsSTLCont(fullname) ) {
2832 Internal::RStl::Instance().GenerateTClassFor(cl.GetNormalizedName(), llvm::dyn_cast<clang::CXXRecordDecl>(cl.GetRecordDecl()), interp, normCtxt);
2833 return;
2834 }
2835
2836 if (ROOT::TMetaUtils::ClassInfo__HasMethod(cl,"Streamer",interp)) {
2837 // The !genreflex is there to prevent genreflex to select collections which are data members
2838 // This is to maintain the behaviour of ROOT5 and ROOT6 up to 6.07 included.
2839 if (cl.RootFlag() && !isGenreflex) ROOT::TMetaUtils::WritePointersSTL(cl, interp, normCtxt); // In particular this detect if the class has a version number.
2840 if (!(cl.RequestNoStreamer())) {
2841 (*WriteStreamerFunc)(cl, interp, normCtxt, dictStream, isGenreflex || cl.RequestStreamerInfo());
2842 } else
2843 ROOT::TMetaUtils::Info(0, "Class %s: Do not generate Streamer() [*** custom streamer ***]\n",fullname.c_str());
2844 } else {
2845 ROOT::TMetaUtils::Info(0, "Class %s: Streamer() not declared\n", fullname.c_str());
2846
2847 // See comment above about the !isGenreflex
2848 if (cl.RequestStreamerInfo() && !isGenreflex) ROOT::TMetaUtils::WritePointersSTL(cl, interp, normCtxt);
2849 }
2850 ROOT::TMetaUtils::WriteAuxFunctions(dictStream, cl, decl, interp, ctorTypes, normCtxt);
2851}
2852
2853////////////////////////////////////////////////////////////////////////////////
2854/// Add any unspecified template parameters to the class template instance,
2855/// mentioned anywhere in the type.
2856///
2857/// Note: this does not strip any typedef but could be merged with cling::utils::Transform::GetPartiallyDesugaredType
2858/// if we can safely replace TClassEdit::IsStd with a test on the declaring scope
2859/// and if we can resolve the fact that the added parameter do not take into account possible use/dependences on Double32_t
2860/// and if we decide that adding the default is the right long term solution or not.
2861/// Whether it is or not depend on the I/O on whether the default template argument might change or not
2862/// and whether they (should) affect the on disk layout (for STL containers, we do know they do not).
2863
2864clang::QualType ROOT::TMetaUtils::AddDefaultParameters(clang::QualType instanceType,
2865 const cling::Interpreter &interpreter,
2866 const ROOT::TMetaUtils::TNormalizedCtxt &normCtxt)
2867{
2868 const clang::ASTContext& Ctx = interpreter.getCI()->getASTContext();
2869
2870 clang::QualType originalType = instanceType;
2871
2872 // In case of name* we need to strip the pointer first, add the default and attach
2873 // the pointer once again.
2874 if (llvm::isa<clang::PointerType>(instanceType.getTypePtr())) {
2875 // Get the qualifiers.
2876 clang::Qualifiers quals = instanceType.getQualifiers();
2877 clang::QualType newPointee = AddDefaultParameters(instanceType->getPointeeType(), interpreter, normCtxt);
2878 if (newPointee != instanceType->getPointeeType()) {
2879 instanceType = Ctx.getPointerType(newPointee);
2880 // Add back the qualifiers.
2881 instanceType = Ctx.getQualifiedType(instanceType, quals);
2882 }
2883 return instanceType;
2884 }
2885
2886 // In case of Int_t& we need to strip the pointer first, desugar and attach
2887 // the pointer once again.
2888 if (llvm::isa<clang::ReferenceType>(instanceType.getTypePtr())) {
2889 // Get the qualifiers.
2890 bool isLValueRefTy = llvm::isa<clang::LValueReferenceType>(instanceType.getTypePtr());
2891 clang::Qualifiers quals = instanceType.getQualifiers();
2892 clang::QualType newPointee = AddDefaultParameters(instanceType->getPointeeType(), interpreter, normCtxt);
2893
2894 if (newPointee != instanceType->getPointeeType()) {
2895 // Add the r- or l- value reference type back to the desugared one
2896 if (isLValueRefTy)
2897 instanceType = Ctx.getLValueReferenceType(newPointee);
2898 else
2899 instanceType = Ctx.getRValueReferenceType(newPointee);
2900 // Add back the qualifiers.
2901 instanceType = Ctx.getQualifiedType(instanceType, quals);
2902 }
2903 return instanceType;
2904 }
2905
2906 // Treat the Scope.
2907 bool prefix_changed = false;
2908 clang::NestedNameSpecifier* prefix = 0;
2909 clang::Qualifiers prefix_qualifiers = instanceType.getLocalQualifiers();
2910 const clang::ElaboratedType* etype
2911 = llvm::dyn_cast<clang::ElaboratedType>(instanceType.getTypePtr());
2912 if (etype) {
2913 // We have to also handle the prefix.
2914 prefix = AddDefaultParametersNNS(Ctx, etype->getQualifier(), interpreter, normCtxt);
2915 prefix_changed = prefix != etype->getQualifier();
2916 instanceType = clang::QualType(etype->getNamedType().getTypePtr(),0);
2917 }
2918
2919 // In case of template specializations iterate over the arguments and
2920 // add unspecified default parameter.
2921
2922 const clang::TemplateSpecializationType* TST
2923 = llvm::dyn_cast<const clang::TemplateSpecializationType>(instanceType.getTypePtr());
2924
2925 const clang::ClassTemplateSpecializationDecl* TSTdecl
2926 = llvm::dyn_cast_or_null<const clang::ClassTemplateSpecializationDecl>(instanceType.getTypePtr()->getAsCXXRecordDecl());
2927
2928 // Don't add the default paramater onto std classes.
2929 // We really need this for __shared_ptr which add a enum constant value which
2930 // is spelled in its 'numeral' form and thus the resulting type name is
2931 // incorrect. We also can used this for any of the STL collections where we
2932 // know we don't want the default argument. For the other members of the
2933 // std namespace this is dubious (because TMetaUtils::GetNormalizedName would
2934 // not drop those defaults). [I.e. the real test ought to be is std and
2935 // name is __shared_ptr or vector or list or set or etc.]
2936 bool isStdDropDefault = TSTdecl && IsStdDropDefaultClass(*TSTdecl);
2937
2938 bool mightHaveChanged = false;
2939 if (TST && TSTdecl) {
2940
2941 clang::Sema& S = interpreter.getCI()->getSema();
2942 clang::TemplateDecl *Template = TSTdecl->getSpecializedTemplate()->getMostRecentDecl();
2943 clang::TemplateParameterList *Params = Template->getTemplateParameters();
2944 clang::TemplateParameterList::iterator Param = Params->begin(); // , ParamEnd = Params->end();
2945 //llvm::SmallVectorImpl<TemplateArgument> Converted; // Need to contains the other arguments.
2946 // Converted seems to be the same as our 'desArgs'
2947
2948 unsigned int dropDefault = normCtxt.GetConfig().DropDefaultArg(*Template);
2949
2950 llvm::SmallVector<clang::TemplateArgument, 4> desArgs;
2951 unsigned int Idecl = 0, Edecl = TSTdecl->getTemplateArgs().size();
2952 unsigned int maxAddArg = TSTdecl->getTemplateArgs().size() - dropDefault;
2953 for(clang::TemplateSpecializationType::iterator
2954 I = TST->begin(), E = TST->end();
2955 Idecl != Edecl;
2956 I!=E ? ++I : 0, ++Idecl, ++Param) {
2957
2958 if (I != E) {
2959
2960 if (I->getKind() == clang::TemplateArgument::Template) {
2961 clang::TemplateName templateName = I->getAsTemplate();
2962 clang::TemplateDecl* templateDecl = templateName.getAsTemplateDecl();
2963 if (templateDecl) {
2964 clang::DeclContext* declCtxt = templateDecl->getDeclContext();
2965
2966 if (declCtxt && !templateName.getAsQualifiedTemplateName()){
2967 clang::NamespaceDecl* ns = clang::dyn_cast<clang::NamespaceDecl>(declCtxt);
2968 clang::NestedNameSpecifier* nns;
2969 if (ns) {
2970 nns = cling::utils::TypeName::CreateNestedNameSpecifier(Ctx, ns);
2971 } else if (clang::TagDecl* TD = llvm::dyn_cast<clang::TagDecl>(declCtxt)) {
2972 nns = cling::utils::TypeName::CreateNestedNameSpecifier(Ctx,TD, false /*FullyQualified*/);
2973 } else {
2974 // TU scope
2975 desArgs.push_back(*I);
2976 continue;
2977 }
2978 clang::TemplateName templateNameWithNSS ( Ctx.getQualifiedTemplateName(nns, false, templateDecl) );
2979 desArgs.push_back(clang::TemplateArgument(templateNameWithNSS));
2980 mightHaveChanged = true;
2981 continue;
2982 }
2983 }
2984 }
2985
2986 if (I->getKind() != clang::TemplateArgument::Type) {
2987 desArgs.push_back(*I);
2988 continue;
2989 }
2990
2991 clang::QualType SubTy = I->getAsType();
2992
2993 // Check if the type needs more desugaring and recurse.
2994 // (Originally this was limited to elaborated and templated type,
2995 // but we also need to do it for pointer and reference type
2996 // and who knows what, so do it always)
2997 clang::QualType newSubTy = AddDefaultParameters(SubTy,
2998 interpreter,
2999 normCtxt);
3000 if (SubTy != newSubTy) {
3001 mightHaveChanged = true;
3002 desArgs.push_back(clang::TemplateArgument(newSubTy));
3003 } else {
3004 desArgs.push_back(*I);
3005 }
3006 // Converted.push_back(TemplateArgument(ArgTypeForTemplate));
3007 } else if (!isStdDropDefault && Idecl < maxAddArg) {
3008
3009 mightHaveChanged = true;
3010
3011 const clang::TemplateArgument& templateArg
3012 = TSTdecl->getTemplateArgs().get(Idecl);
3013 if (templateArg.getKind() != clang::TemplateArgument::Type) {
3014 desArgs.push_back(templateArg);
3015 continue;
3016 }
3017 clang::QualType SubTy = templateArg.getAsType();
3018
3019 clang::SourceLocation TemplateLoc = Template->getSourceRange ().getBegin(); //NOTE: not sure that this is the 'right' location.
3020 clang::SourceLocation RAngleLoc = TSTdecl->getSourceRange().getBegin(); // NOTE: most likely wrong, I think this is expecting the location of right angle
3021
3022 clang::TemplateTypeParmDecl *TTP = llvm::dyn_cast<clang::TemplateTypeParmDecl>(*Param);
3023 {
3024 // We may induce template instantiation
3025 cling::Interpreter::PushTransactionRAII clingRAII(const_cast<cling::Interpreter*>(&interpreter));
3026 clang::sema::HackForDefaultTemplateArg raii;
3027 bool HasDefaultArgs;
3028 clang::TemplateArgumentLoc ArgType = S.SubstDefaultTemplateArgumentIfAvailable(
3029 Template,
3030 TemplateLoc,
3031 RAngleLoc,
3032 TTP,
3033 desArgs,
3034 HasDefaultArgs);
3035 // The substition can fail, in which case there would have been compilation
3036 // error printed on the screen.
3037 if (ArgType.getArgument().isNull()
3038 || ArgType.getArgument().getKind() != clang::TemplateArgument::Type) {
3039 ROOT::TMetaUtils::Error("ROOT::TMetaUtils::AddDefaultParameters",
3040 "Template parameter substitution failed for %s around %s\n",
3041 instanceType.getAsString().c_str(), SubTy.getAsString().c_str());
3042 break;
3043 }
3044 clang::QualType BetterSubTy = ArgType.getArgument().getAsType();
3045 SubTy = cling::utils::Transform::GetPartiallyDesugaredType(Ctx,BetterSubTy,normCtxt.GetConfig(),/*fullyQualified=*/ true);
3046 }
3047 SubTy = AddDefaultParameters(SubTy,interpreter,normCtxt);
3048 desArgs.push_back(clang::TemplateArgument(SubTy));
3049 } else {
3050 // We are past the end of the list of specified arguements and we
3051 // do not want to add the default, no need to continue.
3052 break;
3053 }
3054 }
3055
3056 // If we added default parameter, allocate new type in the AST.
3057 if (mightHaveChanged) {
3058 instanceType = Ctx.getTemplateSpecializationType(TST->getTemplateName(),
3059 desArgs,
3060 TST->getCanonicalTypeInternal());
3061 }
3062 }
3063
3064 if (!prefix_changed && !mightHaveChanged) return originalType;
3065 if (prefix) {
3066 instanceType = Ctx.getElaboratedType(clang::ETK_None,prefix,instanceType);
3067 instanceType = Ctx.getQualifiedType(instanceType,prefix_qualifiers);
3068 }
3069 return instanceType;
3070}
3071
3072////////////////////////////////////////////////////////////////////////////////
3073/// ValidArrayIndex return a static string (so use it or copy it immediatly, do not
3074/// call GrabIndex twice in the same expression) containing the size of the
3075/// array data member.
3076/// In case of error, or if the size is not specified, GrabIndex returns 0.
3077/// If errnum is not null, *errnum updated with the error number:
3078/// Cint::G__DataMemberInfo::G__VALID : valid array index
3079/// Cint::G__DataMemberInfo::G__NOT_INT : array index is not an int
3080/// Cint::G__DataMemberInfo::G__NOT_DEF : index not defined before array
3081/// (this IS an error for streaming to disk)
3082/// Cint::G__DataMemberInfo::G__IS_PRIVATE: index exist in a parent class but is private
3083/// Cint::G__DataMemberInfo::G__UNKNOWN : index is not known
3084/// If errstr is not null, *errstr is updated with the address of a static
3085/// string containing the part of the index with is invalid.
3086
3087llvm::StringRef ROOT::TMetaUtils::DataMemberInfo__ValidArrayIndex(const cling::Interpreter &interp, const clang::DeclaratorDecl &m, int *errnum, llvm::StringRef *errstr)
3088{
3089 llvm::StringRef title;
3090
3091 // Try to get the comment either from the annotation or the header file if present
3092 if (clang::AnnotateAttr *A = m.getAttr<clang::AnnotateAttr>())
3093 title = A->getAnnotation();
3094 else
3095 // Try to get the comment from the header file if present
3097
3098 // Let's see if the user provided us with some information
3099 // with the format: //[dimension] this is the dim of the array
3100 // dimension can be an arithmetical expression containing, literal integer,
3101 // the operator *,+ and - and data member of integral type. In addition the
3102 // data members used for the size of the array need to be defined prior to
3103 // the array.
3104
3105 if (errnum) *errnum = VALID;
3106
3107 if (title.size() == 0 || (title[0] != '[')) return llvm::StringRef();
3108 size_t rightbracket = title.find(']');
3109 if (rightbracket == llvm::StringRef::npos) return llvm::StringRef();
3110
3111 std::string working;
3112 llvm::StringRef indexvar(title.data()+1,rightbracket-1);
3113
3114 // now we should have indexvar=dimension
3115 // Let's see if this is legal.
3116 // which means a combination of data member and digit separated by '*','+','-'
3117 // First we remove white spaces.
3118 unsigned int i;
3119 size_t indexvarlen = indexvar.size();
3120 for ( i=0; i<indexvarlen; i++) {
3121 if (!isspace(indexvar[i])) {
3122 working += indexvar[i];
3123 }
3124 };
3125
3126 // Now we go through all indentifiers
3127 const char *tokenlist = "*+-";
3128 char *current = const_cast<char*>(working.c_str());
3129 current = strtok(current,tokenlist); // this method does not need to be reentrant
3130
3131 while (current!=0) {
3132 // Check the token
3133 if (isdigit(current[0])) {
3134 for(i=0;i<strlen(current);i++) {
3135 if (!isdigit(current[i])) {
3136 // Error we only access integer.
3137 //NOTE: *** Need to print an error;
3138 //fprintf(stderr,"*** Datamember %s::%s: size of array (%s) is not an interger\n",
3139 // member.MemberOf()->Name(), member.Name(), current);
3140 if (errstr) *errstr = current;
3141 if (errnum) *errnum = NOT_INT;
3142 return llvm::StringRef();
3143 }
3144 }
3145 } else { // current token is not a digit
3146 // first let's see if it is a data member:
3147 const clang::CXXRecordDecl *parent_clxx = llvm::dyn_cast<clang::CXXRecordDecl>(m.getDeclContext());
3148 const clang::FieldDecl *index1 = nullptr;
3149 if (parent_clxx)
3150 index1 = GetDataMemberFromAll(*parent_clxx, current );
3151 if ( index1 ) {
3152 if ( IsFieldDeclInt(index1) ) {
3153 // Let's see if it has already been written down in the
3154 // Streamer.
3155 // Let's see if we already wrote it down in the
3156 // streamer.
3157 for(clang::RecordDecl::field_iterator field_iter = parent_clxx->field_begin(), end = parent_clxx->field_end();
3158 field_iter != end;
3159 ++field_iter)
3160 {
3161 if ( field_iter->getNameAsString() == m.getNameAsString() ) {
3162 // we reached the current data member before
3163 // reaching the index so we have not written it yet!
3164 //NOTE: *** Need to print an error;
3165 //fprintf(stderr,"*** Datamember %s::%s: size of array (%s) has not been defined before the array \n",
3166 // member.MemberOf()->Name(), member.Name(), current);
3167 if (errstr) *errstr = current;
3168 if (errnum) *errnum = NOT_DEF;
3169 return llvm::StringRef();
3170 }
3171 if ( field_iter->getNameAsString() == index1->getNameAsString() ) {
3172 break;
3173 }
3174 } // end of while (m_local.Next())
3175 } else {
3176 //NOTE: *** Need to print an error;
3177 //fprintf(stderr,"*** Datamember %s::%s: size of array (%s) is not int \n",
3178 // member.MemberOf()->Name(), member.Name(), current);
3179 if (errstr) *errstr = current;
3180 if (errnum) *errnum = NOT_INT;
3181 return llvm::StringRef();
3182 }
3183 } else {
3184 // There is no variable by this name in this class, let see
3185 // the base classes!:
3186 int found = 0;
3187 if (parent_clxx) {
3188 clang::Sema& SemaR = const_cast<cling::Interpreter&>(interp).getSema();
3189 index1 = GetDataMemberFromAllParents(SemaR, *parent_clxx, current);
3190 }
3191 if ( index1 ) {
3192 if ( IsFieldDeclInt(index1) ) {
3193 found = 1;
3194 } else {
3195 // We found a data member but it is the wrong type
3196 //NOTE: *** Need to print an error;
3197 //fprintf(stderr,"*** Datamember %s::%s: size of array (%s) is not int \n",
3198 // member.MemberOf()->Name(), member.Name(), current);
3199 if (errnum) *errnum = NOT_INT;
3200 if (errstr) *errstr = current;
3201 //NOTE: *** Need to print an error;
3202 //fprintf(stderr,"*** Datamember %s::%s: size of array (%s) is not int \n",
3203 // member.MemberOf()->Name(), member.Name(), current);
3204 if (errnum) *errnum = NOT_INT;
3205 if (errstr) *errstr = current;
3206 return llvm::StringRef();
3207 }
3208 if ( found && (index1->getAccess() == clang::AS_private) ) {
3209 //NOTE: *** Need to print an error;
3210 //fprintf(stderr,"*** Datamember %s::%s: size of array (%s) is a private member of %s \n",
3211 if (errstr) *errstr = current;
3212 if (errnum) *errnum = IS_PRIVATE;
3213 return llvm::StringRef();
3214 }
3215 }
3216 if (!found) {
3217 //NOTE: *** Need to print an error;
3218 //fprintf(stderr,"*** Datamember %s::%s: size of array (%s) is not known \n",
3219 // member.MemberOf()->Name(), member.Name(), indexvar);
3220 if (errstr) *errstr = indexvar;
3221 if (errnum) *errnum = UNKNOWN;
3222 return llvm::StringRef();
3223 } // end of if not found
3224 } // end of if is a data member of the class
3225 } // end of if isdigit
3226
3227 current = strtok(0,tokenlist);
3228 } // end of while loop on tokens
3229
3230 return indexvar;
3231
3232}
3233
3234////////////////////////////////////////////////////////////////////////////////
3235/// Return (in the argument 'output') a mangled version of the C++ symbol/type (pass as 'input')
3236/// that can be used in C++ as a variable name.
3237
3238void ROOT::TMetaUtils::GetCppName(std::string &out, const char *in)
3239{
3240 unsigned int i = 0;
3241 char c;
3242 out.clear();
3243 while((c = in[i++])) {
3244 const char *repl = nullptr;
3245 switch(c) {
3246 case '+': repl = "pL"; break;
3247 case '-': repl = "mI"; break;
3248 case '*': repl = "mU"; break;
3249 case '/': repl = "dI"; break;
3250 case '&': repl = "aN"; break;
3251 case '%': repl = "pE"; break;
3252 case '|': repl = "oR"; break;
3253 case '^': repl = "hA"; break;
3254 case '>': repl = "gR"; break;
3255 case '<': repl = "lE"; break;
3256 case '=': repl = "eQ"; break;
3257 case '~': repl = "wA"; break;
3258 case '.': repl = "dO"; break;
3259 case '(': repl = "oP"; break;
3260 case ')': repl = "cP"; break;
3261 case '[': repl = "oB"; break;
3262 case ']': repl = "cB"; break;
3263 case '!': repl = "nO"; break;
3264 case ',': repl = "cO"; break;
3265 case '$': repl = "dA"; break;
3266 case ' ': repl = "sP"; break;
3267 case ':': repl = "cL"; break;
3268 case '"': repl = "dQ"; break;
3269 case '@': repl = "aT"; break;
3270 case '\'': repl = "sQ"; break;
3271 case '\\': repl = "fI"; break;
3272 }
3273 if (repl)
3274 out.append(repl);
3275 else
3276 out.push_back(c);
3277 }
3278
3279 // Remove initial numbers if any
3280 auto firstNonNumber = out.find_first_not_of("0123456789");
3281 if (firstNonNumber != std::string::npos)
3282 out.replace(0,firstNonNumber,"");
3283}
3284
3285static clang::SourceLocation
3286getFinalSpellingLoc(clang::SourceManager& sourceManager,
3287 clang::SourceLocation sourceLoc) {
3288 // Follow macro expansion until we hit a source file.
3289 if (!sourceLoc.isFileID()) {
3290 return sourceManager.getExpansionRange(sourceLoc).getEnd();
3291 }
3292 return sourceLoc;
3293}
3294
3295////////////////////////////////////////////////////////////////////////////////
3296/// Return the header file to be included to declare the Decl.
3297
3298std::string ROOT::TMetaUtils::GetFileName(const clang::Decl& decl,
3299 const cling::Interpreter& interp)
3300{
3301 // It looks like the template specialization decl actually contains _less_ information
3302 // on the location of the code than the decl (in case where there is forward declaration,
3303 // that is what the specialization points to).
3304 //
3305 // const clang::CXXRecordDecl* clxx = llvm::dyn_cast<clang::CXXRecordDecl>(decl);
3306 // if (clxx) {
3307 // switch(clxx->getTemplateSpecializationKind()) {
3308 // case clang::TSK_Undeclared:
3309 // // We want the default behavior
3310 // break;
3311 // case clang::TSK_ExplicitInstantiationDeclaration:
3312 // case clang::TSK_ExplicitInstantiationDefinition:
3313 // case clang::TSK_ImplicitInstantiation: {
3314 // // We want the location of the template declaration:
3315 // const clang::ClassTemplateSpecializationDecl *tmplt_specialization = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl> (clxx);
3316 // if (tmplt_specialization) {
3317 // // return GetFileName(const_cast< clang::ClassTemplateSpecializationDecl *>(tmplt_specialization)->getSpecializedTemplate());
3318 // }
3319 // break;
3320 // }
3321 // case clang::TSK_ExplicitSpecialization:
3322 // // We want the default behavior
3323 // break;
3324 // default:
3325 // break;
3326 // }
3327 // }
3328
3329 using namespace clang;
3330 SourceLocation headerLoc = decl.getLocation();
3331
3332 static const char invalidFilename[] = "";
3333 if (!headerLoc.isValid()) return invalidFilename;
3334
3335 HeaderSearch& HdrSearch = interp.getCI()->getPreprocessor().getHeaderSearchInfo();
3336
3337 SourceManager& sourceManager = decl.getASTContext().getSourceManager();
3338 headerLoc = getFinalSpellingLoc(sourceManager, headerLoc);
3339 FileID headerFID = sourceManager.getFileID(headerLoc);
3340 SourceLocation includeLoc
3341 = getFinalSpellingLoc(sourceManager,
3342 sourceManager.getIncludeLoc(headerFID));
3343
3344 const FileEntry *headerFE = sourceManager.getFileEntryForID(headerFID);
3345 while (includeLoc.isValid() && sourceManager.isInSystemHeader(includeLoc)) {
3346 const DirectoryLookup *foundDir = 0;
3347 // use HeaderSearch on the basename, to make sure it takes a header from
3348 // the include path (e.g. not from /usr/include/bits/)
3349 assert(headerFE && "Couldn't find FileEntry from FID!");
3350 const FileEntry *FEhdr
3351 = HdrSearch.LookupFile(llvm::sys::path::filename(headerFE->getName()),
3352 SourceLocation(),
3353 true /*isAngled*/, 0/*FromDir*/, foundDir,
3354 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>>(),
3355 0/*Searchpath*/, 0/*RelPath*/,
3356 0/*SuggestedModule*/, 0/*RequestingModule*/,
3357 0/*IsMapped*/, nullptr /*IsFrameworkFound*/,
3358 false /*SkipCache*/,
3359 false /*BuildSystemModule*/,
3360 false /*OpenFile*/, true /*CacheFailures*/);
3361 if (FEhdr) break;
3362 headerFID = sourceManager.getFileID(includeLoc);
3363 headerFE = sourceManager.getFileEntryForID(headerFID);
3364 // If we have a system header in a module we can't just trace back the
3365 // original include with the preprocessor. But it should be enough if
3366 // we trace it back to the top-level system header that includes this
3367 // declaration.
3368 if (interp.getCI()->getLangOpts().Modules && !headerFE) {
3369 assert(decl.isFirstDecl() && "Couldn't trace back include from a decl"
3370 " that is not from an AST file");
3371 assert(StringRef(includeLoc.printToString(sourceManager)).startswith("<module-includes>"));
3372 break;
3373 }
3374 includeLoc = getFinalSpellingLoc(sourceManager,
3375 sourceManager.getIncludeLoc(headerFID));
3376 }
3377
3378 if (!headerFE) return invalidFilename;
3379
3380 llvm::SmallString<256> headerFileName(headerFE->getName());
3381 // Remove double ../ from the path so that the search below finds a valid
3382 // longest match and does not result in growing paths.
3383 llvm::sys::path::remove_dots(headerFileName, /*remove_dot_dot=*/true);
3384
3385 // Now headerFID references the last valid system header or the original
3386 // user file.
3387 // Find out how to include it by matching file name to include paths.
3388 // We assume that the file "/A/B/C/D.h" can at some level be included as
3389 // "C/D.h". Be we cannot know whether that happens to be a different file
3390 // with the same name. Thus we first find the longest stem that can be
3391 // reached, say B/C/D.h. Then we find the shortest one, say C/D.h, that
3392 // points to the same file as the long version. If such a short version
3393 // exists it will be returned. If it doesn't the long version is returned.
3394 bool isAbsolute = llvm::sys::path::is_absolute(headerFileName);
3395 const FileEntry* FELong = 0;
3396 // Find the longest available match.
3397 for (llvm::sys::path::const_iterator
3398 IDir = llvm::sys::path::begin(headerFileName),
3399 EDir = llvm::sys::path::end(headerFileName);
3400 !FELong && IDir != EDir; ++IDir) {
3401 if (isAbsolute) {
3402 // skip "/" part
3403 isAbsolute = false;
3404 continue;
3405 }
3406 size_t lenTrailing = headerFileName.size() - (IDir->data() - headerFileName.data());
3407 llvm::StringRef trailingPart(IDir->data(), lenTrailing);
3408 assert(trailingPart.data() + trailingPart.size()
3409 == headerFileName.data() + headerFileName.size()
3410 && "Mismatched partitioning of file name!");
3411 const DirectoryLookup* FoundDir = 0;
3412 FELong = HdrSearch.LookupFile(trailingPart, SourceLocation(),
3413 true /*isAngled*/, 0/*FromDir*/, FoundDir,
3414 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>>(),
3415 0/*Searchpath*/, 0/*RelPath*/,
3416 0/*SuggestedModule*/, 0/*RequestingModule*/,
3417 0/*IsMapped*/, nullptr /*IsFrameworkFound*/);
3418 }
3419
3420 if (!FELong) {
3421 // We did not find any file part in any search path.
3422 return invalidFilename;
3423 }
3424
3425 // Iterates through path *parts* "C"; we need trailing parts "C/D.h"
3426 for (llvm::sys::path::reverse_iterator
3427 IDir = llvm::sys::path::rbegin(headerFileName),
3428 EDir = llvm::sys::path::rend(headerFileName);
3429 IDir != EDir; ++IDir) {
3430 size_t lenTrailing = headerFileName.size() - (IDir->data() - headerFileName.data());
3431 llvm::StringRef trailingPart(IDir->data(), lenTrailing);
3432 assert(trailingPart.data() + trailingPart.size()
3433 == headerFileName.data() + headerFileName.size()
3434 && "Mismatched partitioning of file name!");
3435 const DirectoryLookup* FoundDir = 0;
3436 // Can we find it, and is it the same file as the long version?
3437 // (or are we back to the previously found spelling, which is fine, too)
3438 if (HdrSearch.LookupFile(trailingPart, SourceLocation(),
3439 true /*isAngled*/, 0/*FromDir*/, FoundDir,
3440 ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>>(),
3441 0/*Searchpath*/, 0/*RelPath*/,
3442 0/*SuggestedModule*/, 0/*RequestingModule*/,
3443 0/*IsMapped*/, nullptr /*IsFrameworkFound*/) == FELong) {
3444 return trailingPart;
3445 }
3446 }
3447
3448 return invalidFilename;
3449}
3450
3451////////////////////////////////////////////////////////////////////////////////
3452
3454 const clang::QualType &qtype,
3455 const clang::ASTContext &astContext)
3456{
3457 std::string fqname = cling::utils::TypeName::GetFullyQualifiedName(qtype, astContext);
3458 TClassEdit::TSplitType splitname(fqname.c_str(),
3461}
3462
3463////////////////////////////////////////////////////////////////////////////////
3464
3466 const clang::QualType &qtype,
3467 const cling::Interpreter &interpreter)
3468{
3469 // We need this because GetFullyQualifiedTypeName is triggering deserialization
3470 // This calling the same name function GetFullyQualifiedTypeName, but this should stay here because
3471 // callee doesn't have an interpreter pointer
3472 cling::Interpreter::PushTransactionRAII RAII(const_cast<cling::Interpreter*>(&interpreter));
3473
3474 GetFullyQualifiedTypeName(typenamestr,
3475 qtype,
3476 interpreter.getCI()->getASTContext());
3477}
3478
3479////////////////////////////////////////////////////////////////////////////////
3480/// Get the template specialisation decl and template decl behind the qualtype
3481/// Returns true if successfully found, false otherwise
3482
3483bool ROOT::TMetaUtils::QualType2Template(const clang::QualType& qt,
3484 clang::ClassTemplateDecl*& ctd,
3485 clang::ClassTemplateSpecializationDecl*& ctsd)
3486{
3487 using namespace clang;
3488 const Type* theType = qt.getTypePtr();
3489 if (!theType){
3490 ctd=nullptr;
3491 ctsd=nullptr;
3492 return false;
3493 }
3494
3495 if (theType->isPointerType()) {
3496 return QualType2Template(theType->getPointeeType(), ctd, ctsd);
3497 }
3498
3499 if (const RecordType* rType = llvm::dyn_cast<RecordType>(theType)) {
3500 ctsd = llvm::dyn_cast_or_null<ClassTemplateSpecializationDecl>(rType->getDecl());
3501 if (ctsd) {
3502 ctd = ctsd->getSpecializedTemplate();
3503 return true;
3504 }
3505 }
3506
3507 if (const SubstTemplateTypeParmType* sttpType = llvm::dyn_cast<SubstTemplateTypeParmType>(theType)){
3508 return QualType2Template(sttpType->getReplacementType(), ctd, ctsd);
3509 }
3510
3511
3512 ctsd = llvm::dyn_cast_or_null<ClassTemplateSpecializationDecl>(qt->getAsCXXRecordDecl());
3513 if(ctsd){
3514 ctd = ctsd->getSpecializedTemplate();
3515 return true;
3516 }
3517
3518 ctd=nullptr;
3519 ctsd=nullptr;
3520 return false;
3521}
3522
3523////////////////////////////////////////////////////////////////////////////////
3524/// Extract from a qualtype the class template if this makes sense.
3525/// Retuns the ClassTemplateDecl or nullptr otherwise.
3526
3527clang::ClassTemplateDecl* ROOT::TMetaUtils::QualType2ClassTemplateDecl(const clang::QualType& qt)
3528{
3529 using namespace clang;
3530 ClassTemplateSpecializationDecl* ctsd;
3531 ClassTemplateDecl* ctd;
3532 QualType2Template(qt,ctd,ctsd);
3533 return ctd;
3534}
3535
3536////////////////////////////////////////////////////////////////////////////////
3537/// These manipulations are necessary because a template specialisation type
3538/// does not inherit from a record type (there is an asymmetry between
3539/// the decls and the types in the clang interface).
3540/// We may need therefore to step into the "Decl dimension" to then get back
3541/// to the "type dimension".
3542
3543clang::TemplateName ROOT::TMetaUtils::ExtractTemplateNameFromQualType(const clang::QualType& qt)
3544{
3545 using namespace clang;
3546 TemplateName theTemplateName;
3547
3548 const Type* theType = qt.getTypePtr();
3549
3550 if (const TemplateSpecializationType* tst = llvm::dyn_cast_or_null<const TemplateSpecializationType>(theType)) {
3551 theTemplateName = tst->getTemplateName();
3552 } // We step into the decl dimension
3553 else if (ClassTemplateDecl* ctd = QualType2ClassTemplateDecl(qt)) {
3554 theTemplateName = TemplateName(ctd);
3555 }
3556
3557 return theTemplateName;
3558}
3559
3560////////////////////////////////////////////////////////////////////////////////
3561
3562static bool areEqualTypes(const clang::TemplateArgument& tArg,
3563 llvm::SmallVectorImpl<clang::TemplateArgument>& preceedingTArgs,
3564 const clang::NamedDecl& tPar,
3565 const cling::Interpreter& interp,
3566 const ROOT::TMetaUtils::TNormalizedCtxt& normCtxt)
3567{
3568 using namespace ROOT::TMetaUtils;
3569 using namespace clang;
3570
3571 // Check if this is a type for security
3572 TemplateTypeParmDecl* ttpdPtr = const_cast<TemplateTypeParmDecl*>(llvm::dyn_cast<TemplateTypeParmDecl>(&tPar));
3573 if (!ttpdPtr) return false;
3574 if (!ttpdPtr->hasDefaultArgument()) return false; // we should not be here in this case, but we protect us.
3575
3576 // Try the fast solution
3577 QualType tParQualType = ttpdPtr->getDefaultArgument();
3578 const QualType tArgQualType = tArg.getAsType();
3579
3580 // Now the equality tests for non template specialisations.
3581
3582 // The easy cases:
3583 // template <class T=double> class A; or
3584 // template <class T=A<float>> class B;
3585 if (tParQualType.getTypePtr() == tArgQualType.getTypePtr()) return true;
3586
3587 // Here the difficulty comes. We have to check if the argument is equal to its
3588 // default. We can do that bootstrapping an argument which has the default value
3589 // based on the preceeding arguments.
3590 // Basically we ask sema to give us the value of the argument given the template
3591 // of behind the parameter and the all the arguments.
3592 // So:
3593
3594 // Take the template out of the parameter
3595
3596 const clang::ElaboratedType* etype
3597 = llvm::dyn_cast<clang::ElaboratedType>(tParQualType.getTypePtr());
3598 while (etype) {
3599 tParQualType = clang::QualType(etype->getNamedType().getTypePtr(),0);
3600 etype = llvm::dyn_cast<clang::ElaboratedType>(tParQualType.getTypePtr());
3601 }
3602
3603 const TemplateSpecializationType* tst =
3604 llvm::dyn_cast<TemplateSpecializationType>(tParQualType.getTypePtr());
3605
3606 if(!tst) // nothing more to be tried. They are different indeed.
3607 return false;
3608
3609 ClassTemplateSpecializationDecl* TSTdecl
3610 = llvm::dyn_cast_or_null<ClassTemplateSpecializationDecl>(tArgQualType->getAsCXXRecordDecl());
3611
3612 if(!TSTdecl) // nothing more to be tried. They are different indeed.
3613 return false;
3614
3615 TemplateDecl *Template = tst->getTemplateName().getAsTemplateDecl();
3616
3617 // Take the template location
3618 SourceLocation TemplateLoc = Template->getSourceRange ().getBegin();
3619
3620 // Get the position of the "<" (LA) of the specializaion
3621 SourceLocation LAngleLoc = TSTdecl->getSourceRange().getBegin();
3622
3623
3624 // Enclose in a scope for the RAII
3625 bool isEqual=false;
3626 TemplateArgument newArg = tArg;
3627 {
3628 clang::Sema& S = interp.getCI()->getSema();
3629 cling::Interpreter::PushTransactionRAII clingRAII(const_cast<cling::Interpreter*>(&interp));
3630 clang::sema::HackForDefaultTemplateArg raii; // Hic sunt leones
3631 bool HasDefaultArgs;
3632 TemplateArgumentLoc defTArgLoc = S.SubstDefaultTemplateArgumentIfAvailable(Template,
3633 TemplateLoc,
3634 LAngleLoc,
3635 ttpdPtr,
3636 preceedingTArgs,
3637 HasDefaultArgs);
3638 // The substition can fail, in which case there would have been compilation
3639 // error printed on the screen.
3640 newArg = defTArgLoc.getArgument();
3641 if (newArg.isNull() ||
3642 newArg.getKind() != clang::TemplateArgument::Type) {
3643 ROOT::TMetaUtils::Error("areEqualTypes",
3644 "Template parameter substitution failed!");
3645 }
3646
3647 ClassTemplateSpecializationDecl* nTSTdecl
3648 = llvm::dyn_cast_or_null<ClassTemplateSpecializationDecl>(newArg.getAsType()->getAsCXXRecordDecl());
3649// std::cout << "nSTdecl is " << nTSTdecl << std::endl;
3650
3651 isEqual = (nTSTdecl && nTSTdecl->getMostRecentDecl() == TSTdecl->getMostRecentDecl()) ||
3652 (tParQualType.getTypePtr() == newArg.getAsType().getTypePtr());
3653 }
3654
3655
3656 return isEqual;
3657}
3658
3659
3660////////////////////////////////////////////////////////////////////////////////
3661/// std::cout << "Are equal values?\n";
3662
3663static bool areEqualValues(const clang::TemplateArgument& tArg,
3664 const clang::NamedDecl& tPar)
3665{
3666 using namespace clang;
3667 const NonTypeTemplateParmDecl* nttpdPtr = llvm::dyn_cast<NonTypeTemplateParmDecl>(&tPar);
3668 if (!nttpdPtr) return false;
3669 const NonTypeTemplateParmDecl& nttpd = *nttpdPtr;
3670
3671 if (!nttpd.hasDefaultArgument())
3672 return false;
3673
3674 // 64 bits wide and signed (non unsigned, that is why "false")
3675 llvm::APSInt defaultValueAPSInt(64, false);
3676 if (Expr* defArgExpr = nttpd.getDefaultArgument()) {
3677 const ASTContext& astCtxt = nttpdPtr->getASTContext();
3678 defArgExpr->isIntegerConstantExpr(defaultValueAPSInt, astCtxt);
3679 }
3680
3681 const int value = tArg.getAsIntegral().getLimitedValue();
3682
3683 // std::cout << (value == defaultValueAPSInt ? "yes!":"no") << std::endl;
3684 return value == defaultValueAPSInt;
3685}
3686
3687////////////////////////////////////////////////////////////////////////////////
3688/// Check if this NamedDecl is a template parameter with a default argument.
3689/// This is a single interface to treat both integral and type parameters.
3690/// Returns true if this is the case, false otherwise
3691
3692static bool isTypeWithDefault(const clang::NamedDecl* nDecl)
3693{
3694 using namespace clang;
3695 if (!nDecl) return false;
3696 if (const TemplateTypeParmDecl* ttpd = llvm::dyn_cast<TemplateTypeParmDecl>(nDecl))
3697 return ttpd->hasDefaultArgument();
3698 if (const NonTypeTemplateParmDecl* nttpd = llvm::dyn_cast<NonTypeTemplateParmDecl>(nDecl))
3699 return nttpd->hasDefaultArgument();
3700 return false;
3701
3702}
3703
3704static void KeepNParams(clang::QualType& normalizedType,
3705 const clang::QualType& vanillaType,
3706 const cling::Interpreter& interp,
3707 const ROOT::TMetaUtils::TNormalizedCtxt& normCtxt);
3708
3709// Returns true if normTArg might have changed.
3710static bool RecurseKeepNParams(clang::TemplateArgument &normTArg,
3711 const clang::TemplateArgument &tArg,
3712 const cling::Interpreter& interp,
3713 const ROOT::TMetaUtils::TNormalizedCtxt& normCtxt,
3714 const clang::ASTContext& astCtxt)
3715{
3716 using namespace ROOT::TMetaUtils;
3717 using namespace clang;
3718
3719 // Once we know there is no more default parameter, we can run through to the end
3720 // and/or recurse in the template parameter packs.
3721
3722 // If this is a type,
3723 // we need first of all to recurse: this argument may need to be manipulated
3724 if (tArg.getKind() == clang::TemplateArgument::Type) {
3725 QualType thisNormQualType = normTArg.getAsType();
3726 QualType thisArgQualType = tArg.getAsType();
3727 KeepNParams(thisNormQualType,
3728 thisArgQualType,
3729 interp,
3730 normCtxt);
3731 normTArg = TemplateArgument(thisNormQualType);
3732 return (thisNormQualType != thisArgQualType);
3733 } else if (normTArg.getKind() == clang::TemplateArgument::Pack) {
3734 assert( tArg.getKind() == clang::TemplateArgument::Pack );
3735
3736 SmallVector<TemplateArgument, 2> desArgs;
3737 bool mightHaveChanged = true;
3738 for (auto I = normTArg.pack_begin(), E = normTArg.pack_end(),
3739 FI = tArg.pack_begin(), FE = tArg.pack_end();
3740 I != E && FI != FE; ++I, ++FI)
3741 {
3742 TemplateArgument pack_arg(*I);
3743 mightHaveChanged |= RecurseKeepNParams(pack_arg, *FI, interp, normCtxt, astCtxt);
3744 desArgs.push_back(pack_arg);
3745 }
3746 if (mightHaveChanged) {
3747 ASTContext &mutableCtx( const_cast<ASTContext&>(astCtxt) );
3748 normTArg = TemplateArgument::CreatePackCopy(mutableCtx, desArgs);
3749 }
3750 return mightHaveChanged;
3751 }
3752 return false;
3753}
3754
3755
3756////////////////////////////////////////////////////////////////////////////////
3757/// This function allows to manipulate the number of arguments in the type
3758/// of a template specialisation.
3759
3760static void KeepNParams(clang::QualType& normalizedType,
3761 const clang::QualType& vanillaType,
3762 const cling::Interpreter& interp,
3763 const ROOT::TMetaUtils::TNormalizedCtxt& normCtxt)
3764{
3765 using namespace ROOT::TMetaUtils;
3766 using namespace clang;
3767
3768 // If this type has no template specialisation behind, we don't need to do
3769 // anything
3770 ClassTemplateSpecializationDecl* ctsd;
3771 ClassTemplateDecl* ctd;
3772 if (! QualType2Template(vanillaType, ctd, ctsd)) return ;
3773
3774 // Even if this is a template, if we don't keep any argument, return
3775 const int nArgsToKeep = normCtxt.GetNargsToKeep(ctd);
3776
3777 // Important in case of early return: we must restore the original qualtype
3778 QualType originalNormalizedType = normalizedType;
3779
3780 const ASTContext& astCtxt = ctsd->getASTContext();
3781
3782
3783 // In case of name* we need to strip the pointer first, add the default and attach
3784 // the pointer once again.
3785 if (llvm::isa<clang::PointerType>(normalizedType.getTypePtr())) {
3786 // Get the qualifiers.
3787 clang::Qualifiers quals = normalizedType.getQualifiers();
3788 auto valNormalizedType = normalizedType->getPointeeType();
3789 KeepNParams(valNormalizedType,vanillaType, interp, normCtxt);
3790 normalizedType = astCtxt.getPointerType(valNormalizedType);
3791 // Add back the qualifiers.
3792 normalizedType = astCtxt.getQualifiedType(normalizedType, quals);
3793 return;
3794 }
3795
3796 // In case of Int_t& we need to strip the pointer first, desugar and attach
3797 // the pointer once again.
3798 if (llvm::isa<clang::ReferenceType>(normalizedType.getTypePtr())) {
3799 // Get the qualifiers.
3800 bool isLValueRefTy = llvm::isa<clang::LValueReferenceType>(normalizedType.getTypePtr());
3801 clang::Qualifiers quals = normalizedType.getQualifiers();
3802 auto valNormType = normalizedType->getPointeeType();
3803 KeepNParams(valNormType, vanillaType, interp, normCtxt);
3804
3805 // Add the r- or l- value reference type back to the desugared one
3806 if (isLValueRefTy)
3807 normalizedType = astCtxt.getLValueReferenceType(valNormType);
3808 else
3809 normalizedType = astCtxt.getRValueReferenceType(valNormType);
3810 // Add back the qualifiers.
3811 normalizedType = astCtxt.getQualifiedType(normalizedType, quals);
3812 return;
3813 }
3814
3815 // Treat the Scope (factorise the code out to reuse it in AddDefaultParameters)
3816 bool prefix_changed = false;
3817 clang::NestedNameSpecifier* prefix = nullptr;
3818 clang::Qualifiers prefix_qualifiers = normalizedType.getLocalQualifiers();
3819 const clang::ElaboratedType* etype
3820 = llvm::dyn_cast<clang::ElaboratedType>(normalizedType.getTypePtr());
3821 if (etype) {
3822 // We have to also handle the prefix.
3823 // TODO: we ought to be running KeepNParams
3824 prefix = AddDefaultParametersNNS(astCtxt, etype->getQualifier(), interp, normCtxt);
3825 prefix_changed = prefix != etype->getQualifier();
3826 normalizedType = clang::QualType(etype->getNamedType().getTypePtr(),0);
3827 }
3828
3829 // The canonical decl does not necessarily have the template default arguments.
3830 // Need to walk through the redecl chain to find it (we know there will be no
3831 // inconsistencies, at least)
3832 const clang::ClassTemplateDecl* ctdWithDefaultArgs = ctd;
3833 for (const RedeclarableTemplateDecl* rd: ctdWithDefaultArgs->redecls()) {
3834 clang::TemplateParameterList* tpl = rd->getTemplateParameters();
3835 if (tpl->getMinRequiredArguments () < tpl->size()) {
3836 ctdWithDefaultArgs = llvm::dyn_cast<clang::ClassTemplateDecl>(rd);
3837 break;
3838 }
3839 }
3840
3841 if (!ctdWithDefaultArgs) {
3842 Error("KeepNParams", "Not found template default arguments\n");
3843 normalizedType=originalNormalizedType;
3844 return;
3845 }
3846
3847 TemplateParameterList* tParsPtr = ctdWithDefaultArgs->getTemplateParameters();
3848 const TemplateParameterList& tPars = *tParsPtr;
3849 const TemplateArgumentList& tArgs = ctsd->getTemplateArgs();
3850
3851 // We extract the template name from the type
3852 TemplateName theTemplateName = ExtractTemplateNameFromQualType(normalizedType);
3853 if (theTemplateName.isNull()) {
3854 normalizedType=originalNormalizedType;
3855 return;
3856 }
3857
3858 const TemplateSpecializationType* normalizedTst =
3859 llvm::dyn_cast<TemplateSpecializationType>(normalizedType.getTypePtr());
3860 if (!normalizedTst) {
3861 normalizedType=originalNormalizedType;
3862 return;
3863 }
3864
3865 const clang::ClassTemplateSpecializationDecl* TSTdecl
3866 = llvm::dyn_cast_or_null<const clang::ClassTemplateSpecializationDecl>(normalizedType.getTypePtr()->getAsCXXRecordDecl());
3867 bool isStdDropDefault = TSTdecl && IsStdDropDefaultClass(*TSTdecl);
3868
3869 // Loop over the template parameters and arguments recursively.
3870 // We go down the two lanes: the one of template parameters (decls) and the
3871 // one of template arguments (QualTypes) in parallel. The former are a
3872 // property of the template, independent of its instantiations.
3873 // The latter are a property of the instance itself.
3874 llvm::SmallVector<TemplateArgument, 4> argsToKeep;
3875
3876 const int nArgs = tArgs.size();
3877 const int nNormArgs = normalizedTst->getNumArgs();
3878
3879 bool mightHaveChanged = false;
3880
3881 // becomes true when a parameter has a value equal to its default
3882 for (int formal = 0, inst = 0; formal != nArgs; ++formal, ++inst) {
3883 const NamedDecl* tParPtr = tPars.getParam(formal);
3884 if (!tParPtr) {
3885 Error("KeepNParams", "The parameter number %s is null.\n", formal);
3886 continue;
3887 }
3888
3889 // Stop if the normalized TemplateSpecializationType has less arguments than
3890 // the one index is pointing at.
3891 // We piggy back on the AddDefaultParameters routine basically.
3892 if (formal == nNormArgs || inst == nNormArgs) break;
3893
3894 const TemplateArgument& tArg = tArgs.get(formal);
3895 TemplateArgument normTArg(normalizedTst->getArgs()[inst]);
3896
3897 bool shouldKeepArg = nArgsToKeep < 0 || inst < nArgsToKeep;
3898 if (isStdDropDefault) shouldKeepArg = false;
3899
3900 // Nothing to do here: either this parameter has no default, or we have to keep it.
3901 // FIXME: Temporary measure to get Atlas started with this.
3902 // We put a hard cut on the number of template arguments to keep, w/o checking if
3903 // they are non default. This makes this feature UNUSABLE for cases like std::vector,
3904 // where 2 different entities would have the same name if an allocator different from
3905 // the default one is by chance used.
3906 if (!isTypeWithDefault(tParPtr) || shouldKeepArg) {
3907 if ( tParPtr->isTemplateParameterPack() ) {
3908 // This is the last template parameter in the template declaration
3909 // but it is signaling that there can be an arbitrary number of arguments
3910 // in the template instance. So to avoid inadvertenly dropping those
3911 // arguments we just process all remaining argument and exit the main loop.
3912 for( ; inst != nNormArgs; ++inst) {
3913 normTArg = normalizedTst->getArgs()[inst];
3914 mightHaveChanged |= RecurseKeepNParams(normTArg, tArg, interp, normCtxt, astCtxt);
3915 argsToKeep.push_back(normTArg);
3916 }
3917 // Done.
3918 break;
3919 }
3920 mightHaveChanged |= RecurseKeepNParams(normTArg, tArg, interp, normCtxt, astCtxt);
3921 argsToKeep.push_back(normTArg);
3922 continue;
3923 } else {
3924 if (!isStdDropDefault) {
3925 // Here we should not break but rather check if the value is the default one.
3926 mightHaveChanged = true;
3927 break;
3928 }
3929 // For std, we want to check the default args values.
3930 }
3931
3932 // Now, we keep it only if it not is equal to its default, expressed in the arg
3933 // Some gymnastic is needed to decide how to check for equality according to the
3934 // flavour of Type: templateType or Integer
3935 bool equal=false;
3936 auto argKind = tArg.getKind();
3937 if (argKind == clang::TemplateArgument::Type){
3938 // we need all the info
3939 equal = areEqualTypes(tArg, argsToKeep, *tParPtr, interp, normCtxt);
3940 } else if (argKind == clang::TemplateArgument::Integral){
3941 equal = areEqualValues(tArg, *tParPtr);
3942 }
3943 if (!equal) {
3944 mightHaveChanged |= RecurseKeepNParams(normTArg, tArg, interp, normCtxt, astCtxt);
3945 argsToKeep.push_back(normTArg);
3946 } else {
3947 mightHaveChanged = true;
3948 }
3949
3950
3951 } // of loop over parameters and arguments
3952
3953 if (!prefix_changed && !mightHaveChanged) {
3954 normalizedType = originalNormalizedType;
3955 return;
3956 }
3957
3958 // now, let's remanipulate our Qualtype
3959 if (mightHaveChanged) {
3960 Qualifiers qualifiers = normalizedType.getLocalQualifiers();
3961 normalizedType = astCtxt.getTemplateSpecializationType(theTemplateName,
3962 argsToKeep,
3963 normalizedType.getTypePtr()->getCanonicalTypeInternal());
3964 normalizedType = astCtxt.getQualifiedType(normalizedType, qualifiers);
3965 }
3966
3967 // Here we have (prefix_changed==true || mightHaveChanged), in both case
3968 // we need to reconstruct the type.
3969 if (prefix) {
3970 normalizedType = astCtxt.getElaboratedType(clang::ETK_None,prefix,normalizedType);
3971 normalizedType = astCtxt.getQualifiedType(normalizedType,prefix_qualifiers);
3972 }
3973
3974}
3975
3976////////////////////////////////////////////////////////////////////////////////
3977/// Return the type normalized for ROOT,
3978/// keeping only the ROOT opaque typedef (Double32_t, etc.) and
3979/// adding default template argument for all types except those explicitly
3980/// requested to be drop by the user.
3981/// Default template for STL collections are not yet removed by this routine.
3982
3983clang::QualType ROOT::TMetaUtils::GetNormalizedType(const clang::QualType &type, const cling::Interpreter &interpreter, const TNormalizedCtxt &normCtxt)
3984{
3985 clang::ASTContext &ctxt = interpreter.getCI()->getASTContext();
3986
3987 // Modules can trigger deserialization.
3988 cling::Interpreter::PushTransactionRAII RAII(const_cast<cling::Interpreter*>(&interpreter));
3989 clang::QualType normalizedType = cling::utils::Transform::GetPartiallyDesugaredType(ctxt, type, normCtxt.GetConfig(), true /* fully qualify */);
3990
3991 // Readd missing default template parameters
3992 normalizedType = ROOT::TMetaUtils::AddDefaultParameters(normalizedType, interpreter, normCtxt);
3993
3994 // Get the number of arguments to keep in case they are not default.
3995 KeepNParams(normalizedType,type,interpreter,normCtxt);
3996
3997 return normalizedType;
3998}
3999
4000////////////////////////////////////////////////////////////////////////////////
4001/// Return the type name normalized for ROOT,
4002/// keeping only the ROOT opaque typedef (Double32_t, etc.) and
4003/// adding default template argument for all types except the STL collections
4004/// where we remove the default template argument if any.
4005///
4006/// This routine might actually belong in the interpreter because
4007/// cache the clang::Type might be intepreter specific.
4008
4009void ROOT::TMetaUtils::GetNormalizedName(std::string &norm_name, const clang::QualType &type, const cling::Interpreter &interpreter, const TNormalizedCtxt &normCtxt)
4010{
4011 if (type.isNull()) {
4012 norm_name = "";
4013 return;
4014 }
4015
4016 clang::QualType normalizedType = GetNormalizedType(type,interpreter,normCtxt);
4017
4018 clang::ASTContext &ctxt = interpreter.getCI()->getASTContext();
4019 clang::PrintingPolicy policy(ctxt.getPrintingPolicy());
4020 policy.SuppressTagKeyword = true; // Never get the class or struct keyword
4021 policy.SuppressScope = true; // Force the scope to be coming from a clang::ElaboratedType.
4022 policy.AnonymousTagLocations = false; // Do not extract file name + line number for anonymous types.
4023 // The scope suppression is required for getting rid of the anonymous part of the name of a class defined in an anonymous namespace.
4024 // This gives us more control vs not using the clang::ElaboratedType and relying on the Policy.SuppressUnwrittenScope which would
4025 // strip both the anonymous and the inline namespace names (and we probably do not want the later to be suppressed).
4026
4027 std::string normalizedNameStep1;
4028
4029 // getAsStringInternal can trigger deserialization
4030 cling::Interpreter::PushTransactionRAII clingRAII(const_cast<cling::Interpreter*>(&interpreter));
4031 normalizedType.getAsStringInternal(normalizedNameStep1,policy);
4032
4033 // Still remove the std:: and default template argument for STL container and
4034 // normalize the location and amount of white spaces.
4037
4038 // The result of this routine is by definition a fully qualified name. There is an implicit starting '::' at the beginning of the name.
4039 // Depending on how the user typed their code, in particular typedef declarations, we may end up with an explicit '::' being
4040 // part of the result string. For consistency, we must remove it.
4041 if (norm_name.length()>2 && norm_name[0]==':' && norm_name[1]==':') {
4042 norm_name.erase(0,2);
4043 }
4044
4045}
4046
4047////////////////////////////////////////////////////////////////////////////////
4048
4049void ROOT::TMetaUtils::GetNormalizedName(std::string &norm_name,
4050 const clang::TypeDecl* typeDecl,
4051 const cling::Interpreter &interpreter)
4052{
4053 ROOT::TMetaUtils::TNormalizedCtxt tNormCtxt(interpreter.getLookupHelper());
4054 const clang::Sema &sema = interpreter.getSema();
4055 clang::ASTContext& astCtxt = sema.getASTContext();
4056 clang::QualType qualType = astCtxt.getTypeDeclType(typeDecl);
4057
4059 qualType,
4060 interpreter,
4061 tNormCtxt);
4062}
4063
4064////////////////////////////////////////////////////////////////////////////////
4065std::pair<std::string,clang::QualType>
4066ROOT::TMetaUtils::GetNameTypeForIO(const clang::QualType& thisType,
4067 const cling::Interpreter &interpreter,
4068 const TNormalizedCtxt &normCtxt,
4070{
4071 std::string thisTypeName;
4072 GetNormalizedName(thisTypeName, thisType, interpreter, normCtxt );
4073 bool hasChanged;
4074 auto thisTypeNameForIO = TClassEdit::GetNameForIO(thisTypeName, mode, &hasChanged);
4075 if (!hasChanged) return std::make_pair(thisTypeName,thisType);
4076
4078 ROOT::TMetaUtils::Info("ROOT::TMetaUtils::GetTypeForIO",
4079 "Name changed from %s to %s\n", thisTypeName.c_str(), thisTypeNameForIO.c_str());
4080 }
4081
4082 auto& lookupHelper = interpreter.getLookupHelper();
4083
4084 const clang::Type* typePtrForIO;
4085 lookupHelper.findScope(thisTypeNameForIO,
4086 cling::LookupHelper::DiagSetting::NoDiagnostics,
4087 &typePtrForIO);
4088
4089 // This should never happen
4090 if (!typePtrForIO) {
4091 ROOT::TMetaUtils::Fatal("ROOT::TMetaUtils::GetTypeForIO",
4092 "Type not found: %s.",thisTypeNameForIO.c_str());
4093 }
4094
4095 clang::QualType typeForIO(typePtrForIO,0);
4096
4097 // Check if this is a class. Indeed it could well be a POD
4098 if (!typeForIO->isRecordType()) {
4099 return std::make_pair(thisTypeNameForIO,typeForIO);
4100 }
4101
4102 auto thisDeclForIO = typeForIO->getAsCXXRecordDecl();
4103 if (!thisDeclForIO) {
4104 ROOT::TMetaUtils::Error("ROOT::TMetaUtils::GetTypeForIO",
4105 "The type for IO corresponding to %s is %s and it could not be found in the AST as class.\n", thisTypeName.c_str(), thisTypeNameForIO.c_str());
4106 return std::make_pair(thisTypeName,thisType);
4107 }
4108
4109 return std::make_pair(thisTypeNameForIO,typeForIO);
4110}
4111
4112////////////////////////////////////////////////////////////////////////////////
4113
4114clang::QualType ROOT::TMetaUtils::GetTypeForIO(const clang::QualType& thisType,
4115 const cling::Interpreter &interpreter,
4116 const TNormalizedCtxt &normCtxt,
4118{
4119 return GetNameTypeForIO(thisType, interpreter, normCtxt, mode).second;
4120}
4121
4122////////////////////////////////////////////////////////////////////////////////
4123/// Return the dictionary file name for a module
4124
4125std::string ROOT::TMetaUtils::GetModuleFileName(const char* moduleName)
4126{
4127 std::string dictFileName(moduleName);
4128 dictFileName += "_rdict.pcm";
4129 return dictFileName;
4130}
4131
4132int dumpDeclForAssert(const clang::Decl& D, const char* commentStart) {
4133 llvm::errs() << llvm::StringRef(commentStart, 80) << '\n';
4134 D.dump();
4135 return 0;
4136}
4137
4138////////////////////////////////////////////////////////////////////////////////
4139/// Returns the comment (// striped away), annotating declaration in a meaningful
4140/// for ROOT IO way.
4141/// Takes optional out parameter clang::SourceLocation returning the source
4142/// location of the comment.
4143///
4144/// CXXMethodDecls, FieldDecls and TagDecls are annotated.
4145/// CXXMethodDecls declarations and FieldDecls are annotated as follows:
4146/// Eg. void f(); // comment1
4147/// int member; // comment2
4148/// Inline definitions of CXXMethodDecls after the closing } \n. Eg:
4149/// void f()
4150/// {...} // comment3
4151/// TagDecls are annotated in the end of the ClassDef macro. Eg.
4152/// class MyClass {
4153/// ...
4154/// ClassDef(MyClass, 1) // comment4
4155///
4156
4157llvm::StringRef ROOT::TMetaUtils::GetComment(const clang::Decl &decl, clang::SourceLocation *loc)
4158{
4159 clang::SourceManager& sourceManager = decl.getASTContext().getSourceManager();
4160 clang::SourceLocation sourceLocation = decl.getEndLoc();
4161
4162 // If the location is a macro get the expansion location.
4163 sourceLocation = sourceManager.getExpansionRange(sourceLocation).getEnd();
4164 // FIXME: We should optimize this routine instead making it do the wrong thing
4165 // returning an empty comment if the decl came from the AST.
4166 // In order to do that we need to: check if the decl has an attribute and
4167 // return the attribute content (including walking the redecl chain) and if
4168 // this is not the case we should try finding it in the header file.
4169 // This will allow us to move the implementation of TCling*Info::Title() in
4170 // TClingDeclInfo.
4171 if (!decl.hasOwningModule() && sourceManager.isLoadedSourceLocation(sourceLocation)) {
4172 // Do not touch disk for nodes coming from the PCH.
4173 return "";
4174 }
4175
4176 bool invalid;
4177 const char *commentStart = sourceManager.getCharacterData(sourceLocation, &invalid);
4178 if (invalid)
4179 return "";
4180
4181 bool skipToSemi = true;
4182 if (const clang::FunctionDecl* FD = clang::dyn_cast<clang::FunctionDecl>(&decl)) {
4183 if (FD->isImplicit()) {
4184 // Compiler generated function.
4185 return "";
4186 }
4187 if (FD->isExplicitlyDefaulted() || FD->isDeletedAsWritten()) {
4188 // ctorOrFunc() = xyz; with commentStart pointing somewhere into
4189 // ctorOrFunc.
4190 // We have to skipToSemi
4191 } else if (FD->doesThisDeclarationHaveABody()) {
4192 // commentStart is at body's '}'
4193 // But we might end up e.g. at the ')' of a CPP macro
4194 assert((decl.getEndLoc() != sourceLocation || *commentStart == '}'
4195 || dumpDeclForAssert(*FD, commentStart))
4196 && "Expected macro or end of body at '}'");
4197 if (*commentStart) ++commentStart;
4198
4199 // We might still have a ';'; skip the spaces and check.
4200 while (*commentStart && isspace(*commentStart)
4201 && *commentStart != '\n' && *commentStart != '\r') {
4202 ++commentStart;
4203 }
4204 if (*commentStart == ';') ++commentStart;
4205
4206 skipToSemi = false;
4207 }
4208 } else if (const clang::EnumConstantDecl* ECD
4209 = clang::dyn_cast<clang::EnumConstantDecl>(&decl)) {
4210 // either "konstant = 12, //COMMENT" or "lastkonstant // COMMENT"
4211 if (ECD->getNextDeclInContext())
4212 while (*commentStart && *commentStart != ',' && *commentStart != '\r' && *commentStart != '\n')
4213 ++commentStart;
4214 // else commentStart already points to the end.
4215
4216 skipToSemi = false;
4217 }
4218
4219 if (skipToSemi) {
4220 while (*commentStart && *commentStart != ';' && *commentStart != '\r' && *commentStart != '\n')
4221 ++commentStart;
4222 if (*commentStart == ';') ++commentStart;
4223 }
4224
4225 // Now skip the spaces until beginning of comments or EOL.
4226 while ( *commentStart && isspace(*commentStart)
4227 && *commentStart != '\n' && *commentStart != '\r') {
4228 ++commentStart;
4229 }
4230
4231 if (commentStart[0] != '/' ||
4232 (commentStart[1] != '/' && commentStart[1] != '*')) {
4233 // not a comment
4234 return "";
4235 }
4236
4237 // Treat by default c++ comments (+2) but also Doxygen comments (+4)
4238 // Int_t fPx; ///< Some doxygen comment for persistent data.
4239 // Int_t fPy; //!< Some doxygen comment for persistent data.
4240 // Int_t fPz; /*!< Some doxygen comment for persistent data. */
4241 // Int_t fPa; /**< Some doxygen comment for persistent data. */
4242 unsigned int skipChars = 2;
4243 if (commentStart[0] == '/' &&
4244 commentStart[1] == '/' &&
4245 (commentStart[2] == '/' || commentStart[2] == '!') &&
4246 commentStart[3] == '<') {
4247 skipChars = 4;
4248 } else if (commentStart[0] == '/' &&
4249 commentStart[1] == '*' &&
4250 (commentStart[2] == '*' || commentStart[2] == '!') &&
4251 commentStart[3] == '<') {
4252 skipChars = 4;
4253 }
4254
4255 commentStart += skipChars;
4256
4257 // Now skip the spaces after comment start until EOL.
4258 while ( *commentStart && isspace(*commentStart)
4259 && *commentStart != '\n' && *commentStart != '\r') {
4260 ++commentStart;
4261 }
4262 const char* commentEnd = commentStart;
4263 // Even for /* comments we only take the first line into account.
4264 while (*commentEnd && *commentEnd != '\n' && *commentEnd != '\r') {
4265 ++commentEnd;
4266 }
4267
4268 // "Skip" (don't include) trailing space.
4269 // *commentEnd points behind comment end thus check commentEnd[-1]
4270 while (commentEnd > commentStart && isspace(commentEnd[-1])) {
4271 --commentEnd;
4272 }
4273
4274 if (loc) {
4275 // Find the true beginning of a comment.
4276 unsigned offset = commentStart - sourceManager.getCharacterData(sourceLocation);
4277 *loc = sourceLocation.getLocWithOffset(offset - 1);
4278 }
4279
4280 return llvm::StringRef(commentStart, commentEnd - commentStart);
4281}
4282
4283////////////////////////////////////////////////////////////////////////////////
4284/// Return true if class has any of class declarations like ClassDef, ClassDefNV, ClassDefOverride
4285
4286bool ROOT::TMetaUtils::HasClassDefMacro(const clang::Decl *decl, const cling::Interpreter &interpreter)
4287{
4288 if (!decl) return false;
4289
4290 auto& sema = interpreter.getCI()->getSema();
4291 auto maybeMacroLoc = decl->getLocation();
4292
4293 if (!maybeMacroLoc.isMacroID()) return false;
4294
4295 static const std::vector<std::string> signatures =
4296 { "ClassDef", "ClassDefOverride", "ClassDefNV", "ClassDefInline", "ClassDefInlineOverride", "ClassDefInlineNV" };
4297
4298 for (auto &name : signatures)
4299 if (sema.findMacroSpelling(maybeMacroLoc, name))
4300 return true;
4301
4302 return false;
4303}
4304
4305////////////////////////////////////////////////////////////////////////////////
4306/// Return the class comment after the ClassDef:
4307/// class MyClass {
4308/// ...
4309/// ClassDef(MyClass, 1) // class comment
4310///
4311
4312llvm::StringRef ROOT::TMetaUtils::GetClassComment(const clang::CXXRecordDecl &decl,
4313 clang::SourceLocation *loc,
4314 const cling::Interpreter &interpreter)
4315{
4316 using namespace clang;
4317
4318 const Decl* DeclFileLineDecl
4319 = interpreter.getLookupHelper().findFunctionProto(&decl, "DeclFileLine", "",
4320 cling::LookupHelper::NoDiagnostics);
4321
4322 // For now we allow only a special macro (ClassDef) to have meaningful comments
4323 if (HasClassDefMacro(DeclFileLineDecl, interpreter)) {
4324 SourceLocation commentSLoc;
4325 llvm::StringRef comment = ROOT::TMetaUtils::GetComment(*DeclFileLineDecl, &commentSLoc);
4326 if (comment.size()) {
4327 if (loc) {
4328 *loc = commentSLoc;
4329 }
4330 return comment;
4331 }
4332 }
4333 return llvm::StringRef();
4334}
4335
4336////////////////////////////////////////////////////////////////////////////////
4337/// Return the base/underlying type of a chain of array or pointers type.
4338/// Does not yet support the array and pointer part being intermixed.
4339
4341{
4342 const clang::Type *rawtype = type.getTypePtr();
4343
4344 // NOTE: We probably meant isa<clang::ElaboratedType>
4345 if (rawtype->isElaboratedTypeSpecifier() ) {
4346 rawtype = rawtype->getCanonicalTypeInternal().getTypePtr();
4347 }
4348 if (rawtype->isArrayType()) {
4349 rawtype = type.getTypePtr()->getBaseElementTypeUnsafe ();
4350 }
4351 if (rawtype->isPointerType() || rawtype->isReferenceType() ) {
4352 //Get to the 'raw' type.
4353 clang::QualType pointee;
4354 while ( (pointee = rawtype->getPointeeType()) , pointee.getTypePtrOrNull() && pointee.getTypePtr() != rawtype)
4355 {
4356 rawtype = pointee.getTypePtr();
4357
4358 if (rawtype->isElaboratedTypeSpecifier() ) {
4359 rawtype = rawtype->getCanonicalTypeInternal().getTypePtr();
4360 }
4361 if (rawtype->isArrayType()) {
4362 rawtype = rawtype->getBaseElementTypeUnsafe ();
4363 }
4364 }
4365 }
4366 if (rawtype->isArrayType()) {
4367 rawtype = rawtype->getBaseElementTypeUnsafe ();
4368 }
4369 return rawtype;
4370}
4371
4372////////////////////////////////////////////////////////////////////////////////
4373/// Return true, if the decl is part of the std namespace.
4374
4375bool ROOT::TMetaUtils::IsStdClass(const clang::RecordDecl &cl)
4376{
4378}
4379
4380////////////////////////////////////////////////////////////////////////////////
4381/// Return true, if the decl is part of the std namespace and we want
4382/// its default parameter dropped.
4383
4384bool ROOT::TMetaUtils::IsStdDropDefaultClass(const clang::RecordDecl &cl)
4385{
4386 // Might need to reduce it to shared_ptr and STL collection.s
4388 static const char *names[] =
4389 { "shared_ptr", "__shared_ptr",
4390 "vector", "list", "deque", "map", "multimap", "set", "multiset", "bitset"};
4391 llvm::StringRef clname(cl.getName());
4392 for(auto &&name : names) {
4393 if (clname == name) return true;
4394 }
4395 }
4396 return false;
4397}
4398
4399////////////////////////////////////////////////////////////////////////////////
4400/// This is a recursive function
4401
4402bool ROOT::TMetaUtils::MatchWithDeclOrAnyOfPrevious(const clang::CXXRecordDecl &cl,
4403 const clang::CXXRecordDecl &currentCl)
4404{
4405 // We found it: let's return true
4406 if (&cl == &currentCl) return true;
4407
4408 const clang::CXXRecordDecl* previous = currentCl.getPreviousDecl();
4409
4410 // There is no previous decl, so we cannot possibly find it
4411 if (NULL == previous){
4412 return false;
4413 }
4414
4415 // We try to find it in the previous
4417
4418}
4419
4420//______________________________________________________________________________
4421
4422bool ROOT::TMetaUtils::IsOfType(const clang::CXXRecordDecl &cl, const std::string& typ, const cling::LookupHelper& lh)
4423{
4424 // Return true if the decl is of type.
4425 // A proper hashtable for caching results would be the ideal solution
4426 // 1) Only one lookup per type
4427 // 2) No string comparison
4428 // We may use a map which becomes an unordered map if c++11 is enabled?
4429
4430 const clang::CXXRecordDecl *thisDecl =
4431 llvm::dyn_cast_or_null<clang::CXXRecordDecl>(lh.findScope(typ, cling::LookupHelper::WithDiagnostics));
4432
4433 // this would be probably an assert given that this state is not reachable unless a mistake is somewhere
4434 if (! thisDecl){
4435 Error("IsOfType","Record decl of type %s not found in the AST.", typ.c_str());
4436 return false;
4437 }
4438
4439 // Now loop on all previous decls to seek a match
4440 const clang::CXXRecordDecl *mostRecentDecl = thisDecl->getMostRecentDecl();
4441 bool matchFound = MatchWithDeclOrAnyOfPrevious (cl,*mostRecentDecl);
4442
4443 return matchFound;
4444}
4445
4446////////////////////////////////////////////////////////////////////////////////
4447/// type : type name: vector<list<classA,allocator>,allocator>
4448/// result: 0 : not stl container
4449/// abs(result): code of container 1=vector,2=list,3=deque,4=map
4450/// 5=multimap,6=set,7=multiset
4451
4453{
4454 // This routine could be enhanced to also support:
4455 //
4456 // testAlloc: if true, we test allocator, if it is not default result is negative
4457 // result: 0 : not stl container
4458 // abs(result): code of container 1=vector,2=list,3=deque,4=map
4459 // 5=multimap,6=set,7=multiset
4460 // positive val: we have a vector or list with default allocator to any depth
4461 // like vector<list<vector<int>>>
4462 // negative val: STL container other than vector or list, or non default allocator
4463 // For example: vector<deque<int>> has answer -1
4464
4465 if (!IsStdClass(cl)) {
4466 auto *nsDecl = llvm::dyn_cast<clang::NamespaceDecl>(cl.getDeclContext());
4467 if (cl.getName() != "RVec" || nsDecl == nullptr || nsDecl->getName() != "VecOps")
4468 return ROOT::kNotSTL;
4469
4470 auto *parentNsDecl = llvm::dyn_cast<clang::NamespaceDecl>(cl.getDeclContext()->getParent());
4471 if (parentNsDecl == nullptr || parentNsDecl->getName() != "ROOT")
4472 return ROOT::kNotSTL;
4473 }
4474
4475 return STLKind(cl.getName());
4476}
4477
4479 using namespace clang;
4480 struct SearchTypedef: public TypeVisitor<SearchTypedef, bool> {
4481 bool VisitTypedefType(const TypedefType* TD) {
4482 return true;
4483 }
4484 bool VisitArrayType(const ArrayType* AT) {
4485 return Visit(AT->getElementType().getTypePtr());
4486 }
4487 bool VisitDecltypeType(const DecltypeType* DT) {
4488 return Visit(DT->getUnderlyingType().getTypePtr());
4489 }
4490 bool VisitPointerType(const PointerType* PT) {
4491 return Visit(PT->getPointeeType().getTypePtr());
4492 }
4493 bool VisitReferenceType(const ReferenceType* RT) {
4494 return Visit(RT->getPointeeType().getTypePtr());
4495 }
4496 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType* STST) {
4497 return Visit(STST->getReplacementType().getTypePtr());
4498 }
4499 bool VisitTemplateSpecializationType(const TemplateSpecializationType* TST) {
4500 for (int I = 0, N = TST->getNumArgs(); I < N; ++I) {
4501 const TemplateArgument& TA = TST->getArg(I);
4502 if (TA.getKind() == TemplateArgument::Type
4503 && Visit(TA.getAsType().getTypePtr()))
4504 return true;
4505 }
4506 return false;
4507 }
4508 bool VisitTemplateTypeParmType(const TemplateTypeParmType* TTPT) {
4509 return false; // shrug...
4510 }
4511 bool VisitTypeOfType(const TypeOfType* TOT) {
4512 return TOT->getUnderlyingType().getTypePtr();
4513 }
4514 bool VisitElaboratedType(const ElaboratedType* ET) {
4515 NestedNameSpecifier* NNS = ET->getQualifier();
4516 while (NNS) {
4517 if (NNS->getKind() == NestedNameSpecifier::TypeSpec) {
4518 if (Visit(NNS->getAsType()))
4519 return true;
4520 }
4521 NNS = NNS->getPrefix();
4522 }
4523 return Visit(ET->getNamedType().getTypePtr());
4524 }
4525 };
4526
4527 SearchTypedef ST;
4528 return ST.Visit(T);
4529}
4530
4531////////////////////////////////////////////////////////////////////////////////
4532/// Check if 'input' or any of its template parameter was substituted when
4533/// instantiating the class template instance and replace it with the
4534/// partially sugared types we have from 'instance'.
4535
4536clang::QualType ROOT::TMetaUtils::ReSubstTemplateArg(clang::QualType input, const clang::Type *instance)
4537{
4538 if (!instance) return input;
4539 // if there is no typedef in instance then there is nothing guiding any
4540 // template parameter typedef replacement.
4542 return input;
4543
4544 using namespace llvm;
4545 using namespace clang;
4546 const clang::ASTContext &Ctxt = instance->getAsCXXRecordDecl()->getASTContext();
4547
4548 // Treat scope (clang::ElaboratedType) if any.
4549 const clang::ElaboratedType* etype
4550 = llvm::dyn_cast<clang::ElaboratedType>(input.getTypePtr());
4551 if (etype) {
4552 // We have to also handle the prefix.
4553
4554 clang::Qualifiers scope_qualifiers = input.getLocalQualifiers();
4555 assert(instance->getAsCXXRecordDecl()!=0 && "ReSubstTemplateArg only makes sense with a type representing a class.");
4556
4557 clang::NestedNameSpecifier *scope = ReSubstTemplateArgNNS(Ctxt,etype->getQualifier(),instance);
4558 clang::QualType subTy = ReSubstTemplateArg(clang::QualType(etype->getNamedType().getTypePtr(),0),instance);
4559
4560 if (scope) subTy = Ctxt.getElaboratedType(clang::ETK_None,scope,subTy);
4561 subTy = Ctxt.getQualifiedType(subTy,scope_qualifiers);
4562 return subTy;
4563 }
4564
4565 QualType QT = input;
4566
4567 // In case of Int_t* we need to strip the pointer first, ReSubst and attach
4568 // the pointer once again.
4569 if (isa<clang::PointerType>(QT.getTypePtr())) {
4570 // Get the qualifiers.
4571 Qualifiers quals = QT.getQualifiers();
4572 QualType nQT;
4573 nQT = ReSubstTemplateArg(QT->getPointeeType(),instance);
4574 if (nQT == QT->getPointeeType()) return QT;
4575
4576 QT = Ctxt.getPointerType(nQT);
4577 // Add back the qualifiers.
4578 QT = Ctxt.getQualifiedType(QT, quals);
4579 return QT;
4580 }
4581
4582 // In case of Int_t& we need to strip the pointer first, ReSubst and attach
4583 // the reference once again.
4584 if (isa<ReferenceType>(QT.getTypePtr())) {
4585 // Get the qualifiers.
4586 bool isLValueRefTy = isa<LValueReferenceType>(QT.getTypePtr());
4587 Qualifiers quals = QT.getQualifiers();
4588 QualType nQT;
4589 nQT = ReSubstTemplateArg(QT->getPointeeType(),instance);
4590 if (nQT == QT->getPointeeType()) return QT;
4591
4592 // Add the r- or l-value reference type back to the desugared one.
4593 if (isLValueRefTy)
4594 QT = Ctxt.getLValueReferenceType(nQT);
4595 else
4596 QT = Ctxt.getRValueReferenceType(nQT);
4597 // Add back the qualifiers.
4598 QT = Ctxt.getQualifiedType(QT, quals);
4599 return QT;
4600 }
4601
4602 // In case of Int_t[2] we need to strip the array first, ReSubst and attach
4603 // the array once again.
4604 if (isa<clang::ArrayType>(QT.getTypePtr())) {
4605 // Get the qualifiers.
4606 Qualifiers quals = QT.getQualifiers();
4607
4608 if (const auto arr = dyn_cast<ConstantArrayType>(QT.getTypePtr())) {
4609 QualType newQT= ReSubstTemplateArg(arr->getElementType(),instance);
4610
4611 if (newQT == arr->getElementType()) return QT;
4612 QT = Ctxt.getConstantArrayType (newQT,
4613 arr->getSize(),
4614 arr->getSizeModifier(),
4615 arr->getIndexTypeCVRQualifiers());
4616
4617 } else if (const auto arr = dyn_cast<DependentSizedArrayType>(QT.getTypePtr())) {
4618 QualType newQT = ReSubstTemplateArg(arr->getElementType(),instance);
4619
4620 if (newQT == QT) return QT;
4621 QT = Ctxt.getDependentSizedArrayType (newQT,
4622 arr->getSizeExpr(),
4623 arr->getSizeModifier(),
4624 arr->getIndexTypeCVRQualifiers(),
4625 arr->getBracketsRange());
4626
4627 } else if (const auto arr = dyn_cast<IncompleteArrayType>(QT.getTypePtr())) {
4628 QualType newQT = ReSubstTemplateArg(arr->getElementType(),instance);
4629
4630 if (newQT == arr->getElementType()) return QT;
4631 QT = Ctxt.getIncompleteArrayType (newQT,
4632 arr->getSizeModifier(),
4633 arr->getIndexTypeCVRQualifiers());
4634
4635 } else if (const auto arr = dyn_cast<VariableArrayType>(QT.getTypePtr())) {
4636 QualType newQT = ReSubstTemplateArg(arr->getElementType(),instance);
4637
4638 if (newQT == arr->getElementType()) return QT;
4639 QT = Ctxt.getVariableArrayType (newQT,
4640 arr->getSizeExpr(),
4641 arr->getSizeModifier(),
4642 arr->getIndexTypeCVRQualifiers(),
4643 arr->getBracketsRange());
4644 }
4645
4646 // Add back the qualifiers.
4647 QT = Ctxt.getQualifiedType(QT, quals);
4648 return QT;
4649 }
4650
4651 // If the instance is also an elaborated type, we need to skip
4652 etype = llvm::dyn_cast<clang::ElaboratedType>(instance);
4653 if (etype) {
4654 instance = etype->getNamedType().getTypePtr();
4655 if (!instance) return input;
4656 }
4657
4658 const clang::TemplateSpecializationType* TST
4659 = llvm::dyn_cast<const clang::TemplateSpecializationType>(instance);
4660
4661 if (!TST) return input;
4662
4663 const clang::ClassTemplateSpecializationDecl* TSTdecl
4664 = llvm::dyn_cast_or_null<const clang::ClassTemplateSpecializationDecl>(instance->getAsCXXRecordDecl());
4665
4666 if (!TSTdecl) return input;
4667
4668 const clang::SubstTemplateTypeParmType *substType
4669 = llvm::dyn_cast<clang::SubstTemplateTypeParmType>(input.getTypePtr());
4670
4671 if (substType) {
4672 // Make sure it got replaced from this template
4673 const clang::ClassTemplateDecl *replacedCtxt = 0;
4674
4675 const clang::DeclContext *replacedDeclCtxt = substType->getReplacedParameter()->getDecl()->getDeclContext();
4676 const clang::CXXRecordDecl *decl = llvm::dyn_cast<clang::CXXRecordDecl>(replacedDeclCtxt);
4677 unsigned int index = substType->getReplacedParameter()->getIndex();
4678 if (decl) {
4679
4680 if (decl->getKind() == clang::Decl::ClassTemplatePartialSpecialization) {
4681 const clang::ClassTemplatePartialSpecializationDecl *spec = llvm::dyn_cast<clang::ClassTemplatePartialSpecializationDecl>(decl);
4682
4683 unsigned int depth = substType->getReplacedParameter()->getDepth();
4684
4685 const TemplateArgument *instanceArgs = spec->getTemplateArgs().data();
4686 unsigned int instanceNArgs = spec->getTemplateArgs().size();
4687
4688 // Search for the 'right' replacement.
4689
4690 for(unsigned int A = 0; A < instanceNArgs; ++A) {
4691 if (instanceArgs[A].getKind() == clang::TemplateArgument::Type) {
4692 clang::QualType argQualType = instanceArgs[A].getAsType();
4693
4694 const clang::TemplateTypeParmType *replacementType;
4695
4696 replacementType = llvm::dyn_cast<clang::TemplateTypeParmType>(argQualType);
4697
4698 if (!replacementType) {
4699 const clang::SubstTemplateTypeParmType *argType
4700 = llvm::dyn_cast<clang::SubstTemplateTypeParmType>(argQualType);
4701 if (argType) {
4702 clang::QualType replacementQT = argType->getReplacementType();
4703 replacementType = llvm::dyn_cast<clang::TemplateTypeParmType>(replacementQT);
4704 }
4705 }
4706 if (replacementType &&
4707 depth == replacementType->getDepth() &&
4708 index == replacementType->getIndex() )
4709 {
4710 index = A;
4711 break;
4712 }
4713 }
4714 }
4715 replacedCtxt = spec->getSpecializedTemplate();
4716 } else {
4717 replacedCtxt = decl->getDescribedClassTemplate();
4718 }
4719 } else if (auto const declguide = llvm::dyn_cast<clang::CXXDeductionGuideDecl>(replacedDeclCtxt)) {
4720 replacedCtxt = llvm::dyn_cast<clang::ClassTemplateDecl>(declguide->getDeducedTemplate());
4721 } else if (auto const ctdecl = llvm::dyn_cast<clang::ClassTemplateDecl>(replacedDeclCtxt)) {
4722 replacedCtxt = ctdecl;
4723 } else {
4724 std::string astDump;
4725 llvm::raw_string_ostream ostream(astDump);
4726 instance->dump(ostream);
4727 ostream.flush();
4728 ROOT::TMetaUtils::Warning("ReSubstTemplateArg","Unexpected type of declaration context for template parameter: %s.\n\tThe responsible class is:\n\t%s\n",
4729 replacedDeclCtxt->getDeclKindName(), astDump.c_str());
4730 replacedCtxt = nullptr;
4731 }
4732
4733 if ((replacedCtxt && replacedCtxt->getCanonicalDecl() == TSTdecl->getSpecializedTemplate()->getCanonicalDecl())
4734 || /* the following is likely just redundant */
4735 substType->getReplacedParameter()->getDecl()
4736 == TSTdecl->getSpecializedTemplate ()->getTemplateParameters()->getParam(index))
4737 {
4738 if ( index >= TST->getNumArgs() ) {
4739 // The argument replaced was a default template argument that is
4740 // being listed as part of the instance ...
4741 // so we probably don't really know how to spell it ... we would need to recreate it
4742 // (See AddDefaultParameters).
4743 return input;
4744 } else if (TST->getArg(index).getKind() == clang::TemplateArgument::Type) {
4745 return TST->getArg(index).getAsType();
4746 } else {
4747 // The argument is (likely) a value or expression and there is nothing for us
4748 // to change
4749 return input;
4750 }
4751 }
4752 }
4753 // Maybe a class template instance, recurse and rebuild
4754 const clang::TemplateSpecializationType* inputTST
4755 = llvm::dyn_cast<const clang::TemplateSpecializationType>(input.getTypePtr());
4756 const clang::ASTContext& astCtxt = TSTdecl->getASTContext();
4757
4758 if (inputTST) {
4759 bool mightHaveChanged = false;
4760 llvm::SmallVector<clang::TemplateArgument, 4> desArgs;
4761 for(clang::TemplateSpecializationType::iterator I = inputTST->begin(), E = inputTST->end();
4762 I != E; ++I) {
4763 if (I->getKind() != clang::TemplateArgument::Type) {
4764 desArgs.push_back(*I);
4765 continue;
4766 }
4767
4768 clang::QualType SubTy = I->getAsType();
4769 // Check if the type needs more desugaring and recurse.
4770 if (llvm::isa<clang::SubstTemplateTypeParmType>(SubTy)
4771 || llvm::isa<clang::TemplateSpecializationType>(SubTy)) {
4772 clang::QualType newSubTy = ReSubstTemplateArg(SubTy,instance);
4773 mightHaveChanged = SubTy != newSubTy;
4774 if (!newSubTy.isNull()) {
4775 desArgs.push_back(clang::TemplateArgument(newSubTy));
4776 }
4777 } else
4778 desArgs.push_back(*I);
4779 }
4780
4781 // If desugaring happened allocate new type in the AST.
4782 if (mightHaveChanged) {
4783 clang::Qualifiers qualifiers = input.getLocalQualifiers();
4784 input = astCtxt.getTemplateSpecializationType(inputTST->getTemplateName(),
4785 desArgs,
4786 inputTST->getCanonicalTypeInternal());
4787 input = astCtxt.getQualifiedType(input, qualifiers);
4788 }
4789 }
4790
4791 return input;
4792}
4793
4794////////////////////////////////////////////////////////////////////////////////
4795/// Remove the last n template arguments from the name
4796
4797int ROOT::TMetaUtils::RemoveTemplateArgsFromName(std::string& name, unsigned int nArgsToRemove)
4798{
4799 if ( nArgsToRemove == 0 || name == "")
4800 return 0;
4801
4802 // We proceed from the right to the left, counting commas which are not
4803 // enclosed by < >.
4804 const unsigned int length = name.length();
4805 unsigned int cur=0; // let's start beyond the first > from the right
4806 unsigned int nArgsRemoved=0;
4807 unsigned int nBraces=0;
4808 char c='@';
4809 while (nArgsRemoved!=nArgsToRemove && cur<length){
4810 c = name[cur];
4811 if (c == '<') nBraces++;
4812 if (c == '>') nBraces--;
4813 if (c == ',' && nBraces==1 /*So we are not in a sub-template*/) nArgsRemoved++;
4814 cur++;
4815 }
4816 cur--;
4817 name = name.substr(0,cur)+">";
4818 return 0;
4819
4820}
4821
4822////////////////////////////////////////////////////////////////////////////////
4823/// Converts STL container name to number. vector -> 1, etc..
4824
4826{
4827 static const char *stls[] = //container names
4828 {"any","vector","list", "deque","map","multimap","set","multiset","bitset",
4829 "forward_list","unordered_set","unordered_multiset","unordered_map","unordered_multimap", "RVec", 0};
4830 static const ROOT::ESTLType values[] =
4841 };
4842 // kind of stl container
4843 for(int k=1;stls[k];k++) {if (type.equals(stls[k])) return values[k];}
4844 return ROOT::kNotSTL;
4845}
4846
4847////////////////////////////////////////////////////////////////////////////////
4848
4849const clang::TypedefNameDecl *ROOT::TMetaUtils::GetAnnotatedRedeclarable(const clang::TypedefNameDecl *TND)
4850{
4851 if (!TND)
4852 return nullptr;
4853
4854 TND = TND->getMostRecentDecl();
4855 while (TND && !(TND->hasAttrs()))
4856 TND = TND->getPreviousDecl();
4857
4858 return TND;
4859}
4860
4861////////////////////////////////////////////////////////////////////////////////
4862
4863const clang::TagDecl *ROOT::TMetaUtils::GetAnnotatedRedeclarable(const clang::TagDecl *TD)
4864{
4865 if (!TD)
4866 return nullptr;
4867
4868 TD = TD->getMostRecentDecl();
4869 while (TD && !(TD->hasAttrs() && TD->isThisDeclarationADefinition()))
4870 TD = TD->getPreviousDecl();
4871
4872 return TD;
4873}
4874
4875////////////////////////////////////////////////////////////////////////////////
4876/// Extract the immediately outer namespace and then launch the recursion
4877
4879 std::list<std::pair<std::string,bool> >& enclosingNamespaces)
4880{
4881 const clang::DeclContext* enclosingNamespaceDeclCtxt = decl.getDeclContext();
4882 if (!enclosingNamespaceDeclCtxt) return;
4883
4884 const clang::NamespaceDecl* enclosingNamespace =
4885 clang::dyn_cast<clang::NamespaceDecl>(enclosingNamespaceDeclCtxt);
4886 if (!enclosingNamespace) return;
4887
4888 enclosingNamespaces.push_back(std::make_pair(enclosingNamespace->getNameAsString(),
4889 enclosingNamespace->isInline()));
4890
4891 ExtractCtxtEnclosingNameSpaces(*enclosingNamespace, enclosingNamespaces);
4892
4893}
4894
4895////////////////////////////////////////////////////////////////////////////////
4896/// Extract enclosing namespaces recursively
4897
4898void ROOT::TMetaUtils::ExtractCtxtEnclosingNameSpaces(const clang::DeclContext& ctxt,
4899 std::list<std::pair<std::string,bool> >& enclosingNamespaces)
4900{
4901 const clang::DeclContext* enclosingNamespaceDeclCtxt = ctxt.getParent ();
4902
4903 // If no parent is found, nothing more to be done
4904 if (!enclosingNamespaceDeclCtxt) {
4905 return;
4906 }
4907
4908 // Check if the parent is a namespace (it could be a class for example)
4909 // if not, nothing to be done here
4910 const clang::NamespaceDecl* enclosingNamespace = clang::dyn_cast<clang::NamespaceDecl>(enclosingNamespaceDeclCtxt);
4911 if (!enclosingNamespace) return;
4912
4913 // Add to the list of parent namespaces
4914 enclosingNamespaces.push_back(std::make_pair(enclosingNamespace->getNameAsString(),
4915 enclosingNamespace->isInline()));
4916
4917 // here the recursion
4918 ExtractEnclosingNameSpaces(*enclosingNamespace, enclosingNamespaces);
4919}
4920
4921////////////////////////////////////////////////////////////////////////////////
4922/// Extract the names and types of containing scopes.
4923/// Stop if a class is met and return its pointer.
4924
4925const clang::RecordDecl *ROOT::TMetaUtils::ExtractEnclosingScopes(const clang::Decl& decl,
4926 std::list<std::pair<std::string,unsigned int> >& enclosingSc)
4927{
4928 const clang::DeclContext* enclosingDeclCtxt = decl.getDeclContext();
4929 if (!enclosingDeclCtxt) return nullptr;
4930
4931 unsigned int scopeType;
4932
4933 if (auto enclosingNamespacePtr =
4934 clang::dyn_cast<clang::NamespaceDecl>(enclosingDeclCtxt)){
4935 scopeType= enclosingNamespacePtr->isInline() ? 1 : 0; // inline or simple namespace
4936 enclosingSc.push_back(std::make_pair(enclosingNamespacePtr->getNameAsString(),scopeType));
4937 return ExtractEnclosingScopes(*enclosingNamespacePtr, enclosingSc);
4938 }
4939
4940 if (auto enclosingClassPtr =
4941 clang::dyn_cast<clang::RecordDecl>(enclosingDeclCtxt)){
4942 return enclosingClassPtr;
4943 }
4944
4945 return nullptr;
4946}
4947
4948////////////////////////////////////////////////////////////////////////////////
4949/// Reimplementation of TSystem::ExpandPathName() that cannot be
4950/// used from TMetaUtils.
4951
4952static void replaceEnvVars(const char* varname, std::string& txt)
4953{
4954 std::string::size_type beginVar = 0;
4955 std::string::size_type endVar = 0;
4956 while ((beginVar = txt.find('$', beginVar)) != std::string::npos
4957 && beginVar + 1 < txt.length()) {
4958 std::string::size_type beginVarName = beginVar + 1;
4959 std::string::size_type endVarName = std::string::npos;
4960 if (txt[beginVarName] == '(') {
4961 // "$(VARNAME)" style.
4962 endVarName = txt.find(')', beginVarName);
4963 ++beginVarName;
4964 if (endVarName == std::string::npos) {
4965 ROOT::TMetaUtils::Error(0, "Missing ')' for '$(' in $%s at %s\n",
4966 varname, txt.c_str() + beginVar);
4967 return;
4968 }
4969 endVar = endVarName + 1;
4970 } else {
4971 // "$VARNAME/..." style.
4972 beginVarName = beginVar + 1;
4973 endVarName = beginVarName;
4974 while (isalnum(txt[endVarName]) || txt[endVarName] == '_')
4975 ++endVarName;
4976 endVar = endVarName;
4977 }
4978
4979 const char* val = getenv(txt.substr(beginVarName,
4980 endVarName - beginVarName).c_str());
4981 if (!val) val = "";
4982
4983 txt.replace(beginVar, endVar - beginVar, val);
4984 int lenval = strlen(val);
4985 int delta = lenval - (endVar - beginVar); // these many extra chars,
4986 endVar += delta; // advance the end marker accordingly.
4987
4988 // Look for the next one
4989 beginVar = endVar + 1;
4990 }
4991}
4992
4993////////////////////////////////////////////////////////////////////////////////
4994/// Organise the parameters for cling in order to guarantee relocatability
4995/// It treats the gcc toolchain and the root include path
4996/// FIXME: enables relocatability for experiments' framework headers until PCMs
4997/// are available.
4998
4999void ROOT::TMetaUtils::SetPathsForRelocatability(std::vector<std::string>& clingArgs )
5000{
5001 const char* envInclPath = getenv("ROOT_INCLUDE_PATH");
5002
5003 if (!envInclPath)
5004 return;
5005 std::istringstream envInclPathsStream(envInclPath);
5006 std::string inclPath;
5007 while (std::getline(envInclPathsStream, inclPath, ':')) {
5008 // Can't use TSystem in here; re-implement TSystem::ExpandPathName().
5009 replaceEnvVars("ROOT_INCLUDE_PATH", inclPath);
5010 if (!inclPath.empty()) {
5011 clingArgs.push_back("-I");
5012 clingArgs.push_back(inclPath);
5013 }
5014 }
5015}
5016
5017////////////////////////////////////////////////////////////////////////////////
5018
5019void ROOT::TMetaUtils::ReplaceAll(std::string& str, const std::string& from, const std::string& to,bool recurse)
5020{
5021 if(from.empty())
5022 return;
5023 size_t start_pos = 0;
5024 bool changed=true;
5025 while (changed){
5026 changed=false;
5027 start_pos = 0;
5028 while((start_pos = str.find(from, start_pos)) != std::string::npos) {
5029 str.replace(start_pos, from.length(), to);
5030 start_pos += to.length();
5031 if (recurse) changed = true;
5032 }
5033 }
5034}
5035
5036////////////////////////////////////////////////////////////////////////////////
5037/// Return the separator suitable for this platform.
5039{
5041}
5042
5043////////////////////////////////////////////////////////////////////////////////
5044
5045bool ROOT::TMetaUtils::EndsWith(const std::string &theString, const std::string &theSubstring)
5046{
5047 if (theString.size() < theSubstring.size()) return false;
5048 const unsigned int theSubstringSize = theSubstring.size();
5049 return 0 == theString.compare(theString.size() - theSubstringSize,
5050 theSubstringSize,
5051 theSubstring);
5052}
5053
5054////////////////////////////////////////////////////////////////////////////////
5055
5056bool ROOT::TMetaUtils::BeginsWith(const std::string &theString, const std::string &theSubstring)
5057{
5058 if (theString.size() < theSubstring.size()) return false;
5059 const unsigned int theSubstringSize = theSubstring.size();
5060 return 0 == theString.compare(0,
5061 theSubstringSize,
5062 theSubstring);
5063}
5064
5065
5066
5067////////////////////////////////////////////////////////////////////////////////
5068
5070{
5071 // Note, should change this into take llvm::StringRef.
5072
5073 if ((strstr(filename, "LinkDef") || strstr(filename, "Linkdef") ||
5074 strstr(filename, "linkdef")) && strstr(filename, ".h")) {
5075 return true;
5076 }
5077 size_t len = strlen(filename);
5078 size_t linkdeflen = 9; /* strlen("linkdef.h") */
5079 if (len >= 9) {
5080 if (0 == strncasecmp(filename + (len - linkdeflen), "linkdef", linkdeflen - 2)
5081 && 0 == strcmp(filename + (len - 2), ".h")
5082 ) {
5083 return true;
5084 } else {
5085 return false;
5086 }
5087 } else {
5088 return false;
5089 }
5090}
5091
5092////////////////////////////////////////////////////////////////////////////////
5093
5095{
5096 return llvm::sys::path::extension(filename) == ".h" ||
5104}
5105
5106////////////////////////////////////////////////////////////////////////////////
5107
5108const std::string ROOT::TMetaUtils::AST2SourceTools::Decls2FwdDecls(const std::vector<const clang::Decl *> &decls,
5109 cling::Interpreter::IgnoreFilesFunc_t ignoreFiles,
5110 const cling::Interpreter &interp,
5111 std::string *logs)
5112{
5113 clang::Sema &sema = interp.getSema();
5114 cling::Transaction theTransaction(sema);
5115 std::set<clang::Decl *> addedDecls;
5116 for (auto decl : decls) {
5117 // again waiting for cling
5118 clang::Decl *ncDecl = const_cast<clang::Decl *>(decl);
5119 theTransaction.append(ncDecl);
5120 }
5121 std::string newFwdDecl;
5122 llvm::raw_string_ostream llvmOstr(newFwdDecl);
5123
5124 std::string locallogs;
5125 llvm::raw_string_ostream llvmLogStr(locallogs);
5126 interp.forwardDeclare(theTransaction, sema.getPreprocessor(), sema.getASTContext(), llvmOstr, true,
5127 logs ? &llvmLogStr : nullptr, ignoreFiles);
5128 llvmOstr.flush();
5129 llvmLogStr.flush();
5130 if (logs)
5131 logs->swap(locallogs);
5132 return newFwdDecl;
5133}
5134
5135////////////////////////////////////////////////////////////////////////////////
5136/// Take the namespaces which enclose the decl and put them around the
5137/// definition string.
5138/// For example, if the definition string is "myClass" which is enclosed by
5139/// the namespaces ns1 and ns2, one would get:
5140/// namespace ns2{ namespace ns1 { class myClass; } }
5141
5143 std::string& defString)
5144{
5145 auto rcd = EncloseInScopes(decl, defString);
5146 return rcd ? 1:0;
5147}
5148
5149////////////////////////////////////////////////////////////////////////////////
5150/// Take the scopes which enclose the decl and put them around the
5151/// definition string.
5152/// If a class is encountered, bail out.
5153
5154const clang::RecordDecl* ROOT::TMetaUtils::AST2SourceTools::EncloseInScopes(const clang::Decl& decl,
5155 std::string& defString)
5156{
5157 std::list<std::pair<std::string,unsigned int> > enclosingNamespaces;
5158 auto rcdPtr = ROOT::TMetaUtils::ExtractEnclosingScopes(decl,enclosingNamespaces);
5159
5160 if (rcdPtr) return rcdPtr;
5161
5162 // Check if we have enclosing namespaces
5163 static const std::string scopeType [] = {"namespace ", "inline namespace ", "class "};
5164
5165 std::string scopeName;
5166 std::string scopeContent;
5167 unsigned int scopeIndex;
5168 for (auto const & encScope : enclosingNamespaces){
5169 scopeIndex = encScope.second;
5170 scopeName = encScope.first;
5171 scopeContent = " { " + defString + " }";
5172 defString = scopeType[scopeIndex] +
5173 scopeName +
5174 scopeContent;
5175 }
5176 return nullptr;
5177}
5178
5179////////////////////////////////////////////////////////////////////////////////
5180/// Loop over the template parameters and build a string for template arguments
5181/// using the fully qualified name
5182/// There are different cases:
5183/// Case 1: a simple template parameter
5184/// E.g. `template<typename T> class A;`
5185/// Case 2: a non-type: either an integer or an enum
5186/// E.g. `template<int I, Foo > class A;` where `Foo` is `enum Foo {red, blue};`
5187/// 2 sub cases here:
5188/// SubCase 2.a: the parameter is an enum: bail out, cannot be treated.
5189/// SubCase 2.b: use the fully qualified name
5190/// Case 3: a TemplateTemplate argument
5191/// E.g. `template <template <typename> class T> class container { };`
5192
5194 const clang::TemplateParameterList& tmplParamList,
5195 const cling::Interpreter& interpreter)
5196{
5197 templateArgs="<";
5198 for (auto prmIt = tmplParamList.begin();
5199 prmIt != tmplParamList.end(); prmIt++){
5200
5201 if (prmIt != tmplParamList.begin())
5202 templateArgs += ", ";
5203
5204 auto nDecl = *prmIt;
5205 std::string typeName;
5206
5207 // Case 1
5208 if (llvm::isa<clang::TemplateTypeParmDecl>(nDecl)){
5209 typeName = "typename ";
5210 if (nDecl->isParameterPack())
5211 typeName += "... ";
5212 typeName += (*prmIt)->getNameAsString();
5213 }
5214 // Case 2
5215 else if (auto nttpd = llvm::dyn_cast<clang::NonTypeTemplateParmDecl>(nDecl)){
5216 auto theType = nttpd->getType();
5217 // If this is an enum, use int as it is impossible to fwd declare and
5218 // this makes sense since it is not a type...
5219 if (theType.getAsString().find("enum") != std::string::npos){
5220 std::string astDump;
5221 llvm::raw_string_ostream ostream(astDump);
5222 nttpd->dump(ostream);
5223 ostream.flush();
5224 ROOT::TMetaUtils::Warning(0,"Forward declarations of templates with enums as template parameters. The responsible class is: %s\n", astDump.c_str());
5225 return 1;
5226 } else {
5228 theType,
5229 interpreter);
5230 }
5231 }
5232 // Case 3: TemplateTemplate argument
5233 else if (auto ttpd = llvm::dyn_cast<clang::TemplateTemplateParmDecl>(nDecl)){
5234 int retCode = FwdDeclFromTmplDecl(*ttpd,interpreter,typeName);
5235 if (retCode!=0){
5236 std::string astDump;
5237 llvm::raw_string_ostream ostream(astDump);
5238 ttpd->dump(ostream);
5239 ostream.flush();
5240 ROOT::TMetaUtils::Error(0,"Cannot reconstruct template template parameter forward declaration for %s\n", astDump.c_str());
5241 return 1;
5242 }
5243 }
5244
5245 templateArgs += typeName;
5246 }
5247
5248 templateArgs+=">";
5249 return 0;
5250}
5251
5252////////////////////////////////////////////////////////////////////////////////
5253/// Convert a tmplt decl to its fwd decl
5254
5255int ROOT::TMetaUtils::AST2SourceTools::FwdDeclFromTmplDecl(const clang::TemplateDecl& templDecl,
5256 const cling::Interpreter& interpreter,
5257 std::string& defString)
5258{
5259 std::string templatePrefixString;
5260 auto tmplParamList= templDecl.getTemplateParameters();
5261 if (!tmplParamList){ // Should never happen
5262 Error(0,
5263 "Cannot extract template parameter list for %s",
5264 templDecl.getNameAsString().c_str());
5265 return 1;
5266 }
5267
5268 int retCode = PrepareArgsForFwdDecl(templatePrefixString,*tmplParamList,interpreter);
5269 if (retCode!=0){
5270 Warning(0,
5271 "Problems with arguments for forward declaration of class %s\n",
5272 templDecl.getNameAsString().c_str());
5273 return retCode;
5274 }
5275 templatePrefixString = "template " + templatePrefixString + " ";
5276
5277 defString = templatePrefixString + "class ";
5278 if (templDecl.isParameterPack())
5279 defString += "... ";
5280 defString += templDecl.getNameAsString();
5281 if (llvm::isa<clang::TemplateTemplateParmDecl>(&templDecl)) {
5282 // When fwd declaring the template template arg of
5283 // namespace N { template <template <class T> class C> class X; }
5284 // we don't need to put it into any namespace, and we want no trailing
5285 // ';'
5286 return 0;
5287 }
5288 defString += ';';
5289 return EncloseInNamespaces(templDecl, defString);
5290}
5291
5292////////////////////////////////////////////////////////////////////////////////
5293
5294static int TreatSingleTemplateArg(const clang::TemplateArgument& arg,
5295 std::string& argFwdDecl,
5296 const cling::Interpreter& interpreter,
5297 bool acceptStl=false)
5298{
5299 using namespace ROOT::TMetaUtils::AST2SourceTools;
5300
5301 // We do nothing in presence of ints, bools, templates.
5302 // We should probably in presence of templates though...
5303 if (clang::TemplateArgument::Type != arg.getKind()) return 0;
5304
5305 auto argQualType = arg.getAsType();
5306
5307 // Recursively remove all *
5308 while (llvm::isa<clang::PointerType>(argQualType.getTypePtr())) argQualType = argQualType->getPointeeType();
5309
5310 auto argTypePtr = argQualType.getTypePtr();
5311
5312 // Bail out on enums
5313 if (llvm::isa<clang::EnumType>(argTypePtr)){
5314 return 1;
5315 }
5316
5317 // If this is a built-in, just return: fwd decl not necessary.
5318 if (llvm::isa<clang::BuiltinType>(argTypePtr)){
5319 return 0;
5320 }
5321
5322 // Treat typedefs which are arguments
5323 if (auto tdTypePtr = llvm::dyn_cast<clang::TypedefType>(argTypePtr)) {
5324 FwdDeclFromTypeDefNameDecl(*tdTypePtr->getDecl(), interpreter, argFwdDecl);
5325 return 0;
5326 }
5327
5328 if (auto argRecTypePtr = llvm::dyn_cast<clang::RecordType>(argTypePtr)){
5329 // Now we cannot but have a RecordType
5330 if (auto argRecDeclPtr = argRecTypePtr->getDecl()){
5331 FwdDeclFromRcdDecl(*argRecDeclPtr,interpreter,argFwdDecl,acceptStl);
5332 }
5333 return 0;
5334 }
5335
5336 return 1;
5337}
5338
5339////////////////////////////////////////////////////////////////////////////////
5340/// Convert a tmplt decl to its fwd decl
5341
5342int ROOT::TMetaUtils::AST2SourceTools::FwdDeclIfTmplSpec(const clang::RecordDecl& recordDecl,
5343 const cling::Interpreter& interpreter,
5344 std::string& defString,
5345 const std::string &normalizedName)
5346{
5347 // If this is an explicit specialization, inject it into cling, too, such that it can have
5348 // externalLexicalStorage, see TCling.cxx's ExtVisibleStorageAdder::VisitClassTemplateSpecializationDecl.
5349 if (auto tmplSpecDeclPtr = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(&recordDecl)) {
5350 if (const auto *specDef = tmplSpecDeclPtr->getDefinition()) {
5351 if (specDef->getTemplateSpecializationKind() != clang::TSK_ExplicitSpecialization)
5352 return 0;
5353 // normalizedName contains scope, no need to enclose in namespace!
5355 std::cout << " Forward declaring template spec " << normalizedName << ":\n";
5356 for (auto arg : tmplSpecDeclPtr->getTemplateArgs().asArray()) {
5357 std::string argFwdDecl;
5358 int retCode = TreatSingleTemplateArg(arg, argFwdDecl, interpreter, /*acceptStl=*/false);
5360 std::cout << " o Template argument ";
5361 if (retCode == 0) {
5362 std::cout << "successfully treated. Arg fwd decl: " << argFwdDecl << std::endl;
5363 } else {
5364 std::cout << "could not be treated. Abort fwd declaration generation.\n";
5365 }
5366 }
5367
5368 if (retCode != 0) { // A sign we must bail out
5369 return retCode;
5370 }
5371 defString += argFwdDecl + '\n';
5372 }
5373 defString += "template <> class " + normalizedName + ';';
5374 return 0;
5375 }
5376 }
5377
5378 return 0;
5379}
5380
5381////////////////////////////////////////////////////////////////////////////////
5382/// Convert a rcd decl to its fwd decl
5383/// If this is a template specialisation, treat in the proper way.
5384/// If it is contained in a class, just fwd declare the class.
5385
5386int ROOT::TMetaUtils::AST2SourceTools::FwdDeclFromRcdDecl(const clang::RecordDecl& recordDecl,
5387 const cling::Interpreter& interpreter,
5388 std::string& defString,
5389 bool acceptStl)
5390{
5391 // Do not fwd declare the templates in the stl.
5392 if (ROOT::TMetaUtils::IsStdClass(recordDecl) && !acceptStl)
5393 return 0;
5394
5395 // Do not fwd declare unnamed decls.
5396 if (!recordDecl.getIdentifier())
5397 return 0;
5398
5399 // We may need to fwd declare the arguments of the template
5400 std::string argsFwdDecl;
5401
5402 if (auto tmplSpecDeclPtr = llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(&recordDecl)){
5403 std::string argFwdDecl;
5405 std::cout << "Class " << recordDecl.getNameAsString()
5406 << " is a template specialisation. Treating its arguments.\n";
5407 for(auto arg : tmplSpecDeclPtr->getTemplateArgs().asArray()){
5408 int retCode = TreatSingleTemplateArg(arg, argFwdDecl, interpreter, acceptStl);
5410 std::cout << " o Template argument ";
5411 if (retCode==0){
5412 std::cout << "successfully treated. Arg fwd decl: " << argFwdDecl << std::endl;
5413 } else {
5414 std::cout << "could not be treated. Abort fwd declaration generation.\n";
5415 }
5416 }
5417
5418 if (retCode!=0){ // A sign we must bail out
5419 return retCode;
5420 }
5421 argsFwdDecl+=argFwdDecl;
5422 }
5423
5424 if (acceptStl){
5425 defString=argsFwdDecl;
5426 return 0;
5427 }
5428
5429 int retCode=0;
5430 if (auto tmplDeclPtr = tmplSpecDeclPtr->getSpecializedTemplate()){
5431 retCode = FwdDeclFromTmplDecl(*tmplDeclPtr,interpreter,defString);
5432 }
5433 defString = argsFwdDecl + "\n" + defString;
5434 return retCode;
5435
5436 }
5437
5438 defString = "class " + recordDecl.getNameAsString() + ";";
5439 const clang::RecordDecl* rcd = EncloseInScopes(recordDecl, defString);
5440
5441 if (rcd){
5442 FwdDeclFromRcdDecl(*rcd, interpreter,defString);
5443 }
5444 // Add a \n here to avoid long lines which contain duplications, for example (from MathCore):
5445 // namespace ROOT { namespace Math { class IBaseFunctionMultiDim; } }namespace ROOT { namespace Fit { template <typename FunType> class Chi2FCN; } }
5446 // namespace ROOT { namespace Math { class IGradientFunctionMultiDim; } }namespace ROOT { namespace Fit { template <typename FunType> class Chi2FCN; } }
5447 defString = argsFwdDecl + "\n" + defString;
5448
5449 return 0;
5450}
5451
5452////////////////////////////////////////////////////////////////////////////////
5453/// Extract "forward declaration" of a typedef.
5454/// If the typedef is contained in a class, just fwd declare the class.
5455/// If not, fwd declare the typedef and all the dependent typedefs and types if necessary.
5456
5458 const cling::Interpreter& interpreter,
5459 std::string& fwdDeclString,
5460 std::unordered_set<std::string>* fwdDeclSetPtr)
5461{
5462 std::string buffer = tdnDecl.getNameAsString();
5463 std::string underlyingName;
5464 auto underlyingType = tdnDecl.getUnderlyingType().getCanonicalType();
5465 if (const clang::TagType* TT
5466 = llvm::dyn_cast<clang::TagType>(underlyingType.getTypePtr())) {
5467 if (clang::NamedDecl* ND = TT->getDecl()) {
5468 if (!ND->getIdentifier()) {
5469 // No fwd decl for unnamed underlying entities.
5470 return 0;
5471 }
5472 }
5473 }
5474
5475 TNormalizedCtxt nCtxt(interpreter.getLookupHelper());
5477 underlyingType,
5478 interpreter,
5479 nCtxt);
5480
5481 // Heuristic: avoid entities like myclass<myType1, myType2::xyz>
5482 if (underlyingName.find(">::") != std::string::npos)
5483 return 0;
5484
5485 buffer="typedef "+underlyingName+" "+buffer+";";
5486 const clang::RecordDecl* rcd=EncloseInScopes(tdnDecl,buffer);
5487 if (rcd) {
5488 // We do not need the whole series of scopes, just the class.
5489 // It is enough to trigger an uncomplete type autoload/parse callback
5490 // for example: MyClass::blabla::otherNs::myTypedef
5491 return FwdDeclFromRcdDecl(*rcd, interpreter,fwdDeclString,fwdDeclSetPtr);
5492 }
5493
5494 // Start Recursion if the underlying type is a TypedefNameDecl
5495 // Note: the simple cast w/o the getSingleStepDesugaredType call
5496 // does not work in case the typedef is in a namespace.
5497 auto& ctxt = tdnDecl.getASTContext();
5498 auto immediatelyUnderlyingType = underlyingType.getSingleStepDesugaredType(ctxt);
5499
5500 if (auto underlyingTdnTypePtr = llvm::dyn_cast<clang::TypedefType>(immediatelyUnderlyingType.getTypePtr())){
5501 std::string tdnFwdDecl;
5502 auto underlyingTdnDeclPtr = underlyingTdnTypePtr->getDecl();
5503 FwdDeclFromTypeDefNameDecl(*underlyingTdnDeclPtr,
5504 interpreter,
5505 tdnFwdDecl,
5506 fwdDeclSetPtr);
5507 if (!fwdDeclSetPtr || fwdDeclSetPtr->insert(tdnFwdDecl).second)
5508 fwdDeclString+=tdnFwdDecl;
5509 } else if (auto CXXRcdDeclPtr = immediatelyUnderlyingType->getAsCXXRecordDecl()){
5510 std::string classFwdDecl;
5512 std::cout << "Typedef " << tdnDecl.getNameAsString() << " hides a class: "
5513 << CXXRcdDeclPtr->getNameAsString() << std::endl;
5514 int retCode = FwdDeclFromRcdDecl(*CXXRcdDeclPtr,
5515 interpreter,
5516 classFwdDecl,
5517 true /* acceptStl*/);
5518 if (retCode!=0){ // bail out
5519 return 0;
5520 }
5521
5522 if (!fwdDeclSetPtr || fwdDeclSetPtr->insert(classFwdDecl).second)
5523 fwdDeclString+=classFwdDecl;
5524 }
5525
5526 fwdDeclString+=buffer;
5527
5528 return 0;
5529}
5530
5531////////////////////////////////////////////////////////////////////////////////
5532/// Get the default value as string.
5533/// Limited at the moment to:
5534/// - Integers
5535/// - Booleans
5536
5537int ROOT::TMetaUtils::AST2SourceTools::GetDefArg(const clang::ParmVarDecl& par,