Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TClassEdit.cxx
Go to the documentation of this file.
1// @(#)root/metautils:$Id$
2/// \file TClassEdit.cxx
3/// \ingroup Base
4/// \author Victor Perev
5/// \author Philippe Canal
6/// \date 04/10/2003
7
8/*************************************************************************
9 * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *
10 * All rights reserved. *
11 * *
12 * For the licensing terms see $ROOTSYS/LICENSE. *
13 * For the list of contributors see $ROOTSYS/README/CREDITS. *
14 *************************************************************************/
15
16#include <cstdio>
17#include <cstdlib>
18#include <cassert>
19#include <cstring>
20#include "TClassEdit.h"
21#include <cctype>
22#include "Rstrstream.h"
23#include <set>
24#include <stack>
25// for shared_ptr
26#include <memory>
27#include "ROOT/RStringView.hxx"
28#include <algorithm>
29
30#include "TSpinLockGuard.h"
31
32using namespace std;
33
34namespace {
35 static TClassEdit::TInterpreterLookupHelper *gInterpreterHelper = nullptr;
36
37 template <typename T>
38 struct ShuttingDownSignaler : public T {
39 using T::T;
40
41 ShuttingDownSignaler() = default;
42 ShuttingDownSignaler(T &&in) : T(std::move(in)) {}
43
44 ~ShuttingDownSignaler()
45 {
46 if (gInterpreterHelper)
47 gInterpreterHelper->ShuttingDownSignal();
48 }
49 };
50}
51
52////////////////////////////////////////////////////////////////////////////////
53/// Return the length, if any, taken by std:: and any
54/// potential inline namespace (well compiler detail namespace).
55
56static size_t StdLen(const std::string_view name)
57{
58 size_t len = 0;
59 if (name.compare(0,5,"std::")==0) {
60 len = 5;
61
62 // TODO: This is likely to induce unwanted autoparsing, those are reduced
63 // by the caching of the result.
64 if (gInterpreterHelper) {
65 for(size_t i = 5; i < name.length(); ++i) {
66 if (name[i] == '<') break;
67 if (name[i] == ':') {
68 std::string scope(name.data(),i);
69
70 // We assume that we are called in already serialized code.
71 // Note: should we also cache the negative answers?
72 static ShuttingDownSignaler<std::set<std::string>> gInlined;
73 static std::atomic_flag spinFlag = ATOMIC_FLAG_INIT;
74
75 bool isInlined;
76 {
77 ROOT::Internal::TSpinLockGuard lock(spinFlag);
78 isInlined = (gInlined.find(scope) != gInlined.end());
79 }
80
81 if (isInlined) {
82 len = i;
83 if (i+1<name.length() && name[i+1]==':') {
84 len += 2;
85 }
86 } else {
87 std::string scoperesult;
88 if (!gInterpreterHelper->ExistingTypeCheck(scope, scoperesult)
89 && gInterpreterHelper->IsDeclaredScope(scope, isInlined))
90 {
91 if (isInlined) {
92 {
93 ROOT::Internal::TSpinLockGuard lock(spinFlag);
94 gInlined.insert(scope);
95 }
96 len = i;
97 if (i+1<name.length() && name[i+1]==':') {
98 len += 2;
99 }
100 }
101 }
102 }
103 }
104 }
105 }
106 }
107
108 return len;
109}
110
111////////////////////////////////////////////////////////////////////////////////
112/// Remove std:: and any potential inline namespace (well compiler detail
113/// namespace.
114
115static void RemoveStd(std::string &name, size_t pos = 0)
116{
117 size_t len = StdLen({name.data()+pos,name.length()-pos});
118 if (len) {
119 name.erase(pos,len);
120 }
121}
122
123////////////////////////////////////////////////////////////////////////////////
124/// Remove std:: and any potential inline namespace (well compiler detail
125/// namespace.
126
127static void RemoveStd(std::string_view &name)
128{
129 size_t len = StdLen(name);
130 if (len) {
131 name.remove_prefix(len);
132 }
133}
134
135////////////////////////////////////////////////////////////////////////////////
136
138{
139 if (0 == strncmp(clName, "complex<", 8)) {
140 const char *clNamePlus8 = clName + 8;
141 if (0 == strcmp("float>", clNamePlus8)) {
142 return EComplexType::kFloat;
143 }
144 if (0 == strcmp("double>", clNamePlus8)) {
145 return EComplexType::kDouble;
146 }
147 if (0 == strcmp("int>", clNamePlus8)) {
148 return EComplexType::kInt;
149 }
150 if (0 == strcmp("long>", clNamePlus8)) {
151 return EComplexType::kLong;
152 }
153 }
154 return EComplexType::kNone;
155}
156
157////////////////////////////////////////////////////////////////////////////////
159{
160 // Already too late to call this->ShuttingDownSignal
161 // the virtual table has already lost (on some platform) the
162 // address of the derived function that we would need to call.
163 // But at least forget about this instance!
164
165 if (this == gInterpreterHelper)
166 gInterpreterHelper = nullptr;
167}
168
169////////////////////////////////////////////////////////////////////////////////
170
172{
173 gInterpreterHelper = helper;
174}
175
176////////////////////////////////////////////////////////////////////////////////
177/// default constructor
178
179TClassEdit::TSplitType::TSplitType(const char *type2split, EModType mode) : fName(type2split), fNestedLocation(0)
180{
182}
183
184////////////////////////////////////////////////////////////////////////////////
185/// type : type name: vector<list<classA,allocator>,allocator>[::iterator]
186/// result: 0 : not stl container and not declared inside an stl container.
187/// result: code of container that the type or is the scope of the type
188
190{
191 if (fElements[0].empty()) return ROOT::kNotSTL;
192 return STLKind(fElements[0]);
193}
194
195////////////////////////////////////////////////////////////////////////////////
196/// type : type name: vector<list<classA,allocator>,allocator>
197/// testAlloc: if true, we test allocator, if it is not default result is negative
198/// result: 0 : not stl container
199/// abs(result): code of container 1=vector,2=list,3=deque,4=map
200/// 5=multimap,6=set,7=multiset
201/// positive val: we have a vector or list with default allocator to any depth
202/// like vector<list<vector<int>>>
203/// negative val: STL container other than vector or list, or non default allocator
204/// For example: vector<deque<int>> has answer -1
205
206int TClassEdit::TSplitType::IsSTLCont(int testAlloc) const
207{
208
209 if (fElements[0].empty()) return 0;
210 int numb = fElements.size();
211 if (!fElements[numb-1].empty() && fElements[numb-1][0]=='*') --numb;
212
213 if ( fNestedLocation ) {
214 // The type has been defined inside another namespace and/or class
215 // this couldn't possibly be an STL container
216 return 0;
217 }
218
219 int kind = STLKind(fElements[0]);
220
221 if (kind==ROOT::kSTLvector || kind==ROOT::kSTLlist || kind==ROOT::kSTLforwardlist) {
222
223 int nargs = STLArgs(kind);
224 if (testAlloc && (numb-1 > nargs) && !IsDefAlloc(fElements[numb-1].c_str(),fElements[1].c_str())) {
225
226 // We have a non default allocator,
227 // let's return a negative value.
228
229 kind = -kind;
230
231 } else {
232
233 // We has a default allocator, let's continue to
234 // look inside the argument list.
235 int k = TClassEdit::IsSTLCont(fElements[1].c_str(),testAlloc);
236 if (k<0) kind = -kind;
237
238 }
239 }
240
241 // We return a negative value for anything which is not a vector or a list.
242 if(kind>2) kind = - kind;
243 return kind;
244}
245
246////////////////////////////////////////////////////////////////////////////////
247//////////////////////////////////////////////////////////////////////////////
248/// Return the absolute type of typeDesc into the string answ.
249
250void TClassEdit::TSplitType::ShortType(std::string &answ, int mode)
251{
252 // E.g.: typeDesc = "class const volatile TNamed**", returns "TNamed**".
253 // if (mode&1) remove last "*"s returns "TNamed"
254 // if (mode&2) remove default allocators from STL containers
255 // if (mode&4) remove all allocators from STL containers
256 // if (mode&8) return inner class of stl container. list<innerClass>
257 // if (mode&16) return deepest class of stl container. vector<list<deepest>>
258 // if (mode&kDropAllDefault) remove default template arguments
259 /////////////////////////////////////////////////////////////////////////////
260
261 answ.clear();
262 int narg = fElements.size();
263 int tailLoc = 0;
264
265 if (narg == 0) {
266 answ = fName;
267 return ;
268 }
269 // fprintf(stderr,"calling ShortType %d for %s with narg %d\n",mode,typeDesc,narg);
270 // {for (int i=0;i<narg;i++) fprintf(stderr,"calling ShortType %d for %s with %d %s \n",
271 // mode,typeDesc,i,arglist[i].c_str());
272 // }
273 if (fElements[narg-1].empty() == false &&
274 (fElements[narg-1][0]=='*'
275 || fElements[narg-1][0]=='&'
276 || fElements[narg-1][0]=='['
277 || 0 == fElements[narg-1].compare(0,6,"const*")
278 || 0 == fElements[narg-1].compare(0,6,"const&")
279 || 0 == fElements[narg-1].compare(0,6,"const[")
280 || 0 == fElements[narg-1].compare("const")
281 )
282 ) {
283 if ((mode&1)==0) tailLoc = narg-1;
284 }
285 else { assert(fElements[narg-1].empty()); };
286 narg--;
287 mode &= (~1);
288
289 if (fNestedLocation) narg--;
290
291 // fprintf(stderr,"calling ShortType %d for %s with narg %d tail %d\n",imode,typeDesc,narg,tailLoc);
292
293 //kind of stl container
294 const int kind = STLKind(fElements[0]);
295 const int iall = STLArgs(kind);
296
297 // Only class is needed
298 if (mode&(8|16)) {
299 while(narg-1>iall) { fElements.pop_back(); narg--;}
300 if (!fElements[0].empty() && tailLoc) {
301 tailLoc = 0;
302 }
303 fElements[0].clear();
304 mode&=(~8);
305 }
306
307 if (mode & kDropAllDefault) mode |= kDropStlDefault;
308 if (mode & kDropStlDefault) mode |= kDropDefaultAlloc;
309
310 if (kind) {
311 bool allocRemoved = false;
312
313 if ( mode & (kDropDefaultAlloc|kDropAlloc) ) {
314 // remove allocators
315
316
317 if (narg-1 == iall+1) {
318 // has an allocator specified
319 bool dropAlloc = false;
320 if (mode & kDropAlloc) {
321
322 dropAlloc = true;
323
324 } else if (mode & kDropDefaultAlloc) {
325 switch (kind) {
326 case ROOT::kSTLvector:
327 case ROOT::kSTLlist:
329 case ROOT::kSTLdeque:
330 case ROOT::kSTLset:
334 dropAlloc = IsDefAlloc(fElements[iall+1].c_str(),fElements[1].c_str());
335 break;
336 case ROOT::kSTLmap:
340 dropAlloc = IsDefAlloc(fElements[iall+1].c_str(),fElements[1].c_str(),fElements[2].c_str());
341 break;
342 default:
343 dropAlloc = false;
344 }
345
346 }
347 if (dropAlloc) {
348 narg--;
349 allocRemoved = true;
350 }
351 } else {
352 // has no allocator specified (hence it is already removed!)
353 allocRemoved = true;
354 }
355 }
356
357 if ( allocRemoved && (mode & kDropStlDefault) && narg-1 == iall) { // remove default comparator
358 if ( IsDefComp( fElements[iall].c_str(), fElements[1].c_str() ) ) {
359 narg--;
360 }
361 } else if ( mode & kDropComparator ) {
362
363 switch (kind) {
364 case ROOT::kSTLvector:
365 case ROOT::kSTLlist:
367 case ROOT::kSTLdeque:
368 break;
369 case ROOT::kSTLset:
371 case ROOT::kSTLmap:
373 if (!allocRemoved && narg-1 == iall+1) {
374 narg--;
375 allocRemoved = true;
376 }
377 if (narg-1 == iall) narg--;
378 break;
379 default:
380 break;
381 }
382 }
383
384 // Treat now Pred and Hash for unordered set/map containers. Signature is:
385 // template < class Key,
386 // class Hash = hash<Key>,
387 // class Pred = equal_to<Key>,
388 // class Alloc = allocator<Key>
389 // > class unordered_{set,multiset}
390 // template < class Key,
391 // class Val,
392 // class Hash = hash<Key>,
393 // class Pred = equal_to<Key>,
394 // class Alloc = allocator<Key>
395 // > class unordered_{map,multimap}
396
397
399
400 bool predRemoved = false;
401
402 if ( allocRemoved && (mode & kDropStlDefault) && narg-1 == iall) { // remove default predicate
403 if ( IsDefPred( fElements[iall].c_str(), fElements[1].c_str() ) ) {
404 predRemoved=true;
405 narg--;
406 }
407 }
408
409 if ( predRemoved && (mode & kDropStlDefault) && narg == iall) { // remove default hash
410 if ( IsDefHash( fElements[iall-1].c_str(), fElements[1].c_str() ) ) {
411 narg--;
412 }
413 }
414 }
415 } // End of treatment of stl containers
416 else {
417 if ( (mode & kDropStlDefault) && (narg >= 3)) {
418 unsigned int offset = (0==strncmp("const ",fElements[0].c_str(),6)) ? 6 : 0;
419 offset += (0==strncmp("std::",fElements[0].c_str()+offset,5)) ? 5 : 0;
420 if (0 == strcmp(fElements[0].c_str()+offset,"__shared_ptr"))
421 {
422#ifdef _CONCURRENCE_H
423 static const std::string sharedPtrDef = std::to_string(__gnu_cxx::__default_lock_policy); // to_string is C++11
424#else
425 static const std::string sharedPtrDef = std::to_string(2); // to_string is C++11
426#endif
427 if (fElements[2] == sharedPtrDef) {
428 narg--;
429 }
430 }
431 }
432 }
433
434 // do the same for all inside
435 for (int i=1;i<narg; i++) {
436 if (strchr(fElements[i].c_str(),'<')==0) {
437 if (mode&kDropStd) {
438 unsigned int offset = (0==strncmp("const ",fElements[i].c_str(),6)) ? 6 : 0;
439 RemoveStd( fElements[i], offset );
440 }
441 if (mode&kResolveTypedef) {
442 fElements[i] = ResolveTypedef(fElements[i].c_str(),true);
443 }
444 continue;
445 }
446 fElements[i] = TClassEdit::ShortType(fElements[i].c_str(),mode | TClassEdit::kKeepOuterConst);
447 if (mode&kResolveTypedef) {
448 // We 'just' need to check whether the outer type is a typedef or not;
449 // this also will add the default template parameter if any needs to
450 // be added.
451 string typeresult;
452 if (gInterpreterHelper &&
453 (gInterpreterHelper->ExistingTypeCheck(fElements[i], typeresult)
454 || gInterpreterHelper->GetPartiallyDesugaredNameWithScopeHandling(fElements[i], typeresult))) {
455 if (!typeresult.empty()) fElements[i] = typeresult;
456 }
457 }
458 }
459
460 unsigned int tailOffset = 0;
461 if (tailLoc && fElements[tailLoc].compare(0,5,"const") == 0) {
462 if (mode & kKeepOuterConst) answ += "const ";
463 tailOffset = 5;
464 }
465 if (!fElements[0].empty()) {answ += fElements[0]; answ +="<";}
466
467#if 0
468 // This code is no longer use, the moral equivalent would be to get
469 // the 'fixed' number of argument the user told us to ignore and drop those.
470 // However, the name we get here might be (usually) normalized enough that
471 // this is not necessary (at the very least nothing break in roottest without
472 // the aforementioned new code or this old code).
473 if (mode & kDropAllDefault) {
474 int nargNonDefault = 0;
475 std::string nonDefName = answ;
476 // "superlong" because tLong might turn fName into an even longer name
477 std::string nameSuperLong = fName;
478 if (gInterpreterHelper)
479 gInterpreterHelper->GetPartiallyDesugaredName(nameSuperLong);
480 while (++nargNonDefault < narg) {
481 // If T<a> is a "typedef" (aka default template params)
482 // to T<a,b> then we can strip the "b".
483 const char* closeTemplate = " >";
484 if (nonDefName[nonDefName.length() - 1] != '>')
485 ++closeTemplate;
486 string nondef = nonDefName + closeTemplate;
487 if (gInterpreterHelper &&
488 gInterpreterHelper->IsAlreadyPartiallyDesugaredName(nondef, nameSuperLong))
489 break;
490 if (nargNonDefault>1) nonDefName += ",";
491 nonDefName += fElements[nargNonDefault];
492 }
493 if (nargNonDefault < narg)
494 narg = nargNonDefault;
495 }
496#endif
497
498 { for (int i=1;i<narg-1; i++) { answ += fElements[i]; answ+=",";} }
499 if (narg>1) { answ += fElements[narg-1]; }
500
501 if (!fElements[0].empty()) {
502 if ( answ.at(answ.size()-1) == '>') {
503 answ += " >";
504 } else {
505 answ += '>';
506 }
507 }
508 if (fNestedLocation) {
509 // Treat X pf A<B>::X
510 fElements[fNestedLocation] = TClassEdit::ShortType(fElements[fNestedLocation].c_str(),mode);
511 answ += fElements[fNestedLocation];
512 }
513 // tail is not a type name, just [2], &, * etc.
514 if (tailLoc) answ += fElements[tailLoc].c_str()+tailOffset;
515}
516
517////////////////////////////////////////////////////////////////////////////////
518/// Check if the type is a template
520{
521 return !fElements[0].empty();
522}
523
524////////////////////////////////////////////////////////////////////////////////
525/// Converts STL container name to number. vector -> 1, etc..
526/// If len is greater than 0, only look at that many characters in the string.
527
529{
530 if (type.length() == 0)
531 return ROOT::kNotSTL;
532 size_t offset = 0;
533 if (type.compare(0,6,"const ")==0) { offset += 6; }
534 offset += StdLen(type.substr(offset));
535 const auto len = type.length() - offset;
536 if (len == 0)
537 return ROOT::kNotSTL;
538
539 //container names
540 static const char *stls[] =
541 { "any", "vector", "list", "deque", "map", "multimap", "set", "multiset", "bitset",
542 "forward_list", "unordered_set", "unordered_multiset", "unordered_map", "unordered_multimap", 0};
543 static const size_t stllen[] =
544 { 3, 6, 4, 5, 3, 8, 3, 8, 6,
545 12, 13, 18, 13, 18, 0};
546 static const ROOT::ESTLType values[] =
552 // New C++11
557 };
558
559 // kind of stl container
560 // find the correct ESTLType, skipping std::any (because I/O for it is not implemented yet?)
561 for (int k = 1; stls[k]; ++k) {
562 if (len == stllen[k]) {
563 if (type.compare(offset, len, stls[k]) == 0)
564 return values[k];
565 }
566 }
567 return ROOT::kNotSTL;
568}
569
570////////////////////////////////////////////////////////////////////////////////
571/// Return number of arguments for STL container before allocator
572
574{
575 static const char stln[] =// min number of container arguments
576 // vector, list, deque, map, multimap, set, multiset, bitset,
577 { 1, 1, 1, 1, 3, 3, 2, 2, 1,
578 // forward_list, unordered_set, unordered_multiset, unordered_map, unordered_multimap, ROOT::RVec
579 1, 3, 3, 4, 4, 1};
580 assert(std::size_t(kind) < sizeof(stln) && "index is out of bounds");
581
582 return stln[kind];
583}
584
585////////////////////////////////////////////////////////////////////////////////
586
587static size_t findNameEnd(const std::string_view full)
588{
589 int level = 0;
590 for(size_t i = 0; i < full.length(); ++i) {
591 switch(full[i]) {
592 case '<': { ++level; break; }
593 case '>': {
594 if (level == 0) return i;
595 else --level;
596 break;
597 }
598 case ',': {
599 if (level == 0) return i;
600 break;
601 }
602 default: break;
603 }
604 }
605 return full.length();
606}
607
608////////////////////////////////////////////////////////////////////////////////
609
610static size_t findNameEnd(const std::string &full, size_t pos)
611{
612 return pos + findNameEnd( {full.data()+pos,full.length()-pos} );
613}
614
615////////////////////////////////////////////////////////////////////////////////
616/// return whether or not 'allocname' is the STL default allocator for type
617/// 'classname'
618
619bool TClassEdit::IsDefAlloc(const char *allocname, const char *classname)
620{
621 string_view a( allocname );
622 RemoveStd(a);
623
624 if (a=="alloc") return true;
625 if (a=="__default_alloc_template<true,0>") return true;
626 if (a=="__malloc_alloc_template<0>") return true;
627
628 const static int alloclen = strlen("allocator<");
629 if (a.compare(0,alloclen,"allocator<") != 0) {
630 return false;
631 }
632 a.remove_prefix(alloclen);
633
634 RemoveStd(a);
635
636 string_view k = classname;
637 RemoveStd(k);
638
639 if (a.compare(0,k.length(),k) != 0) {
640 // Now we need to compare the normalized name.
641 size_t end = findNameEnd(a);
642
643 std::string valuepart;
644 GetNormalizedName(valuepart,std::string_view(a.data(),end));
645
646 std::string norm_value;
647 GetNormalizedName(norm_value,k);
648
649 if (valuepart != norm_value) {
650 return false;
651 }
652 a.remove_prefix(end);
653 } else {
654 a.remove_prefix(k.length());
655 }
656
657 if (a.compare(0,1,">")!=0 && a.compare(0,2," >")!=0) {
658 return false;
659 }
660
661 return true;
662}
663
664////////////////////////////////////////////////////////////////////////////////
665/// return whether or not 'allocname' is the STL default allocator for a key
666/// of type 'keyclassname' and a value of type 'valueclassname'
667
668bool TClassEdit::IsDefAlloc(const char *allocname,
669 const char *keyclassname,
670 const char *valueclassname)
671{
672 if (IsDefAlloc(allocname,keyclassname)) return true;
673
674 string_view a( allocname );
675 RemoveStd(a);
676
677 const static int alloclen = strlen("allocator<");
678 if (a.compare(0,alloclen,"allocator<") != 0) {
679 return false;
680 }
681 a.remove_prefix(alloclen);
682
683 RemoveStd(a);
684
685 const static int pairlen = strlen("pair<");
686 if (a.compare(0,pairlen,"pair<") != 0) {
687 return false;
688 }
689 a.remove_prefix(pairlen);
690
691 const static int constlen = strlen("const");
692 if (a.compare(0,constlen+1,"const ") == 0) {
693 a.remove_prefix(constlen+1);
694 }
695
696 RemoveStd(a);
697
698 string_view k = keyclassname;
699 RemoveStd(k);
700 if (k.compare(0,constlen+1,"const ") == 0) {
701 k.remove_prefix(constlen+1);
702 }
703
704 if (a.compare(0,k.length(),k) != 0) {
705 // Now we need to compare the normalized name.
706 size_t end = findNameEnd(a);
707
708 std::string alloc_keypart;
709 GetNormalizedName(alloc_keypart,std::string_view(a.data(),end));
710
711 std::string norm_key;
712 GetNormalizedName(norm_key,k);
713
714 if (alloc_keypart != norm_key) {
715 if ( norm_key[norm_key.length()-1] == '*' ) {
716 // also check with a trailing 'const'.
717 norm_key += "const";
718 } else {
719 norm_key += " const";
720 }
721 if (alloc_keypart != norm_key) {
722 return false;
723 }
724 }
725 a.remove_prefix(end);
726 } else {
727 size_t end = k.length();
728 if ( (a[end-1] == '*') || a[end]==' ' ) {
729 size_t skipSpace = (a[end] == ' ');
730 if (a.compare(end+skipSpace,constlen,"const") == 0) {
731 end += constlen+skipSpace;
732 }
733 }
734 a.remove_prefix(end);
735 }
736
737 if (a[0] != ',') {
738 return false;
739 }
740 a.remove_prefix(1);
741 RemoveStd(a);
742
743 string_view v = valueclassname;
744 RemoveStd(v);
745
746 if (a.compare(0,v.length(),v) != 0) {
747 // Now we need to compare the normalized name.
748 size_t end = findNameEnd(a);
749
750 std::string valuepart;
751 GetNormalizedName(valuepart,std::string_view(a.data(),end));
752
753 std::string norm_value;
754 GetNormalizedName(norm_value,v);
755
756 if (valuepart != norm_value) {
757 return false;
758 }
759 a.remove_prefix(end);
760 } else {
761 a.remove_prefix(v.length());
762 }
763
764 if (a.compare(0,1,">")!=0 && a.compare(0,2," >")!=0) {
765 return false;
766 }
767
768 return true;
769}
770
771////////////////////////////////////////////////////////////////////////////////
772/// return whether or not 'elementName' is the STL default Element for type
773/// 'classname'
774
775static bool IsDefElement(const char *elementName, const char* defaultElementName, const char *classname)
776{
777 string c = elementName;
778
779 size_t pos = StdLen(c);
780
781 const int elementlen = strlen(defaultElementName);
782 if (c.compare(pos,elementlen,defaultElementName) != 0) {
783 return false;
784 }
785 pos += elementlen;
786
787 string k = classname;
788 if (c.compare(pos,k.length(),k) != 0) {
789 // Now we need to compare the normalized name.
790 size_t end = findNameEnd(c,pos);
791
792 std::string keypart;
793 if (pos != end) { // i.e. elementName != "std::less<>", see ROOT-11000.
794 TClassEdit::GetNormalizedName(keypart,std::string_view(c.c_str()+pos,end-pos));
795 }
796
797 std::string norm_key;
799
800 if (keypart != norm_key) {
801 return false;
802 }
803 pos = end;
804 } else {
805 pos += k.length();
806 }
807
808 if (c.compare(pos,1,">")!=0 && c.compare(pos,2," >")!=0) {
809 return false;
810 }
811
812 return true;
813}
814
815////////////////////////////////////////////////////////////////////////////////
816/// return whether or not 'compare' is the STL default comparator for type
817/// 'classname'
818
819bool TClassEdit::IsDefComp(const char *compname, const char *classname)
820{
821 return IsDefElement(compname, "less<", classname);
822}
823
824////////////////////////////////////////////////////////////////////////////////
825/// return whether or not 'predname' is the STL default predicate for type
826/// 'classname'
827
828bool TClassEdit::IsDefPred(const char *predname, const char *classname)
829{
830 return IsDefElement(predname, "equal_to<", classname);
831}
832
833////////////////////////////////////////////////////////////////////////////////
834/// return whether or not 'hashname' is the STL default hash for type
835/// 'classname'
836
837bool TClassEdit::IsDefHash(const char *hashname, const char *classname)
838{
839 return IsDefElement(hashname, "hash<", classname);
840}
841
842////////////////////////////////////////////////////////////////////////////////
843/// Return the normalized name. See TMetaUtils::GetNormalizedName.
844///
845/// Return the type name normalized for ROOT,
846/// keeping only the ROOT opaque typedef (Double32_t, etc.) and
847/// removing the STL collections default parameter if any.
848///
849/// Compare to TMetaUtils::GetNormalizedName, this routines does not
850/// and can not add default template parameters.
851
852void TClassEdit::GetNormalizedName(std::string &norm_name, std::string_view name)
853{
854 if (name.empty()) {
855 norm_name.clear();
856 return;
857 }
858
859 norm_name = std::string(name); // NOTE: Is that the shortest version?
860
862 // If there is a @ symbol (followed by a version number) then this is a synthetic class name created
863 // from an already normalized name for the purpose of supporting schema evolution.
864 return;
865 }
866
867 // Remove the std:: and default template argument and insert the Long64_t and change basic_string to string.
870
871 // 4 elements expected: "pair", "first type name", "second type name", "trailing stars"
872 if (splitname.fElements.size() == 4 && (splitname.fElements[0] == "std::pair" || splitname.fElements[0] == "pair" || splitname.fElements[0] == "__pair_base")) {
873 // We don't want to lookup the std::pair itself.
874 std::string first, second;
875 GetNormalizedName(first, splitname.fElements[1]);
876 GetNormalizedName(second, splitname.fElements[2]);
877 norm_name = splitname.fElements[0] + "<" + first + "," + second;
878 if (!second.empty() && second.back() == '>')
879 norm_name += " >";
880 else
881 norm_name += ">";
882 return;
883 }
884
885 // Depending on how the user typed their code, in particular typedef
886 // declarations, we may end up with an explicit '::' being
887 // part of the result string. For consistency, we must remove it.
888 if (norm_name.length()>2 && norm_name[0]==':' && norm_name[1]==':') {
889 norm_name.erase(0,2);
890 }
891
892 if (gInterpreterHelper) {
893 // See if the expanded name itself is a typedef.
894 std::string typeresult;
895 if (gInterpreterHelper->ExistingTypeCheck(norm_name, typeresult)
896 || gInterpreterHelper->GetPartiallyDesugaredNameWithScopeHandling(norm_name, typeresult)) {
897
898 if (!typeresult.empty()) norm_name = typeresult;
899 }
900 }
901}
902
903////////////////////////////////////////////////////////////////////////////////
904/// Replace 'long long' and 'unsigned long long' by 'Long64_t' and 'ULong64_t'
905
906string TClassEdit::GetLong64_Name(const char* original)
907{
908 if (original==0)
909 return "";
910 else
911 return GetLong64_Name(string(original));
912}
913
914////////////////////////////////////////////////////////////////////////////////
915/// Replace 'long long' and 'unsigned long long' by 'Long64_t' and 'ULong64_t'
916
917string TClassEdit::GetLong64_Name(const string& original)
918{
919 static const char* longlong_s = "long long";
920 static const char* ulonglong_s = "unsigned long long";
921 static const unsigned int longlong_len = strlen(longlong_s);
922 static const unsigned int ulonglong_len = strlen(ulonglong_s);
923
924 string result = original;
925
926 int pos = 0;
927 while( (pos = result.find(ulonglong_s,pos) ) >=0 ) {
928 result.replace(pos, ulonglong_len, "ULong64_t");
929 }
930 pos = 0;
931 while( (pos = result.find(longlong_s,pos) ) >=0 ) {
932 result.replace(pos, longlong_len, "Long64_t");
933 }
934 return result;
935}
936
937////////////////////////////////////////////////////////////////////////////////
938/// Return the start of the unqualified name include in 'original'.
939
940const char *TClassEdit::GetUnqualifiedName(const char *original)
941{
942 const char *lastPos = original;
943 {
944 long depth = 0;
945 for(auto cursor = original; *cursor != '\0'; ++cursor) {
946 if ( *cursor == '<' || *cursor == '(') ++depth;
947 else if ( *cursor == '>' || *cursor == ')' ) --depth;
948 else if ( *cursor == ':' ) {
949 if (depth==0 && *(cursor+1) == ':' && *(cursor+2) != '\0') {
950 lastPos = cursor+2;
951 }
952 }
953 }
954 }
955 return lastPos;
956}
957
958////////////////////////////////////////////////////////////////////////////////
959
960static void R__FindTrailing(std::string &full, /*modified*/
961 std::string &stars /* the literal output */
962 )
963{
964 const char *t = full.c_str();
965 const unsigned int tlen( full.size() );
966
967 const char *starloc = t + tlen - 1;
968 bool hasconst = false;
969 if ( (*starloc)=='t'
970 && (starloc-t) > 4 && 0 == strncmp((starloc-4),"const",5)
971 && ( (*(starloc-5)) == ' ' || (*(starloc-5)) == '*' || (*(starloc-5)) == '&'
972 || (*(starloc-5)) == '>' || (*(starloc-5)) == ']') ) {
973 // we are ending on a const.
974 starloc -= 4;
975 if ((*starloc-1)==' ') {
976 // Take the space too.
977 starloc--;
978 }
979 hasconst = true;
980 }
981 if ( hasconst || (*starloc)=='*' || (*starloc)=='&' || (*starloc)==']' ) {
982 bool isArray = ( (*starloc)==']' );
983 while( t<=(starloc-1) && ((*(starloc-1))=='*' || (*(starloc-1))=='&' || (*(starloc-1))=='t' || isArray)) {
984 if (isArray) {
985 starloc--;
986 isArray = ! ( (*starloc)=='[' );
987 } else if ( (*(starloc-1))=='t' ) {
988 if ( (starloc-1-t) > 5 && 0 == strncmp((starloc-5),"const",5)
989 && ( (*(starloc-6)) == ' ' || (*(starloc-6)) == '*' || (*(starloc-6)) == '&'
990 || (*(starloc-6)) == '>' || (*(starloc-6)) == ']')) {
991 // we have a const.
992 starloc -= 5;
993 } else {
994 break;
995 }
996 } else {
997 starloc--;
998 }
999 }
1000 stars = starloc;
1001 if ((*(starloc-1))==' ') {
1002 // erase the space too.
1003 starloc--;
1004 }
1005
1006 const unsigned int starlen = strlen(starloc);
1007 full.erase(tlen-starlen,starlen);
1008 } else if (hasconst) {
1009 stars = starloc;
1010 const unsigned int starlen = strlen(starloc);
1011 full.erase(tlen-starlen,starlen);
1012 }
1013
1014}
1015
1016////////////////////////////////////////////////////////////////////////////////
1017////////////////////////////////////////////////////////////////////////////
1018/// Stores in output (after emptying it) the split type.
1019/// Stores the location of the tail (nested names) in nestedLoc (0 indicates no tail).
1020/// Return the number of elements stored.
1021///
1022/// First in list is the template name or is empty
1023/// "vector<list<int>,alloc>**" to "vector" "list<int>" "alloc" "**"
1024/// or "TNamed*" to "" "TNamed" "*"
1025////////////////////////////////////////////////////////////////////////////
1026
1027int TClassEdit::GetSplit(const char *type, vector<string>& output, int &nestedLoc, EModType mode)
1028{
1029 nestedLoc = 0;
1030 output.clear();
1031 if (strlen(type)==0) return 0;
1032
1033 int cleantypeMode = 1 /* keepInnerConst */;
1034 if (mode & kKeepOuterConst) {
1035 cleantypeMode = 0; /* remove only the outer class keyword */
1036 }
1037 string full( mode & kLong64 ? TClassEdit::GetLong64_Name( CleanType(type, cleantypeMode) )
1038 : CleanType(type, cleantypeMode) );
1039
1040 // We need to replace basic_string with string.
1041 {
1042 unsigned int const_offset = (0==strncmp("const ",full.c_str(),6)) ? 6 : 0;
1043 bool isString = false;
1044 bool isStdString = false;
1045 size_t std_offset = const_offset;
1046 static const char* basic_string_std = "std::basic_string<char";
1047 static const unsigned int basic_string_std_len = strlen(basic_string_std);
1048
1049 if (full.compare(const_offset,basic_string_std_len,basic_string_std) == 0
1050 && full.size() > basic_string_std_len) {
1051 isString = true;
1052 isStdString = true;
1053 std_offset += 5;
1054 } else if (full.compare(const_offset,basic_string_std_len-5,basic_string_std+5) == 0
1055 && full.size() > (basic_string_std_len-5)) {
1056 // no std.
1057 isString = true;
1058 } else if (full.find("basic_string") != std::string::npos) {
1059 size_t len = StdLen(full.c_str() + const_offset);
1060 if (len && len != 5 && full.compare(const_offset + len, basic_string_std_len-5, basic_string_std+5) == 0) {
1061 isString = true;
1062 isStdString = true;
1063 std_offset += len;
1064 }
1065 }
1066 if (isString) {
1067 size_t offset = basic_string_std_len - 5;
1068 offset += std_offset; // std_offset includs both the size of std prefix and const prefix.
1069 if ( full[offset] == '>' ) {
1070 // done.
1071 } else if (full[offset] == ',') {
1072 ++offset;
1073 if (full.compare(offset, 5, "std::") == 0) {
1074 offset += 5;
1075 }
1076 static const char* char_traits_s = "char_traits<char>";
1077 static const unsigned int char_traits_len = strlen(char_traits_s);
1078 if (full.compare(offset, char_traits_len, char_traits_s) == 0) {
1079 offset += char_traits_len;
1080 if ( full[offset] == '>') {
1081 // done.
1082 } else if (full[offset] == ' ' && full[offset+1] == '>') {
1083 ++offset;
1084 // done.
1085 } else if (full[offset] == ',') {
1086 ++offset;
1087 if (full.compare(offset, 5, "std::") == 0) {
1088 offset += 5;
1089 }
1090 static const char* allocator_s = "allocator<char>";
1091 static const unsigned int allocator_len = strlen(allocator_s);
1092 if (full.compare(offset, allocator_len, allocator_s) == 0) {
1093 offset += allocator_len;
1094 if ( full[offset] == '>') {
1095 // done.
1096 } else if (full[offset] == ' ' && full[offset+1] == '>') {
1097 ++offset;
1098 // done.
1099 } else {
1100 // Not std::string
1101 isString = false;
1102 }
1103 }
1104 } else {
1105 // Not std::string
1106 isString = false;
1107 }
1108 } else {
1109 // Not std::string.
1110 isString = false;
1111 }
1112 } else {
1113 // Not std::string.
1114 isString = false;
1115 }
1116 if (isString) {
1117 output.push_back(string());
1118 if (const_offset && (mode & kKeepOuterConst)) {
1119 if (isStdString && !(mode & kDropStd)) {
1120 output.push_back("const std::string");
1121 } else {
1122 output.push_back("const string");
1123 }
1124 } else {
1125 if (isStdString && !(mode & kDropStd)) {
1126 output.push_back("std::string");
1127 } else {
1128 output.push_back("string");
1129 }
1130 }
1131 if (offset < full.length()) {
1132 // Copy the trailing text.
1133 // keep the '>' inside right for R__FindTrailing to work
1134 string right( full.substr(offset) );
1135 string stars;
1136 R__FindTrailing(right, stars);
1137 output.back().append(right.c_str()+1); // skip the '>'
1138 output.push_back(stars);
1139 } else {
1140 output.push_back("");
1141 }
1142 return output.size();
1143 }
1144 }
1145 }
1146
1147 if ( mode & kDropStd) {
1148 unsigned int offset = (0==strncmp("const ",full.c_str(),6)) ? 6 : 0;
1149 RemoveStd( full, offset );
1150 }
1151
1152 string stars;
1153 if ( !full.empty() ) {
1154 R__FindTrailing(full, stars);
1155 }
1156
1157 const char *c = strchr(full.c_str(),'<');
1158 if (c) {
1159 //we have 'something<'
1160 output.push_back(string(full,0,c - full.c_str()));
1161
1162 const char *cursor;
1163 int level = 0;
1164 int parenthesis = 0;
1165 for(cursor = c + 1; *cursor != '\0' && !(level==0 && *cursor == '>'); ++cursor) {
1166 if (*cursor == '(') {
1167 ++parenthesis;
1168 continue;
1169 } else if (*cursor == ')') {
1170 --parenthesis;
1171 continue;
1172 }
1173 if (parenthesis)
1174 continue;
1175 switch (*cursor) {
1176 case '<': ++level; break;
1177 case '>': --level; break;
1178 case ',':
1179 if (level == 0) {
1180 output.push_back(std::string(c+1,cursor));
1181 c = cursor;
1182 }
1183 break;
1184 }
1185 }
1186 if (*cursor=='>') {
1187 if (*(cursor-1) == ' ') {
1188 output.push_back(std::string(c+1,cursor-1));
1189 } else {
1190 output.push_back(std::string(c+1,cursor));
1191 }
1192 // See what's next!
1193 if (*(cursor+1)==':') {
1194 // we have a name specified inside the class/namespace
1195 // For now we keep it in one piece
1196 nestedLoc = output.size();
1197 output.push_back((cursor+1));
1198 }
1199 } else if (level >= 0) {
1200 // Unterminated template
1201 output.push_back(std::string(c+1,cursor));
1202 }
1203 } else {
1204 //empty
1205 output.push_back(string());
1206 output.push_back(full);
1207 }
1208
1209 if (!output.empty()) output.push_back(stars);
1210 return output.size();
1211}
1212
1213
1214////////////////////////////////////////////////////////////////////////////////
1215////////////////////////////////////////////////////////////////////////////
1216/// Cleanup type description, redundant blanks removed
1217/// and redundant tail ignored
1218/// return *tail = pointer to last used character
1219/// if (mode==0) keep keywords
1220/// if (mode==1) remove keywords outside the template params
1221/// if (mode>=2) remove the keywords everywhere.
1222/// if (tail!=0) cut before the trailing *
1223///
1224/// The keywords currently are: "const" , "volatile" removed
1225///
1226///
1227/// CleanType(" A<B, C< D, E> > *,F,G>") returns "A<B,C<D,E> >*"
1228////////////////////////////////////////////////////////////////////////////
1229
1230string TClassEdit::CleanType(const char *typeDesc, int mode, const char **tail)
1231{
1232 static const char* remove[] = {"class","const","volatile",0};
1233 auto initLengthsVector = []() {
1234 std::vector<size_t> create_lengths;
1235 for (int k=0; remove[k]; ++k) {
1236 create_lengths.push_back(strlen(remove[k]));
1237 }
1238 return create_lengths;
1239 };
1240 static std::vector<size_t> lengths{ initLengthsVector() };
1241
1242 string result;
1243 result.reserve(strlen(typeDesc)*2);
1244 int lev=0,kbl=1;
1245 const char* c;
1246
1247 for(c=typeDesc;*c;c++) {
1248 if (c[0]==' ') {
1249 if (kbl) continue;
1250 if (!isalnum(c[ 1]) && c[ 1] !='_') continue;
1251 }
1252 if (kbl && (mode>=2 || lev==0)) { //remove "const' etc...
1253 int done = 0;
1254 int n = (mode) ? 999 : 1;
1255
1256 // loop on all the keywords we want to remove
1257 for (int k=0; k<n && remove[k]; k++) {
1258 int rlen = lengths[k];
1259
1260 // Do we have a match
1261 if (strncmp(remove[k],c,rlen)) continue;
1262
1263 // make sure that the 'keyword' is not part of a longer indentifier
1264 if (isalnum(c[rlen]) || c[rlen]=='_' || c[rlen]=='$') continue;
1265
1266 c+=rlen-1; done = 1; break;
1267 }
1268 if (done) continue;
1269 }
1270
1271 kbl = (!isalnum(c[ 0]) && c[ 0]!='_' && c[ 0]!='$' && c[0]!='[' && c[0]!=']' && c[0]!='-' && c[0]!='@');
1272 // '@' is special character used only the artifical class name used by ROOT to implement the
1273 // I/O customization rules that requires caching of the input data.
1274
1275 if (*c == '<' || *c == '(') lev++;
1276 if (lev==0 && !isalnum(*c)) {
1277 if (!strchr("*&:._$ []-@",*c)) break;
1278 // '.' is used as a module/namespace separator by PyROOT, see
1279 // TPyClassGenerator::GetClass.
1280 }
1281 if (c[0]=='>' && result.size() && result[result.size()-1]=='>') result+=" ";
1282
1283 result += c[0];
1284
1285 if (*c == '>' || *c == ')') lev--;
1286 }
1287 if(tail) *tail=c;
1288 return result;
1289}
1290
1291////////////////////////////////////////////////////////////////////////////////
1292//////////////////////////////////////////////////////////////////////////////
1293/// Return the absolute type of typeDesc.
1294/// E.g.: typeDesc = "class const volatile TNamed**", returns "TNamed**".
1295/// if (mode&1) remove last "*"s returns "TNamed"
1296/// if (mode&2) remove default allocators from STL containers
1297/// if (mode&4) remove all allocators from STL containers
1298/// if (mode&8) return inner class of stl container. list<innerClass>
1299/// if (mode&16) return deapest class of stl container. vector<list<deapest>>
1300/// if (mode&kDropAllDefault) remove default template arguments
1301//////////////////////////////////////////////////////////////////////////////
1302
1303string TClassEdit::ShortType(const char *typeDesc, int mode)
1304{
1305 string answer;
1306
1307 // get list of all arguments
1308 if (typeDesc) {
1309 TSplitType arglist(typeDesc, (EModType) mode);
1310 arglist.ShortType(answer, mode);
1311 }
1312
1313 return answer;
1314}
1315
1316////////////////////////////////////////////////////////////////////////////////
1317/// Return true if the type is one the interpreter details which are
1318/// only forward declared (ClassInfo_t etc..)
1319
1321{
1322 size_t len = strlen(type);
1323 if (len < 2 || strncmp(type+len-2,"_t",2) != 0) return false;
1324
1325 unsigned char offset = 0;
1326 if (strncmp(type,"const ",6)==0) { offset += 6; }
1327 static const char *names[] = { "CallFunc_t","ClassInfo_t","BaseClassInfo_t",
1328 "DataMemberInfo_t","FuncTempInfo_t","MethodInfo_t","MethodArgInfo_t",
1329 "TypeInfo_t","TypedefInfo_t",0};
1330
1331 for(int k=1;names[k];k++) {if (strcmp(type+offset,names[k])==0) return true;}
1332 return false;
1333}
1334
1335////////////////////////////////////////////////////////////////////////////////
1336/// Return true is the name is std::bitset<number> or bitset<number>
1337
1338bool TClassEdit::IsSTLBitset(const char *classname)
1339{
1340 size_t offset = StdLen(classname);
1341 if ( strncmp(classname+offset,"bitset<",strlen("bitset<"))==0) return true;
1342 return false;
1343}
1344
1345////////////////////////////////////////////////////////////////////////////////
1346/// Return the type of STL collection, if any, that is the underlying type
1347/// of the given type. Namely return the value of IsSTLCont after stripping
1348/// pointer, reference and constness from the type.
1349/// UnderlyingIsSTLCont("vector<int>*") == IsSTLCont("vector<int>")
1350/// See TClassEdit::IsSTLCont
1351///
1352/// type : type name: vector<list<classA,allocator>,allocator>*
1353/// result: 0 : not stl container
1354/// code of container 1=vector,2=list,3=deque,4=map
1355/// 5=multimap,6=set,7=multiset
1356
1358{
1359 if (type.compare(0,6,"const ",6) == 0)
1360 type.remove_prefix(6);
1361
1362 while(type[type.length()-1]=='*' ||
1363 type[type.length()-1]=='&' ||
1364 type[type.length()-1]==' ') {
1365 type.remove_suffix(1);
1366 }
1367 return IsSTLCont(type);
1368}
1369
1370////////////////////////////////////////////////////////////////////////////////
1371/// type : type name: vector<list<classA,allocator>,allocator>
1372/// result: 0 : not stl container
1373/// code of container 1=vector,2=list,3=deque,4=map
1374/// 5=multimap,6=set,7=multiset
1375
1377{
1378 auto pos = type.find('<');
1379 if (pos==std::string_view::npos) return ROOT::kNotSTL;
1380
1381 auto c = pos+1;
1382 for (decltype(type.length()) level = 1; c < type.length(); ++c) {
1383 if (type[c] == '<') ++level;
1384 if (type[c] == '>') --level;
1385 if (level == 0) break;
1386 }
1387 if (c != (type.length()-1) ) {
1388 return ROOT::kNotSTL;
1389 }
1390
1391 return STLKind(type.substr(0,pos));
1392}
1393
1394////////////////////////////////////////////////////////////////////////////////
1395/// type : type name: vector<list<classA,allocator>,allocator>
1396/// testAlloc: if true, we test allocator, if it is not default result is negative
1397/// result: 0 : not stl container
1398/// abs(result): code of container 1=vector,2=list,3=deque,4=map
1399/// 5=multimap,6=set,7=multiset
1400/// positive val: we have a vector or list with default allocator to any depth
1401/// like vector<list<vector<int>>>
1402/// negative val: STL container other than vector or list, or non default allocator
1403/// For example: vector<deque<int>> has answer -1
1404
1405int TClassEdit::IsSTLCont(const char *type, int testAlloc)
1406{
1407 if (strchr(type,'<')==0) return 0;
1408
1409 TSplitType arglist( type );
1410 return arglist.IsSTLCont(testAlloc);
1411}
1412
1413////////////////////////////////////////////////////////////////////////////////
1414/// return true if the class belongs to the std namespace
1415
1416bool TClassEdit::IsStdClass(const char *classname)
1417{
1418 classname += StdLen( classname );
1419 if ( strcmp(classname,"string")==0 ) return true;
1420 if ( strncmp(classname,"bitset<",strlen("bitset<"))==0) return true;
1421 if ( IsStdPair(classname) ) return true;
1422 if ( strcmp(classname,"allocator")==0) return true;
1423 if ( strncmp(classname,"allocator<",strlen("allocator<"))==0) return true;
1424 if ( strncmp(classname,"greater<",strlen("greater<"))==0) return true;
1425 if ( strncmp(classname,"less<",strlen("less<"))==0) return true;
1426 if ( strncmp(classname,"equal_to<",strlen("equal_to<"))==0) return true;
1427 if ( strncmp(classname,"hash<",strlen("hash<"))==0) return true;
1428 if ( strncmp(classname,"auto_ptr<",strlen("auto_ptr<"))==0) return true;
1429
1430 if ( strncmp(classname,"vector<",strlen("vector<"))==0) return true;
1431 if ( strncmp(classname,"list<",strlen("list<"))==0) return true;
1432 if ( strncmp(classname,"forward_list<",strlen("forward_list<"))==0) return true;
1433 if ( strncmp(classname,"deque<",strlen("deque<"))==0) return true;
1434 if ( strncmp(classname,"map<",strlen("map<"))==0) return true;
1435 if ( strncmp(classname,"multimap<",strlen("multimap<"))==0) return true;
1436 if ( strncmp(classname,"set<",strlen("set<"))==0) return true;
1437 if ( strncmp(classname,"multiset<",strlen("multiset<"))==0) return true;
1438 if ( strncmp(classname,"unordered_set<",strlen("unordered_set<"))==0) return true;
1439 if ( strncmp(classname,"unordered_multiset<",strlen("unordered_multiset<"))==0) return true;
1440 if ( strncmp(classname,"unordered_map<",strlen("unordered_map<"))==0) return true;
1441 if ( strncmp(classname,"unordered_multimap<",strlen("unordered_multimap<"))==0) return true;
1442 if ( strncmp(classname,"bitset<",strlen("bitset<"))==0) return true;
1443
1444 return false;
1445}
1446
1447
1448////////////////////////////////////////////////////////////////////////////////
1449
1451 TSplitType splitname( name );
1452
1453 return ( TClassEdit::STLKind( splitname.fElements[0] ) == ROOT::kSTLvector)
1454 && ( splitname.fElements[1] == "bool" || splitname.fElements[1]=="Bool_t");
1455}
1456
1457////////////////////////////////////////////////////////////////////////////////
1458
1459static void ResolveTypedefProcessType(const char *tname,
1460 unsigned int /* len */,
1461 unsigned int cursor,
1462 bool constprefix,
1463 unsigned int start_of_type,
1464 unsigned int end_of_type,
1465 unsigned int mod_start_of_type,
1466 bool &modified,
1467 std::string &result)
1468{
1469 std::string type(modified && (mod_start_of_type < result.length()) ?
1470 result.substr(mod_start_of_type, string::npos)
1471 : string(tname, start_of_type, end_of_type == 0 ? cursor - start_of_type : end_of_type - start_of_type)); // we need to try to avoid this copy
1472 string typeresult;
1473 if (gInterpreterHelper->ExistingTypeCheck(type, typeresult)
1474 || gInterpreterHelper->GetPartiallyDesugaredNameWithScopeHandling(type, typeresult, false)) {
1475 // it is a known type
1476 if (!typeresult.empty()) {
1477 // and it is a typedef, we need to replace it in the output.
1478 if (modified) {
1479 result.replace(mod_start_of_type, string::npos,
1480 typeresult);
1481 }
1482 else {
1483 modified = true;
1484 mod_start_of_type = start_of_type;
1485 result += string(tname,0,start_of_type);
1486 if (constprefix && typeresult.compare(0,6,"const ",6) == 0) {
1487 result += typeresult.substr(6,string::npos);
1488 } else {
1489 result += typeresult;
1490 }
1491 }
1492 } else if (modified) {
1493 result.replace(mod_start_of_type, string::npos,
1494 type);
1495 }
1496 if (modified) {
1497 if (end_of_type != 0 && end_of_type!=cursor) {
1498 result += std::string(tname,end_of_type,cursor-end_of_type);
1499 }
1500 }
1501 } else {
1502 // no change needed.
1503 if (modified) {
1504 // result += type;
1505 if (end_of_type != 0 && end_of_type!=cursor) {
1506 result += std::string(tname,end_of_type,cursor-end_of_type);
1507 }
1508 }
1509 }
1510}
1511
1512////////////////////////////////////////////////////////////////////////////////
1513
1514static void ResolveTypedefImpl(const char *tname,
1515 unsigned int len,
1516 unsigned int &cursor,
1517 bool &modified,
1518 std::string &result)
1519{
1520 // Need to parse and deal with
1521 // A::B::C< D, E::F, G::H<I,J>::K::L >::M
1522 // where E might be replace by N<O,P>
1523 // and G::H<I,J>::K or G might be a typedef.
1524
1525 bool constprefix = false;
1526
1527 if (tname[cursor]==' ') {
1528 if (!modified) {
1529 modified = true;
1530 result += string(tname,0,cursor);
1531 }
1532 while (tname[cursor]==' ') ++cursor;
1533 }
1534
1535 if (tname[cursor]=='c' && (cursor+6<len)) {
1536 if (strncmp(tname+cursor,"const ",6) == 0) {
1537 cursor += 6;
1538 if (modified) result += "const ";
1539 }
1540 constprefix = true;
1541
1542 }
1543
1544 if (len > 2 && strncmp(tname+cursor,"::",2) == 0) {
1545 cursor += 2;
1546 }
1547
1548 unsigned int start_of_type = cursor;
1549 unsigned int end_of_type = 0;
1550 unsigned int mod_start_of_type = result.length();
1551 unsigned int prevScope = cursor;
1552 for ( ; cursor<len; ++cursor) {
1553 switch (tname[cursor]) {
1554 case ':': {
1555 if ((cursor+1)>=len || tname[cursor+1]!=':') {
1556 // we expected another ':', malformed, give up.
1557 if (modified) result += (tname+prevScope);
1558 return;
1559 }
1560 string scope;
1561 if (modified) {
1562 scope = result.substr(mod_start_of_type, string::npos);
1563 scope += std::string(tname+prevScope,cursor-prevScope);
1564 } else {
1565 scope = std::string(tname, start_of_type, cursor - start_of_type); // we need to try to avoid this copy
1566 }
1567 std::string scoperesult;
1568 bool isInlined = false;
1569 if (gInterpreterHelper->ExistingTypeCheck(scope, scoperesult)
1570 ||gInterpreterHelper->GetPartiallyDesugaredNameWithScopeHandling(scope, scoperesult)) {
1571 // it is a known type
1572 if (!scoperesult.empty()) {
1573 // and it is a typedef
1574 if (modified) {
1575 if (constprefix && scoperesult.compare(0,6,"const ",6) != 0) mod_start_of_type -= 6;
1576 result.replace(mod_start_of_type, string::npos,
1577 scoperesult);
1578 result += "::";
1579 } else {
1580 modified = true;
1581 mod_start_of_type = start_of_type;
1582 result += string(tname,0,start_of_type);
1583 //if (constprefix) result += "const ";
1584 result += scoperesult;
1585 result += "::";
1586 }
1587 } else if (modified) {
1588 result += std::string(tname+prevScope,cursor+2-prevScope);
1589 }
1590 } else if (!gInterpreterHelper->IsDeclaredScope(scope,isInlined)) {
1591 // the nesting namespace is not declared, just ignore it and move on
1592 if (modified) result += std::string(tname+prevScope,cursor+2-prevScope);
1593 } else if (isInlined) {
1594 // humm ... just skip it.
1595 if (!modified) {
1596 modified = true;
1597 mod_start_of_type = start_of_type;
1598 result += string(tname,0,start_of_type);
1599 //if (constprefix) result += "const ";
1600 result += string(tname,start_of_type,prevScope - start_of_type);
1601 }
1602 } else if (modified) {
1603 result += std::string(tname+prevScope,cursor+2-prevScope);
1604 }
1605 // Consume the 1st semi colon, the 2nd will be consume by the for loop.
1606 ++cursor;
1607 prevScope = cursor+1;
1608 break;
1609 }
1610 case '<': {
1611 // push information on stack
1612 if (modified) {
1613 result += std::string(tname+prevScope,cursor+1-prevScope);
1614 // above includes the '<' .... result += '<';
1615 }
1616 do {
1617 ++cursor;
1618 ResolveTypedefImpl(tname,len,cursor,modified,result);
1619 } while( cursor<len && tname[cursor] == ',' );
1620
1621 while (cursor<len && tname[cursor+1]==' ') ++cursor;
1622
1623 // Since we already checked the type, skip the next section
1624 // (respective the scope section and final type processing section)
1625 // as they would re-do the same job.
1626 if (cursor+2<len && tname[cursor+1]==':' && tname[cursor+2]==':') {
1627 if (modified) result += "::";
1628 cursor += 2;
1629 prevScope = cursor+1;
1630 }
1631 if ( (cursor+1)<len && tname[cursor+1] == ',') {
1632 ++cursor;
1633 if (modified) result += ',';
1634 return;
1635 }
1636 if ( (cursor+1)<len && tname[cursor+1] == '>') {
1637 ++cursor;
1638 if (modified) result += " >";
1639 return;
1640 }
1641 if ( (cursor+1) >= len) {
1642 return;
1643 }
1644 if (tname[cursor] != ' ') break;
1645 if (modified) prevScope = cursor+1;
1646 // If the 'current' character is a space we need to treat it,
1647 // since this the next case statement, we can just fall through,
1648 // otherwise we should need to do:
1649 // --cursor; break;
1650 }
1651 case ' ': {
1652 end_of_type = cursor;
1653 // let's see if we have 'long long' or 'unsigned int' or 'signed char' or what not.
1654 while ((cursor+1)<len && tname[cursor+1] == ' ') ++cursor;
1655
1656 auto next = cursor+1;
1657 if (strncmp(tname+next,"const",5) == 0 && ((next+5)==len || tname[next+5] == ' ' || tname[next+5] == '*' || tname[next+5] == '&' || tname[next+5] == ',' || tname[next+5] == '>' || tname[next+5] == ']'))
1658 {
1659 // A first const after the type needs to be move in the front.
1660 if (!modified) {
1661 modified = true;
1662 result += string(tname,0,start_of_type);
1663 result += "const ";
1664 mod_start_of_type = start_of_type + 6;
1665 result += string(tname,start_of_type,end_of_type-start_of_type);
1666 } else if (mod_start_of_type < result.length()) {
1667 result.insert(mod_start_of_type,"const ");
1668 mod_start_of_type += 6;
1669 } else {
1670 result += "const ";
1671 mod_start_of_type += 6;
1672 result += string(tname,start_of_type,end_of_type-start_of_type);
1673 }
1674 cursor += 5;
1675 end_of_type = cursor+1;
1676 prevScope = end_of_type;
1677 if ((next+5)==len || tname[next+5] == ',' || tname[next+5] == '>' || tname[next+5] == '[') {
1678 break;
1679 }
1680 } else if (next!=len && tname[next] != '*' && tname[next] != '&') {
1681 // the type is not ended yet.
1682 end_of_type = 0;
1683 break;
1684 }
1685 ++cursor;
1686 // Intentional fall through;
1687 }
1688 case '*':
1689 case '&': {
1690 if (tname[cursor] != ' ') end_of_type = cursor;
1691 // check and skip const (followed by *,&, ,) ... what about followed by ':','['?
1692 auto next = cursor+1;
1693 if (strncmp(tname+next,"const",5) == 0) {
1694 if ((next+5)==len || tname[next+5] == ' ' || tname[next+5] == '*' || tname[next+5] == '&' || tname[next+5] == ',' || tname[next+5] == '>' || tname[next+5] == '[') {
1695 next += 5;
1696 }
1697 }
1698 while (next<len &&
1699 (tname[next] == ' ' || tname[next] == '*' || tname[next] == '&')) {
1700 ++next;
1701 // check and skip const (followed by *,&, ,) ... what about followed by ':','['?
1702 if (strncmp(tname+next,"const",5) == 0) {
1703 if ((next+5)==len || tname[next+5] == ' ' || tname[next+5] == '*' || tname[next+5] == '&' || tname[next+5] == ',' || tname[next+5] == '>' || tname[next+5] == '[') {
1704 next += 5;
1705 }
1706 }
1707 }
1708 cursor = next-1;
1709// if (modified && mod_start_of_type < result.length()) {
1710// result += string(tname,end_of_type,cursor-end_of_type);
1711// }
1712 break;
1713 }
1714 case ',': {
1715 if (modified && prevScope) {
1716 result += std::string(tname+prevScope,(end_of_type == 0 ? cursor : end_of_type)-prevScope);
1717 }
1718 ResolveTypedefProcessType(tname,len,cursor,constprefix,start_of_type,end_of_type,mod_start_of_type,
1719 modified, result);
1720 if (modified) result += ',';
1721 return;
1722 }
1723 case '>': {
1724 if (modified && prevScope) {
1725 result += std::string(tname+prevScope,(end_of_type == 0 ? cursor : end_of_type)-prevScope);
1726 }
1727 ResolveTypedefProcessType(tname,len,cursor,constprefix,start_of_type,end_of_type,mod_start_of_type,
1728 modified, result);
1729 if (modified) result += '>';
1730 return;
1731 }
1732 default:
1733 end_of_type = 0;
1734 }
1735 }
1736
1737 if (prevScope && modified) result += std::string(tname+prevScope,(end_of_type == 0 ? cursor : end_of_type)-prevScope);
1738
1739 ResolveTypedefProcessType(tname,len,cursor,constprefix,start_of_type,end_of_type,mod_start_of_type,
1740 modified, result);
1741}
1742
1743
1744////////////////////////////////////////////////////////////////////////////////
1745
1746string TClassEdit::ResolveTypedef(const char *tname, bool /* resolveAll */)
1747{
1748 // Return the name of type 'tname' with all its typedef components replaced
1749 // by the actual type its points to
1750 // For example for "typedef MyObj MyObjTypedef;"
1751 // vector<MyObjTypedef> return vector<MyObj>
1752 //
1753
1754 if (tname == 0 || tname[0] == 0)
1755 return "";
1756 if (!gInterpreterHelper)
1757 return tname;
1758
1759 std::string result;
1760
1761 // Check if we already know it is a normalized typename or a registered
1762 // typedef (i.e. known to gROOT).
1763 if (gInterpreterHelper->ExistingTypeCheck(tname, result))
1764 {
1765 if (result.empty()) return tname;
1766 else return result;
1767 }
1768
1769 unsigned int len = strlen(tname);
1770
1771 unsigned int cursor = 0;
1772 bool modified = false;
1773 ResolveTypedefImpl(tname,len,cursor,modified,result);
1774
1775 if (!modified) return tname;
1776 else return result;
1777}
1778
1779
1780////////////////////////////////////////////////////////////////////////////////
1781
1782string TClassEdit::InsertStd(const char *tname)
1783{
1784 // Return the name of type 'tname' with all STL classes prepended by "std::".
1785 // For example for "vector<set<auto_ptr<int*> > >" it returns
1786 // "std::vector<std::set<std::auto_ptr<int*> > >"
1787 //
1788
1789 static const char* sSTLtypes[] = {
1790 "allocator",
1791 "auto_ptr",
1792 "bad_alloc",
1793 "bad_cast",
1794 "bad_exception",
1795 "bad_typeid",
1796 "basic_filebuf",
1797 "basic_fstream",
1798 "basic_ifstream",
1799 "basic_ios",
1800 "basic_iostream",
1801 "basic_istream",
1802 "basic_istringstream",
1803 "basic_ofstream",
1804 "basic_ostream",
1805 "basic_ostringstream",
1806 "basic_streambuf",
1807 "basic_string",
1808 "basic_stringbuf",
1809 "basic_stringstream",
1810 "binary_function",
1811 "binary_negate",
1812 "bitset",
1813 "char_traits",
1814 "codecvt_byname",
1815 "codecvt",
1816 "collate",
1817 "collate_byname",
1818 "compare",
1819 "complex",
1820 "ctype_byname",
1821 "ctype",
1822 "deque",
1823 "divides",
1824 "domain_error",
1825 "equal_to",
1826 "exception",
1827 "forward_list",
1828 "fpos",
1829 "greater_equal",
1830 "greater",
1831 "gslice_array",
1832 "gslice",
1833 "hash",
1834 "indirect_array",
1835 "invalid_argument",
1836 "ios_base",
1837 "istream_iterator",
1838 "istreambuf_iterator",
1839 "istrstream",
1840 "iterator_traits",
1841 "iterator",
1842 "length_error",
1843 "less_equal",
1844 "less",
1845 "list",
1846 "locale",
1847 "localedef utility",
1848 "locale utility",
1849 "logic_error",
1850 "logical_and",
1851 "logical_not",
1852 "logical_or",
1853 "map",
1854 "mask_array",
1855 "mem_fun",
1856 "mem_fun_ref",
1857 "messages",
1858 "messages_byname",
1859 "minus",
1860 "modulus",
1861 "money_get",
1862 "money_put",
1863 "moneypunct",
1864 "moneypunct_byname",
1865 "multimap",
1866 "multiplies",
1867 "multiset",
1868 "negate",
1869 "not_equal_to",
1870 "num_get",
1871 "num_put",
1872 "numeric_limits",
1873 "numpunct",
1874 "numpunct_byname",
1875 "ostream_iterator",
1876 "ostreambuf_iterator",
1877 "ostrstream",
1878 "out_of_range",
1879 "overflow_error",
1880 "pair",
1881 "plus",
1882 "pointer_to_binary_function",
1883 "pointer_to_unary_function",
1884 "priority_queue",
1885 "queue",
1886 "range_error",
1887 "raw_storage_iterator",
1888 "reverse_iterator",
1889 "runtime_error",
1890 "set",
1891 "slice_array",
1892 "slice",
1893 "stack",
1894 "string",
1895 "strstream",
1896 "strstreambuf",
1897 "time_get_byname",
1898 "time_get",
1899 "time_put_byname",
1900 "time_put",
1901 "unary_function",
1902 "unary_negate",
1903 "unique_pointer",
1904 "underflow_error",
1905 "unordered_map",
1906 "unordered_multimap",
1907 "unordered_multiset",
1908 "unordered_set",
1909 "valarray",
1910 "vector",
1911 "wstring"
1912 };
1913
1914 if (tname==0 || tname[0]==0) return "";
1915
1916 auto initSetSTLtypes = []() {
1917 std::set<std::string> iSetSTLtypes;
1918 // set up static set
1919 const size_t nSTLtypes = sizeof(sSTLtypes) / sizeof(const char*);
1920 for (size_t i = 0; i < nSTLtypes; ++i)
1921 iSetSTLtypes.insert(sSTLtypes[i]);
1922 return iSetSTLtypes;
1923 };
1924 static ShuttingDownSignaler<std::set<std::string>> sSetSTLtypes{ initSetSTLtypes() };
1925
1926 size_t b = 0;
1927 size_t len = strlen(tname);
1928 string ret;
1929 ret.reserve(len + 20); // expect up to 4 extra "std::" to insert
1930 string id;
1931 while (b < len) {
1932 // find beginning of next identifier
1933 bool precScope = false; // whether the identifier was preceded by "::"
1934 while (!(isalnum(tname[b]) || tname[b] == '_') && b < len) {
1935 precScope = (b < len - 2) && (tname[b] == ':') && (tname[b + 1] == ':');
1936 if (precScope) {
1937 ret += "::";
1938 b += 2;
1939 } else
1940 ret += tname[b++];
1941 }
1942
1943 // now b is at the beginning of an identifier or len
1944 size_t e = b;
1945 // find end of identifier
1946 id.clear();
1947 while (e < len && (isalnum(tname[e]) || tname[e] == '_'))
1948 id += tname[e++];
1949 if (!id.empty()) {
1950 if (!precScope) {
1951 set<string>::const_iterator iSTLtype = sSetSTLtypes.find(id);
1952 if (iSTLtype != sSetSTLtypes.end())
1953 ret += "std::";
1954 }
1955
1956 ret += id;
1957 b = e;
1958 }
1959 }
1960 return ret;
1961}
1962
1963////////////////////////////////////////////////////////////////////////////////
1964/// An helper class to dismount the name and remount it changed whenever
1965/// necessary
1966
1967class NameCleanerForIO {
1968 std::string fName;
1969 std::vector<std::unique_ptr<NameCleanerForIO>> fArgumentNodes = {};
1970 NameCleanerForIO* fMother;
1971 bool fHasChanged = false;
1972 bool AreAncestorsSTLContOrArray()
1973 {
1974 NameCleanerForIO* mother = fMother;
1975 if (!mother) return false;
1976 bool isSTLContOrArray = true;
1977 while (nullptr != mother){
1978 auto stlType = TClassEdit::IsSTLCont(mother->fName+"<>");
1979 isSTLContOrArray &= ROOT::kNotSTL != stlType || TClassEdit::IsStdArray(mother->fName+"<");
1980 mother = mother->fMother;
1981 }
1982
1983 return isSTLContOrArray;
1984 }
1985
1986public:
1987 NameCleanerForIO(const std::string& clName = "",
1989 NameCleanerForIO* mother = nullptr):fMother(mother)
1990 {
1991 if (clName.back() != '>') {
1992 fName = clName;
1993 return;
1994 }
1995
1996 std::vector<std::string> v;
1997 int dummy=0;
1998 TClassEdit::GetSplit(clName.c_str(), v, dummy, mode);
1999
2000 // We could be in presence of templates such as A1<T1>::A2<T2>::A3<T3>
2001 auto argsEnd = v.end();
2002 auto argsBeginPlusOne = ++v.begin();
2003 auto argPos = std::find_if(argsBeginPlusOne, argsEnd,
2004 [](std::string& arg){return (!arg.empty() && arg.front() == ':');});
2005 if (argPos != argsEnd) {
2006 const int lenght = clName.size();
2007 int wedgeBalance = 0;
2008 int lastOpenWedge = 0;
2009 for (int i=lenght-1;i>-1;i--) {
2010 auto& c = clName.at(i);
2011 if (c == '<') {
2012 wedgeBalance++;
2013 lastOpenWedge = i;
2014 } else if (c == '>') {
2015 wedgeBalance--;
2016 } else if (c == ':' && 0 == wedgeBalance) {
2017 // This would be A1<T1>::A2<T2>
2018 auto nameToClean = clName.substr(0,i-1);
2019 NameCleanerForIO node(nameToClean, mode);
2020 auto cleanName = node.ToString();
2021 fHasChanged = node.HasChanged();
2022 // We got A1<T1>::A2<T2> cleaned
2023
2024 // We build the changed A1<T1>::A2<T2>::A3
2025 cleanName += "::";
2026 // Now we get A3 and append it
2027 cleanName += clName.substr(i+1,lastOpenWedge-i-1);
2028
2029 // We now get the args of what in our case is A1<T1>::A2<T2>::A3
2030 auto lastTemplate = &clName.data()[i+1];
2031
2032 // We split it
2033 TClassEdit::GetSplit(lastTemplate, v, dummy, mode);
2034 // We now replace the name of the template
2035 v[0] = cleanName;
2036 break;
2037 }
2038 }
2039 }
2040
2041 fName = v.front();
2042 unsigned int nargs = v.size() - 2;
2043 for (unsigned int i=0;i<nargs;++i) {
2044 fArgumentNodes.emplace_back(new NameCleanerForIO(v[i+1],mode,this));
2045 }
2046 }
2047
2048 bool HasChanged() const {return fHasChanged;}
2049
2050 std::string ToString()
2051 {
2052 std::string name(fName);
2053
2054 if (fArgumentNodes.empty()) return name;
2055
2056 // We have in hands a case like unique_ptr< ... >
2057 // Perhaps we could treat atomics as well like this?
2058 if (!fMother && TClassEdit::IsUniquePtr(fName+"<")) {
2059 name = fArgumentNodes.front()->ToString();
2060 // ROOT-9933: we remove const if present.
2061 TClassEdit::TSplitType tst(name.c_str());
2062 tst.ShortType(name, 1);
2063 fHasChanged = true;
2064 return name;
2065 }
2066
2067 // Now we treat the case of the collections of unique ptrs
2068 auto stlContType = AreAncestorsSTLContOrArray();
2069 if (stlContType != ROOT::kNotSTL && TClassEdit::IsUniquePtr(fName+"<")) {
2070 name = fArgumentNodes.front()->ToString();
2071 name += "*";
2072 fHasChanged = true;
2073 return name;
2074 }
2075
2076 name += "<";
2077 for (auto& node : fArgumentNodes) {
2078 name += node->ToString() + ",";
2079 fHasChanged |= node->HasChanged();
2080 }
2081 name.pop_back(); // Remove the last comma.
2082 name += name.back() == '>' ? " >" : ">"; // Respect name normalisation
2083 return name;
2084 }
2085
2086 const std::string& GetName() {return fName;}
2087 const std::vector<std::unique_ptr<NameCleanerForIO>>* GetChildNodes() const {return &fArgumentNodes;}
2088};
2089
2090////////////////////////////////////////////////////////////////////////////////
2091
2092std::string TClassEdit::GetNameForIO(const std::string& templateInstanceName,
2094 bool* hasChanged)
2095{
2096 // Decompose template name into pieces and remount it applying the necessary
2097 // transformations necessary for the ROOT IO subsystem, namely:
2098 // - Transform std::unique_ptr<T> into T (for selections) (also nested)
2099 // - Transform std::unique_ptr<const T> into T (for selections) (also nested)
2100 // - Transform std::COLL<std::unique_ptr<T>> into std::COLL<T*> (also nested)
2101 // Name normalisation is respected (e.g. spaces).
2102 // The implementation uses an internal class defined in the cxx file.
2103 NameCleanerForIO node(templateInstanceName, mode);
2104 auto nameForIO = node.ToString();
2105 if (hasChanged) {
2106 *hasChanged = node.HasChanged();
2107 }
2108 return nameForIO;
2109}
2110
2111////////////////////////////////////////////////////////////////////////////////
2112// We could introduce a tuple as return type, but we be consistent with the rest
2113// of the code.
2114bool TClassEdit::GetStdArrayProperties(const char* typeName,
2115 std::string& typeNameBuf,
2116 std::array<int, 5>& maxIndices,
2117 int& ndim)
2118{
2119 if (!IsStdArray(typeName)) return false;
2120
2121 // We have an array, it's worth continuing
2122 NameCleanerForIO node(typeName);
2123
2124 // We now recurse updating the data according to what we find
2125 auto childNodes = node.GetChildNodes();
2126 for (ndim = 1;ndim <=5 ; ndim++) {
2127 maxIndices[ndim-1] = std::atoi(childNodes->back()->GetName().c_str());
2128 auto& frontNode = childNodes->front();
2129 typeNameBuf = frontNode->GetName();
2130 if (! IsStdArray(typeNameBuf+"<")) {
2131 typeNameBuf = frontNode->ToString();
2132 return true;
2133 }
2134 childNodes = frontNode->GetChildNodes();
2135 }
2136
2137 return true;
2138}
2139
2140
2141////////////////////////////////////////////////////////////////////////////////
2142/// Demangle in a portable way the type id name.
2143/// IMPORTANT: The caller is responsible for freeing the returned const char*
2144
2145char* TClassEdit::DemangleTypeIdName(const std::type_info& ti, int& errorCode)
2146{
2147 const char* mangled_name = ti.name();
2148 return DemangleName(mangled_name, errorCode);
2149}
2150/*
2151/// Result of splitting a function declaration into
2152/// fReturnType fScopeName::fFunctionName<fFunctionTemplateArguments>(fFunctionParameters)
2153struct FunctionSplitInfo {
2154 /// Return type of the function, might be empty if the function declaration string did not provide it.
2155 std::string fReturnType;
2156
2157 /// Name of the scope qualification of the function, possibly empty
2158 std::string fScopeName;
2159
2160 /// Name of the function
2161 std::string fFunctionName;
2162
2163 /// Template arguments of the function template specialization, if any; will contain one element "" for
2164 /// `function<>()`
2165 std::vector<std::string> fFunctionTemplateArguments;
2166
2167 /// Function parameters.
2168 std::vector<std::string> fFunctionParameters;
2169};
2170*/
2171
2172namespace {
2173 /// Find the first occurrence of any of needle's characters in haystack that
2174 /// is not nested in a <>, () or [] pair.
2175 std::size_t FindNonNestedNeedles(std::string_view haystack, string_view needles)
2176 {
2177 std::stack<char> expected;
2178 for (std::size_t pos = 0, end = haystack.length(); pos < end; ++pos) {
2179 char c = haystack[pos];
2180 if (expected.empty()) {
2181 if (needles.find(c) != std::string_view::npos)
2182 return pos;
2183 } else {
2184 if (c == expected.top()) {
2185 expected.pop();
2186 continue;
2187 }
2188 }
2189 switch (c) {
2190 case '<': expected.emplace('>'); break;
2191 case '(': expected.emplace(')'); break;
2192 case '[': expected.emplace(']'); break;
2193 }
2194 }
2195 return std::string_view::npos;
2196 }
2197
2198 /// Find the first occurrence of `::` that is not nested in a <>, () or [] pair.
2199 std::size_t FindNonNestedDoubleColons(std::string_view haystack)
2200 {
2201 std::size_t lenHaystack = haystack.length();
2202 std::size_t prevAfterColumn = 0;
2203 while (true) {
2204 std::size_t posColumn = FindNonNestedNeedles(haystack.substr(prevAfterColumn), ":");
2205 if (posColumn == std::string_view::npos)
2206 return std::string_view::npos;
2207 prevAfterColumn += posColumn;
2208 // prevAfterColumn must have "::", i.e. two characters:
2209 if (prevAfterColumn + 1 >= lenHaystack)
2210 return std::string_view::npos;
2211
2212 ++prevAfterColumn; // done with first (or only) ':'
2213 if (haystack[prevAfterColumn] == ':')
2214 return prevAfterColumn - 1;
2215 ++prevAfterColumn; // That was not a ':'.
2216 }
2217
2218 return std::string_view::npos;
2219 }
2220
2221 std::string_view StripSurroundingSpace(std::string_view str)
2222 {
2223 while (!str.empty() && std::isspace(str[0]))
2224 str.remove_prefix(1);
2225 while (!str.empty() && std::isspace(str.back()))
2226 str.remove_suffix(1);
2227 return str;
2228 }
2229
2230 std::string ToString(std::string_view sv)
2231 {
2232 // ROOT's string_view backport doesn't add the new std::string contructor and assignment;
2233 // convert to std::string instead and assign that.
2234 return std::string(sv.data(), sv.length());
2235 }
2236} // unnamed namespace
2237
2238/// Split a function declaration into its different parts.
2240{
2241 // General structure:
2242 // `...` last-space `...` (`...`)
2243 // The first `...` is the return type.
2244 // The second `...` is the (possibly scoped) function name.
2245 // The third `...` are the parameters.
2246 // The function name can be of the form `...`<`...`>
2247 std::size_t posArgs = FindNonNestedNeedles(decl, "(");
2248 std::string_view declNoArgs = decl.substr(0, posArgs);
2249
2250 std::size_t prevAfterWhiteSpace = 0;
2251 static const char whitespace[] = " \t\n";
2252 while (declNoArgs.length() > prevAfterWhiteSpace) {
2253 std::size_t posWS = FindNonNestedNeedles(declNoArgs.substr(prevAfterWhiteSpace), whitespace);
2254 if (posWS == std::string_view::npos)
2255 break;
2256 prevAfterWhiteSpace += posWS + 1;
2257 while (declNoArgs.length() > prevAfterWhiteSpace
2258 && strchr(whitespace, declNoArgs[prevAfterWhiteSpace]))
2259 ++prevAfterWhiteSpace;
2260 }
2261
2262 /// Include any '&*' in the return type:
2263 std::size_t endReturn = prevAfterWhiteSpace;
2264 while (declNoArgs.length() > endReturn
2265 && strchr("&* \t \n", declNoArgs[endReturn]))
2266 ++endReturn;
2267
2268 result.fReturnType = ToString(StripSurroundingSpace(declNoArgs.substr(0, endReturn)));
2269
2270 /// scope::anotherscope::functionName<tmplt>:
2271 std::string_view scopeFunctionTmplt = declNoArgs.substr(endReturn);
2272 std::size_t prevAtScope = FindNonNestedDoubleColons(scopeFunctionTmplt);
2273 while (prevAtScope != std::string_view::npos
2274 && scopeFunctionTmplt.length() > prevAtScope + 2) {
2275 std::size_t posScope = FindNonNestedDoubleColons(scopeFunctionTmplt.substr(prevAtScope + 2));
2276 if (posScope == std::string_view::npos)
2277 break;
2278 prevAtScope += posScope + 2;
2279 }
2280
2281 std::size_t afterScope = prevAtScope + 2;
2282 if (prevAtScope == std::string_view::npos) {
2283 afterScope = 0;
2284 prevAtScope = 0;
2285 }
2286
2287 result.fScopeName = ToString(StripSurroundingSpace(scopeFunctionTmplt.substr(0, prevAtScope)));
2288 std::string_view funcNameTmplArgs = scopeFunctionTmplt.substr(afterScope);
2289
2290 result.fFunctionTemplateArguments.clear();
2291 std::size_t posTmpltOpen = FindNonNestedNeedles(funcNameTmplArgs, "<");
2292 if (posTmpltOpen != std::string_view::npos) {
2293 result.fFunctionName = ToString(StripSurroundingSpace(funcNameTmplArgs.substr(0, posTmpltOpen)));
2294
2295 // Parse template parameters:
2296 std::string_view tmpltArgs = funcNameTmplArgs.substr(posTmpltOpen + 1);
2297 std::size_t posTmpltClose = FindNonNestedNeedles(tmpltArgs, ">");
2298 if (posTmpltClose != std::string_view::npos) {
2299 tmpltArgs = tmpltArgs.substr(0, posTmpltClose);
2300 std::size_t prevAfterArg = 0;
2301 while (tmpltArgs.length() > prevAfterArg) {
2302 std::size_t posComma = FindNonNestedNeedles(tmpltArgs.substr(prevAfterArg), ",");
2303 if (posComma == std::string_view::npos) {
2304 break;
2305 }
2306 result.fFunctionTemplateArguments.emplace_back(ToString(StripSurroundingSpace(tmpltArgs.substr(prevAfterArg, posComma))));
2307 prevAfterArg += posComma + 1;
2308 }
2309 // Add the trailing arg.
2310 result.fFunctionTemplateArguments.emplace_back(ToString(StripSurroundingSpace(tmpltArgs.substr(prevAfterArg))));
2311 }
2312 } else {
2313 result.fFunctionName = ToString(StripSurroundingSpace(funcNameTmplArgs));
2314 }
2315
2316 result.fFunctionParameters.clear();
2317 if (posArgs != std::string_view::npos) {
2318 /// (params)
2319 std::string_view params = decl.substr(posArgs + 1);
2320 std::size_t posEndArgs = FindNonNestedNeedles(params, ")");
2321 if (posEndArgs != std::string_view::npos) {
2322 params = params.substr(0, posEndArgs);
2323 std::size_t prevAfterArg = 0;
2324 while (params.length() > prevAfterArg) {
2325 std::size_t posComma = FindNonNestedNeedles(params.substr(prevAfterArg), ",");
2326 if (posComma == std::string_view::npos) {
2327 result.fFunctionParameters.emplace_back(ToString(StripSurroundingSpace(params.substr(prevAfterArg))));
2328 break;
2329 }
2330 result.fFunctionParameters.emplace_back(ToString(StripSurroundingSpace(params.substr(prevAfterArg, posComma))));
2331 prevAfterArg += posComma + 1; // skip ','
2332 }
2333 }
2334 }
2335
2336 return true;
2337}
#define b(i)
Definition RSha256.hxx:100
#define c(i)
Definition RSha256.hxx:101
#define a(i)
Definition RSha256.hxx:99
#define e(i)
Definition RSha256.hxx:103
static void R__FindTrailing(std::string &full, std::string &stars)
static void ResolveTypedefImpl(const char *tname, unsigned int len, unsigned int &cursor, bool &modified, std::string &result)
static size_t findNameEnd(const std::string_view full)
static bool IsDefElement(const char *elementName, const char *defaultElementName, const char *classname)
return whether or not 'elementName' is the STL default Element for type 'classname'
static void ResolveTypedefProcessType(const char *tname, unsigned int, unsigned int cursor, bool constprefix, unsigned int start_of_type, unsigned int end_of_type, unsigned int mod_start_of_type, bool &modified, std::string &result)
static void RemoveStd(std::string &name, size_t pos=0)
Remove std:: and any potential inline namespace (well compiler detail namespace.
static size_t StdLen(const std::string_view name)
Return the length, if any, taken by std:: and any potential inline namespace (well compiler detail na...
XFontStruct * id
Definition TGX11.cxx:109
char name[80]
Definition TGX11.cxx:110
int type
Definition TGX11.cxx:121
A spin mutex-as-code-guard class.
virtual bool GetPartiallyDesugaredNameWithScopeHandling(const std::string &, std::string &, bool=true)=0
virtual bool IsAlreadyPartiallyDesugaredName(const std::string &, const std::string &)=0
virtual bool IsDeclaredScope(const std::string &, bool &)=0
virtual void GetPartiallyDesugaredName(std::string &)=0
virtual bool ExistingTypeCheck(const std::string &, std::string &)=0
const Int_t n
Definition legend1.C:16
basic_string_view< char > string_view
double T(double x)
std::string ToString(const T &val)
Utility function for conversion to strings.
Definition Util.h:50
ESTLType
Definition ESTLType.h:28
@ kSTLbitset
Definition ESTLType.h:37
@ kSTLmap
Definition ESTLType.h:33
@ kSTLunorderedmultiset
Definition ESTLType.h:43
@ kSTLset
Definition ESTLType.h:35
@ kSTLmultiset
Definition ESTLType.h:36
@ kSTLdeque
Definition ESTLType.h:32
@ kSTLvector
Definition ESTLType.h:30
@ kSTLunorderedmultimap
Definition ESTLType.h:45
@ kSTLunorderedset
Definition ESTLType.h:42
@ kSTLlist
Definition ESTLType.h:31
@ kSTLforwardlist
Definition ESTLType.h:41
@ kSTLunorderedmap
Definition ESTLType.h:44
@ kNotSTL
Definition ESTLType.h:29
@ kSTLmultimap
Definition ESTLType.h:34
ROOT::ESTLType STLKind(std::string_view type)
Converts STL container name to number.
bool IsDefComp(const char *comp, const char *classname)
return whether or not 'compare' is the STL default comparator for type 'classname'
std::string ResolveTypedef(const char *tname, bool resolveAll=false)
std::string CleanType(const char *typeDesc, int mode=0, const char **tail=0)
Cleanup type description, redundant blanks removed and redundant tail ignored return *tail = pointer ...
bool IsStdArray(std::string_view name)
Definition TClassEdit.h:188
bool IsStdClass(const char *type)
return true if the class belongs to the std namespace
bool IsDefHash(const char *hashname, const char *classname)
return whether or not 'hashname' is the STL default hash for type 'classname'
bool IsStdPair(std::string_view name)
Definition TClassEdit.h:190
bool IsInterpreterDetail(const char *type)
Return true if the type is one the interpreter details which are only forward declared (ClassInfo_t e...
std::string InsertStd(const char *tname)
bool SplitFunction(std::string_view decl, FunctionSplitInfo &result)
Split a function declaration into its different parts.
std::string GetLong64_Name(const char *original)
Replace 'long long' and 'unsigned long long' by 'Long64_t' and 'ULong64_t'.
bool IsDefPred(const char *predname, const char *classname)
return whether or not 'predname' is the STL default predicate for type 'classname'
char * DemangleTypeIdName(const std::type_info &ti, int &errorCode)
Demangle in a portable way the type id name.
const char * GetUnqualifiedName(const char *name)
Return the start of the unqualified name include in 'original'.
bool IsVectorBool(const char *name)
void Init(TClassEdit::TInterpreterLookupHelper *helper)
ROOT::ESTLType IsSTLCont(std::string_view type)
type : type name: vector<list<classA,allocator>,allocator> result: 0 : not stl container code of cont...
std::string ShortType(const char *typeDesc, int mode)
Return the absolute type of typeDesc.
char * DemangleName(const char *mangled_name, int &errorCode)
Definition TClassEdit.h:217
bool IsArtificial(std::string_view name)
Definition TClassEdit.h:158
bool GetStdArrayProperties(const char *typeName, std::string &typeNameBuf, std::array< int, 5 > &maxIndices, int &ndim)
std::string GetNameForIO(const std::string &templateInstanceName, TClassEdit::EModType mode=TClassEdit::kNone, bool *hasChanged=nullptr)
int STLArgs(int kind)
Return number of arguments for STL container before allocator.
int GetSplit(const char *type, std::vector< std::string > &output, int &nestedLoc, EModType mode=TClassEdit::kNone)
Stores in output (after emptying it) the split type.
void GetNormalizedName(std::string &norm_name, std::string_view name)
Return the normalized name.
bool IsDefAlloc(const char *alloc, const char *classname)
return whether or not 'allocname' is the STL default allocator for type 'classname'
bool IsUniquePtr(std::string_view name)
Definition TClassEdit.h:186
@ kDropDefaultAlloc
Definition TClassEdit.h:77
@ kResolveTypedef
Definition TClassEdit.h:87
@ kDropComparator
Definition TClassEdit.h:82
@ kDropAllDefault
Definition TClassEdit.h:83
@ kKeepOuterConst
Definition TClassEdit.h:86
@ kDropStlDefault
Definition TClassEdit.h:81
bool IsSTLBitset(const char *type)
Return true is the name is std::bitset<number> or bitset<number>
ROOT::ESTLType UnderlyingIsSTLCont(std::string_view type)
Return the type of STL collection, if any, that is the underlying type of the given type.
EComplexType GetComplexType(const char *)
Definition first.py:1
Result of splitting a function declaration into fReturnType fScopeName::fFunctionName<fFunctionTempla...
Definition TClassEdit.h:249
std::string fFunctionName
Name of the function.
Definition TClassEdit.h:257
std::vector< std::string > fFunctionTemplateArguments
Template arguments of the function template specialization, if any; will contain one element "" for f...
Definition TClassEdit.h:261
std::string fScopeName
Name of the scope qualification of the function, possibly empty.
Definition TClassEdit.h:254
std::vector< std::string > fFunctionParameters
Function parameters.
Definition TClassEdit.h:264
std::string fReturnType
Return type of the function, might be empty if the function declaration string did not provide it.
Definition TClassEdit.h:251
bool IsTemplate()
Check if the type is a template.
int IsSTLCont(int testAlloc=0) const
type : type name: vector<list<classA,allocator>,allocator> testAlloc: if true, we test allocator,...
TSplitType(const char *type2split, EModType mode=TClassEdit::kNone)
default constructor
std::vector< std::string > fElements
Definition TClassEdit.h:140
ROOT::ESTLType IsInSTL() const
type : type name: vector<list<classA,allocator>,allocator>[::iterator] result: 0 : not stl container ...
void ShortType(std::string &answer, int mode)
Return the absolute type of typeDesc into the string answ.
static void output(int code)
Definition gifencode.c:226