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