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 <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 using namespace std;
31 
32 namespace {
33  static TClassEdit::TInterpreterLookupHelper *gInterpreterHelper = nullptr;
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 
51 static 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 
98 static 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 
162 TClassEdit::TSplitType::TSplitType(const char *type2split, EModType mode) : fName(type2split), fNestedLocation(0)
163 {
164  TClassEdit::GetSplit(type2split, fElements, fNestedLocation, mode);
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 
189 int 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 
229 ////////////////////////////////////////////////////////////////////////////////
230 //////////////////////////////////////////////////////////////////////////////
231 /// Return the absolute type of typeDesc into the string answ.
232 
233 void 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:
314  case ROOT::kSTLmultiset:
317  dropAlloc = IsDefAlloc(fElements[iall+1].c_str(),fElements[1].c_str());
318  break;
319  case ROOT::kSTLmap:
320  case ROOT::kSTLmultimap:
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:
353  case ROOT::kSTLmultiset:
354  case ROOT::kSTLmap:
355  case ROOT::kSTLmultimap:
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 
555 int TClassEdit::STLArgs(int kind)
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 
568 static 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 
591 static 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 
600 bool 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 
649 bool 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 
756 static 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  TClassEdit::GetNormalizedName(keypart,std::string_view(c.c_str()+pos,end-pos));
775 
776  std::string norm_key;
777  TClassEdit::GetNormalizedName(norm_key,k);
778 
779  if (keypart != norm_key) {
780  return false;
781  }
782  pos = end;
783  } else {
784  pos += k.length();
785  }
786 
787  if (c.compare(pos,1,">")!=0 && c.compare(pos,2," >")!=0) {
788  return false;
789  }
790 
791  return true;
792 }
793 
794 ////////////////////////////////////////////////////////////////////////////////
795 /// return whether or not 'compare' is the STL default comparator for type
796 /// 'classname'
797 
798 bool TClassEdit::IsDefComp(const char *compname, const char *classname)
799 {
800  return IsDefElement(compname, "less<", classname);
801 }
802 
803 ////////////////////////////////////////////////////////////////////////////////
804 /// return whether or not 'predname' is the STL default predicate for type
805 /// 'classname'
806 
807 bool TClassEdit::IsDefPred(const char *predname, const char *classname)
808 {
809  return IsDefElement(predname, "equal_to<", classname);
810 }
811 
812 ////////////////////////////////////////////////////////////////////////////////
813 /// return whether or not 'hashname' is the STL default hash for type
814 /// 'classname'
815 
816 bool TClassEdit::IsDefHash(const char *hashname, const char *classname)
817 {
818  return IsDefElement(hashname, "hash<", classname);
819 }
820 
821 ////////////////////////////////////////////////////////////////////////////////
822 /// Return the normalized name. See TMetaUtils::GetNormalizedName.
823 ///
824 /// Return the type name normalized for ROOT,
825 /// keeping only the ROOT opaque typedef (Double32_t, etc.) and
826 /// removing the STL collections default parameter if any.
827 ///
828 /// Compare to TMetaUtils::GetNormalizedName, this routines does not
829 /// and can not add default template parameters.
830 
832 {
833  norm_name = std::string(name); // NOTE: Is that the shortest version?
834 
835  // Remove the std:: and default template argument and insert the Long64_t and change basic_string to string.
838 
839  // Depending on how the user typed their code, in particular typedef
840  // declarations, we may end up with an explicit '::' being
841  // part of the result string. For consistency, we must remove it.
842  if (norm_name.length()>2 && norm_name[0]==':' && norm_name[1]==':') {
843  norm_name.erase(0,2);
844  }
845 
846  if (gInterpreterHelper) {
847  // See if the expanded name itself is a typedef.
848  std::string typeresult;
849  if (gInterpreterHelper->ExistingTypeCheck(norm_name, typeresult)
850  || gInterpreterHelper->GetPartiallyDesugaredNameWithScopeHandling(norm_name, typeresult)) {
851 
852  if (!typeresult.empty()) norm_name = typeresult;
853  }
854  }
855 }
856 
857 ////////////////////////////////////////////////////////////////////////////////
858 /// Replace 'long long' and 'unsigned long long' by 'Long64_t' and 'ULong64_t'
859 
860 string TClassEdit::GetLong64_Name(const char* original)
861 {
862  if (original==0)
863  return "";
864  else
865  return GetLong64_Name(string(original));
866 }
867 
868 ////////////////////////////////////////////////////////////////////////////////
869 /// Replace 'long long' and 'unsigned long long' by 'Long64_t' and 'ULong64_t'
870 
871 string TClassEdit::GetLong64_Name(const string& original)
872 {
873  static const char* longlong_s = "long long";
874  static const char* ulonglong_s = "unsigned long long";
875  static const unsigned int longlong_len = strlen(longlong_s);
876  static const unsigned int ulonglong_len = strlen(ulonglong_s);
877 
878  string result = original;
879 
880  int pos = 0;
881  while( (pos = result.find(ulonglong_s,pos) ) >=0 ) {
882  result.replace(pos, ulonglong_len, "ULong64_t");
883  }
884  pos = 0;
885  while( (pos = result.find(longlong_s,pos) ) >=0 ) {
886  result.replace(pos, longlong_len, "Long64_t");
887  }
888  return result;
889 }
890 
891 ////////////////////////////////////////////////////////////////////////////////
892 /// Return the start of the unqualified name include in 'original'.
893 
894 const char *TClassEdit::GetUnqualifiedName(const char *original)
895 {
896  const char *lastPos = original;
897  {
898  long depth = 0;
899  for(auto cursor = original; *cursor != '\0'; ++cursor) {
900  if ( *cursor == '<' || *cursor == '(') ++depth;
901  else if ( *cursor == '>' || *cursor == ')' ) --depth;
902  else if ( *cursor == ':' ) {
903  if (depth==0 && *(cursor+1) == ':' && *(cursor+2) != '\0') {
904  lastPos = cursor+2;
905  }
906  }
907  }
908  }
909  return lastPos;
910 }
911 
912 ////////////////////////////////////////////////////////////////////////////////
913 
914 static void R__FindTrailing(std::string &full, /*modified*/
915  std::string &stars /* the literal output */
916  )
917 {
918  const char *t = full.c_str();
919  const unsigned int tlen( full.size() );
920 
921  const char *starloc = t + tlen - 1;
922  bool hasconst = false;
923  if ( (*starloc)=='t'
924  && (starloc-t) > 4 && 0 == strncmp((starloc-4),"const",5)
925  && ( (*(starloc-5)) == ' ' || (*(starloc-5)) == '*' || (*(starloc-5)) == '&'
926  || (*(starloc-5)) == '>' || (*(starloc-5)) == ']') ) {
927  // we are ending on a const.
928  starloc -= 4;
929  if ((*starloc-1)==' ') {
930  // Take the space too.
931  starloc--;
932  }
933  hasconst = true;
934  }
935  if ( hasconst || (*starloc)=='*' || (*starloc)=='&' || (*starloc)==']' ) {
936  bool isArray = ( (*starloc)==']' );
937  while( t<=(starloc-1) && ((*(starloc-1))=='*' || (*(starloc-1))=='&' || (*(starloc-1))=='t' || isArray)) {
938  if (isArray) {
939  starloc--;
940  isArray = ! ( (*starloc)=='[' );
941  } else if ( (*(starloc-1))=='t' ) {
942  if ( (starloc-1-t) > 5 && 0 == strncmp((starloc-5),"const",5)
943  && ( (*(starloc-6)) == ' ' || (*(starloc-6)) == '*' || (*(starloc-6)) == '&'
944  || (*(starloc-6)) == '>' || (*(starloc-6)) == ']')) {
945  // we have a const.
946  starloc -= 5;
947  } else {
948  break;
949  }
950  } else {
951  starloc--;
952  }
953  }
954  stars = starloc;
955  if ((*(starloc-1))==' ') {
956  // erase the space too.
957  starloc--;
958  }
959 
960  const unsigned int starlen = strlen(starloc);
961  full.erase(tlen-starlen,starlen);
962  } else if (hasconst) {
963  stars = starloc;
964  const unsigned int starlen = strlen(starloc);
965  full.erase(tlen-starlen,starlen);
966  }
967 
968 }
969 
970 ////////////////////////////////////////////////////////////////////////////////
971 ////////////////////////////////////////////////////////////////////////////
972 /// Stores in output (after emptying it) the split type.
973 /// Stores the location of the tail (nested names) in nestedLoc (0 indicates no tail).
974 /// Return the number of elements stored.
975 ///
976 /// First in list is the template name or is empty
977 /// "vector<list<int>,alloc>**" to "vector" "list<int>" "alloc" "**"
978 /// or "TNamed*" to "" "TNamed" "*"
979 ////////////////////////////////////////////////////////////////////////////
980 
981 int TClassEdit::GetSplit(const char *type, vector<string>& output, int &nestedLoc, EModType mode)
982 {
983  nestedLoc = 0;
984  output.clear();
985  if (strlen(type)==0) return 0;
986 
987  int cleantypeMode = 1 /* keepInnerConst */;
988  if (mode & kKeepOuterConst) {
989  cleantypeMode = 0; /* remove only the outer class keyword */
990  }
991  string full( mode & kLong64 ? TClassEdit::GetLong64_Name( CleanType(type, cleantypeMode) )
992  : CleanType(type, cleantypeMode) );
993 
994  // We need to replace basic_string with string.
995  {
996  unsigned int const_offset = (0==strncmp("const ",full.c_str(),6)) ? 6 : 0;
997  bool isString = false;
998  bool isStdString = false;
999  size_t std_offset = const_offset;
1000  static const char* basic_string_std = "std::basic_string<char";
1001  static const unsigned int basic_string_std_len = strlen(basic_string_std);
1002 
1003  if (full.compare(const_offset,basic_string_std_len,basic_string_std) == 0
1004  && full.size() > basic_string_std_len) {
1005  isString = true;
1006  isStdString = true;
1007  std_offset += 5;
1008  } else if (full.compare(const_offset,basic_string_std_len-5,basic_string_std+5) == 0
1009  && full.size() > (basic_string_std_len-5)) {
1010  // no std.
1011  isString = true;
1012  } else if (full.find("basic_string") != std::string::npos) {
1013  size_t len = StdLen(full.c_str() + const_offset);
1014  if (len && len != 5 && full.compare(const_offset + len, basic_string_std_len-5, basic_string_std+5) == 0) {
1015  isString = true;
1016  isStdString = true;
1017  std_offset += len;
1018  }
1019  }
1020  if (isString) {
1021  size_t offset = basic_string_std_len - 5;
1022  offset += std_offset; // std_offset includs both the size of std prefix and const prefix.
1023  if ( full[offset] == '>' ) {
1024  // done.
1025  } else if (full[offset] == ',') {
1026  ++offset;
1027  if (full.compare(offset, 5, "std::") == 0) {
1028  offset += 5;
1029  }
1030  static const char* char_traits_s = "char_traits<char>";
1031  static const unsigned int char_traits_len = strlen(char_traits_s);
1032  if (full.compare(offset, char_traits_len, char_traits_s) == 0) {
1033  offset += char_traits_len;
1034  if ( full[offset] == '>') {
1035  // done.
1036  } else if (full[offset] == ' ' && full[offset+1] == '>') {
1037  ++offset;
1038  // done.
1039  } else if (full[offset] == ',') {
1040  ++offset;
1041  if (full.compare(offset, 5, "std::") == 0) {
1042  offset += 5;
1043  }
1044  static const char* allocator_s = "allocator<char>";
1045  static const unsigned int allocator_len = strlen(allocator_s);
1046  if (full.compare(offset, allocator_len, allocator_s) == 0) {
1047  offset += allocator_len;
1048  if ( full[offset] == '>') {
1049  // done.
1050  } else if (full[offset] == ' ' && full[offset+1] == '>') {
1051  ++offset;
1052  // done.
1053  } else {
1054  // Not std::string
1055  isString = false;
1056  }
1057  }
1058  } else {
1059  // Not std::string
1060  isString = false;
1061  }
1062  } else {
1063  // Not std::string.
1064  isString = false;
1065  }
1066  } else {
1067  // Not std::string.
1068  isString = false;
1069  }
1070  if (isString) {
1071  output.push_back(string());
1072  if (const_offset && (mode & kKeepOuterConst)) {
1073  if (isStdString && !(mode & kDropStd)) {
1074  output.push_back("const std::string");
1075  } else {
1076  output.push_back("const string");
1077  }
1078  } else {
1079  if (isStdString && !(mode & kDropStd)) {
1080  output.push_back("std::string");
1081  } else {
1082  output.push_back("string");
1083  }
1084  }
1085  if (offset < full.length()) {
1086  // Copy the trailing text.
1087  // keep the '>' inside right for R__FindTrailing to work
1088  string right( full.substr(offset) );
1089  string stars;
1090  R__FindTrailing(right, stars);
1091  output.back().append(right.c_str()+1); // skip the '>'
1092  output.push_back(stars);
1093  } else {
1094  output.push_back("");
1095  }
1096  return output.size();
1097  }
1098  }
1099  }
1100 
1101  if ( mode & kDropStd) {
1102  unsigned int offset = (0==strncmp("const ",full.c_str(),6)) ? 6 : 0;
1103  RemoveStd( full, offset );
1104  }
1105 
1106  string stars;
1107  if ( !full.empty() ) {
1108  R__FindTrailing(full, stars);
1109  }
1110 
1111  const char *c = strchr(full.c_str(),'<');
1112  if (c) {
1113  //we have 'something<'
1114  output.push_back(string(full,0,c - full.c_str()));
1115 
1116  const char *cursor;
1117  int level = 0;
1118  for(cursor = c + 1; *cursor != '\0' && !(level==0 && *cursor == '>'); ++cursor) {
1119  switch (*cursor) {
1120  case '<': ++level; break;
1121  case '>': --level; break;
1122  case ',':
1123  if (level == 0) {
1124  output.push_back(std::string(c+1,cursor));
1125  c = cursor;
1126  }
1127  break;
1128  }
1129  }
1130  if (*cursor=='>') {
1131  if (*(cursor-1) == ' ') {
1132  output.push_back(std::string(c+1,cursor-1));
1133  } else {
1134  output.push_back(std::string(c+1,cursor));
1135  }
1136  // See what's next!
1137  if (*(cursor+1)==':') {
1138  // we have a name specified inside the class/namespace
1139  // For now we keep it in one piece
1140  nestedLoc = output.size();
1141  output.push_back((cursor+1));
1142  }
1143  } else if (level >= 0) {
1144  // Unterminated template
1145  output.push_back(std::string(c+1,cursor));
1146  }
1147  } else {
1148  //empty
1149  output.push_back(string());
1150  output.push_back(full);
1151  }
1152 
1153  if (!output.empty()) output.push_back(stars);
1154  return output.size();
1155 }
1156 
1157 
1158 ////////////////////////////////////////////////////////////////////////////////
1159 ////////////////////////////////////////////////////////////////////////////
1160 /// Cleanup type description, redundant blanks removed
1161 /// and redundant tail ignored
1162 /// return *tail = pointer to last used character
1163 /// if (mode==0) keep keywords
1164 /// if (mode==1) remove keywords outside the template params
1165 /// if (mode>=2) remove the keywords everywhere.
1166 /// if (tail!=0) cut before the trailing *
1167 ///
1168 /// The keywords currently are: "const" , "volatile" removed
1169 ///
1170 ///
1171 /// CleanType(" A<B, C< D, E> > *,F,G>") returns "A<B,C<D,E> >*"
1172 ////////////////////////////////////////////////////////////////////////////
1173 
1174 string TClassEdit::CleanType(const char *typeDesc, int mode, const char **tail)
1175 {
1176  static const char* remove[] = {"class","const","volatile",0};
1177  static bool isinit = false;
1178  static std::vector<size_t> lengths;
1179  if (!isinit) {
1180  for (int k=0; remove[k]; ++k) {
1181  lengths.push_back(strlen(remove[k]));
1182  }
1183  isinit = true;
1184  }
1185 
1186  string result;
1187  result.reserve(strlen(typeDesc)*2);
1188  int lev=0,kbl=1;
1189  const char* c;
1190 
1191  for(c=typeDesc;*c;c++) {
1192  if (c[0]==' ') {
1193  if (kbl) continue;
1194  if (!isalnum(c[ 1]) && c[ 1] !='_') continue;
1195  }
1196  if (kbl && (mode>=2 || lev==0)) { //remove "const' etc...
1197  int done = 0;
1198  int n = (mode) ? 999 : 1;
1199 
1200  // loop on all the keywords we want to remove
1201  for (int k=0; k<n && remove[k]; k++) {
1202  int rlen = lengths[k];
1203 
1204  // Do we have a match
1205  if (strncmp(remove[k],c,rlen)) continue;
1206 
1207  // make sure that the 'keyword' is not part of a longer indentifier
1208  if (isalnum(c[rlen]) || c[rlen]=='_' || c[rlen]=='$') continue;
1209 
1210  c+=rlen-1; done = 1; break;
1211  }
1212  if (done) continue;
1213  }
1214 
1215  kbl = (!isalnum(c[ 0]) && c[ 0]!='_' && c[ 0]!='$' && c[0]!='[' && c[0]!=']' && c[0]!='-' && c[0]!='@');
1216  // '@' is special character used only the artifical class name used by ROOT to implement the
1217  // I/O customization rules that requires caching of the input data.
1218 
1219  if (*c == '<' || *c == '(') lev++;
1220  if (lev==0 && !isalnum(*c)) {
1221  if (!strchr("*&:._$ []-@",*c)) break;
1222  // '.' is used as a module/namespace separator by PyROOT, see
1223  // TPyClassGenerator::GetClass.
1224  }
1225  if (c[0]=='>' && result.size() && result[result.size()-1]=='>') result+=" ";
1226 
1227  result += c[0];
1228 
1229  if (*c == '>' || *c == ')') lev--;
1230  }
1231  if(tail) *tail=c;
1232  return result;
1233 }
1234 
1235 ////////////////////////////////////////////////////////////////////////////////
1236 //////////////////////////////////////////////////////////////////////////////
1237 /// Return the absolute type of typeDesc.
1238 /// E.g.: typeDesc = "class const volatile TNamed**", returns "TNamed**".
1239 /// if (mode&1) remove last "*"s returns "TNamed"
1240 /// if (mode&2) remove default allocators from STL containers
1241 /// if (mode&4) remove all allocators from STL containers
1242 /// if (mode&8) return inner class of stl container. list<innerClass>
1243 /// if (mode&16) return deapest class of stl container. vector<list<deapest>>
1244 /// if (mode&kDropAllDefault) remove default template arguments
1245 //////////////////////////////////////////////////////////////////////////////
1246 
1247 string TClassEdit::ShortType(const char *typeDesc, int mode)
1248 {
1249  string answer;
1250 
1251  // get list of all arguments
1252  if (typeDesc) {
1253  TSplitType arglist(typeDesc, (EModType) mode);
1254  arglist.ShortType(answer, mode);
1255  }
1256 
1257  return answer;
1258 }
1259 
1260 ////////////////////////////////////////////////////////////////////////////////
1261 /// Return true if the type is one the interpreter details which are
1262 /// only forward declared (ClassInfo_t etc..)
1263 
1265 {
1266  size_t len = strlen(type);
1267  if (len < 2 || strncmp(type+len-2,"_t",2) != 0) return false;
1268 
1269  unsigned char offset = 0;
1270  if (strncmp(type,"const ",6)==0) { offset += 6; }
1271  static const char *names[] = { "CallFunc_t","ClassInfo_t","BaseClassInfo_t",
1272  "DataMemberInfo_t","FuncTempInfo_t","MethodInfo_t","MethodArgInfo_t",
1273  "TypeInfo_t","TypedefInfo_t",0};
1274 
1275  for(int k=1;names[k];k++) {if (strcmp(type+offset,names[k])==0) return true;}
1276  return false;
1277 }
1278 
1279 ////////////////////////////////////////////////////////////////////////////////
1280 /// Return true is the name is std::bitset<number> or bitset<number>
1281 
1282 bool TClassEdit::IsSTLBitset(const char *classname)
1283 {
1284  size_t offset = StdLen(classname);
1285  if ( strncmp(classname+offset,"bitset<",strlen("bitset<"))==0) return true;
1286  return false;
1287 }
1288 
1289 ////////////////////////////////////////////////////////////////////////////////
1290 /// Return the type of STL collection, if any, that is the underlying type
1291 /// of the given type. Namely return the value of IsSTLCont after stripping
1292 /// pointer, reference and constness from the type.
1293 /// UnderlyingIsSTLCont("vector<int>*") == IsSTLCont("vector<int>")
1294 /// See TClassEdit::IsSTLCont
1295 ///
1296 /// type : type name: vector<list<classA,allocator>,allocator>*
1297 /// result: 0 : not stl container
1298 /// code of container 1=vector,2=list,3=deque,4=map
1299 /// 5=multimap,6=set,7=multiset
1300 
1302 {
1303  if (type.compare(0,6,"const ",6) == 0)
1304  type.remove_prefix(6);
1305 
1306  while(type[type.length()-1]=='*' ||
1307  type[type.length()-1]=='&' ||
1308  type[type.length()-1]==' ') {
1309  type.remove_suffix(1);
1310  }
1311  return IsSTLCont(type);
1312 }
1313 
1314 ////////////////////////////////////////////////////////////////////////////////
1315 /// type : type name: vector<list<classA,allocator>,allocator>
1316 /// result: 0 : not stl container
1317 /// code of container 1=vector,2=list,3=deque,4=map
1318 /// 5=multimap,6=set,7=multiset
1319 
1321 {
1322  auto pos = type.find('<');
1323  if (pos==std::string_view::npos) return ROOT::kNotSTL;
1324 
1325  auto c = pos+1;
1326  for (decltype(type.length()) level = 1; c < type.length(); ++c) {
1327  if (type[c] == '<') ++level;
1328  if (type[c] == '>') --level;
1329  if (level == 0) break;
1330  }
1331  if (c != (type.length()-1) ) {
1332  return ROOT::kNotSTL;
1333  }
1334 
1335  return STLKind(type.substr(0,pos));
1336 }
1337 
1338 ////////////////////////////////////////////////////////////////////////////////
1339 /// type : type name: vector<list<classA,allocator>,allocator>
1340 /// testAlloc: if true, we test allocator, if it is not default result is negative
1341 /// result: 0 : not stl container
1342 /// abs(result): code of container 1=vector,2=list,3=deque,4=map
1343 /// 5=multimap,6=set,7=multiset
1344 /// positive val: we have a vector or list with default allocator to any depth
1345 /// like vector<list<vector<int>>>
1346 /// negative val: STL container other than vector or list, or non default allocator
1347 /// For example: vector<deque<int>> has answer -1
1348 
1349 int TClassEdit::IsSTLCont(const char *type, int testAlloc)
1350 {
1351  if (strchr(type,'<')==0) return 0;
1352 
1353  TSplitType arglist( type );
1354  return arglist.IsSTLCont(testAlloc);
1355 }
1356 
1357 ////////////////////////////////////////////////////////////////////////////////
1358 /// return true if the class belongs to the std namespace
1359 
1360 bool TClassEdit::IsStdClass(const char *classname)
1361 {
1362  classname += StdLen( classname );
1363  if ( strcmp(classname,"string")==0 ) return true;
1364  if ( strncmp(classname,"bitset<",strlen("bitset<"))==0) return true;
1365  if ( strncmp(classname,"pair<",strlen("pair<"))==0) return true;
1366  if ( strcmp(classname,"allocator")==0) return true;
1367  if ( strncmp(classname,"allocator<",strlen("allocator<"))==0) return true;
1368  if ( strncmp(classname,"greater<",strlen("greater<"))==0) return true;
1369  if ( strncmp(classname,"less<",strlen("less<"))==0) return true;
1370  if ( strncmp(classname,"equal_to<",strlen("equal_to<"))==0) return true;
1371  if ( strncmp(classname,"hash<",strlen("hash<"))==0) return true;
1372  if ( strncmp(classname,"auto_ptr<",strlen("auto_ptr<"))==0) return true;
1373 
1374  if ( strncmp(classname,"vector<",strlen("vector<"))==0) return true;
1375  if ( strncmp(classname,"list<",strlen("list<"))==0) return true;
1376  if ( strncmp(classname,"forward_list<",strlen("forward_list<"))==0) return true;
1377  if ( strncmp(classname,"deque<",strlen("deque<"))==0) return true;
1378  if ( strncmp(classname,"map<",strlen("map<"))==0) return true;
1379  if ( strncmp(classname,"multimap<",strlen("multimap<"))==0) return true;
1380  if ( strncmp(classname,"set<",strlen("set<"))==0) return true;
1381  if ( strncmp(classname,"multiset<",strlen("multiset<"))==0) return true;
1382  if ( strncmp(classname,"unordered_set<",strlen("unordered_set<"))==0) return true;
1383  if ( strncmp(classname,"unordered_multiset<",strlen("unordered_multiset<"))==0) return true;
1384  if ( strncmp(classname,"unordered_map<",strlen("unordered_map<"))==0) return true;
1385  if ( strncmp(classname,"unordered_multimap<",strlen("unordered_multimap<"))==0) return true;
1386  if ( strncmp(classname,"bitset<",strlen("bitset<"))==0) return true;
1387 
1388  return false;
1389 }
1390 
1391 
1392 ////////////////////////////////////////////////////////////////////////////////
1393 
1394 bool TClassEdit::IsVectorBool(const char *name) {
1395  TSplitType splitname( name );
1396 
1397  return ( TClassEdit::STLKind( splitname.fElements[0] ) == ROOT::kSTLvector)
1398  && ( splitname.fElements[1] == "bool" || splitname.fElements[1]=="Bool_t");
1399 }
1400 
1401 ////////////////////////////////////////////////////////////////////////////////
1402 
1403 static void ResolveTypedefProcessType(const char *tname,
1404  unsigned int /* len */,
1405  unsigned int cursor,
1406  bool constprefix,
1407  unsigned int start_of_type,
1408  unsigned int end_of_type,
1409  unsigned int mod_start_of_type,
1410  bool &modified,
1411  std::string &result)
1412 {
1413  std::string type(modified && (mod_start_of_type < result.length()) ?
1414  result.substr(mod_start_of_type, string::npos)
1415  : 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
1416  string typeresult;
1417  if (gInterpreterHelper->ExistingTypeCheck(type, typeresult)
1418  || gInterpreterHelper->GetPartiallyDesugaredNameWithScopeHandling(type, typeresult, false)) {
1419  // it is a known type
1420  if (!typeresult.empty()) {
1421  // and it is a typedef, we need to replace it in the output.
1422  if (modified) {
1423  result.replace(mod_start_of_type, string::npos,
1424  typeresult);
1425  }
1426  else {
1427  modified = true;
1428  mod_start_of_type = start_of_type;
1429  result += string(tname,0,start_of_type);
1430  if (constprefix && typeresult.compare(0,6,"const ",6) == 0) {
1431  result += typeresult.substr(6,string::npos);
1432  } else {
1433  result += typeresult;
1434  }
1435  }
1436  } else if (modified) {
1437  result.replace(mod_start_of_type, string::npos,
1438  type);
1439  }
1440  if (modified) {
1441  if (end_of_type != 0 && end_of_type!=cursor) {
1442  result += std::string(tname,end_of_type,cursor-end_of_type);
1443  }
1444  }
1445  } else {
1446  // no change needed.
1447  if (modified) {
1448  // result += type;
1449  if (end_of_type != 0 && end_of_type!=cursor) {
1450  result += std::string(tname,end_of_type,cursor-end_of_type);
1451  }
1452  }
1453  }
1454 }
1455 
1456 ////////////////////////////////////////////////////////////////////////////////
1457 
1458 static void ResolveTypedefImpl(const char *tname,
1459  unsigned int len,
1460  unsigned int &cursor,
1461  bool &modified,
1462  std::string &result)
1463 {
1464  // Need to parse and deal with
1465  // A::B::C< D, E::F, G::H<I,J>::K::L >::M
1466  // where E might be replace by N<O,P>
1467  // and G::H<I,J>::K or G might be a typedef.
1468 
1469  bool constprefix = false;
1470 
1471  if (tname[cursor]==' ') {
1472  if (!modified) {
1473  modified = true;
1474  result += string(tname,0,cursor);
1475  }
1476  while (tname[cursor]==' ') ++cursor;
1477  }
1478 
1479  if (tname[cursor]=='c' && (cursor+6<len)) {
1480  if (strncmp(tname+cursor,"const ",6) == 0) {
1481  cursor += 6;
1482  if (modified) result += "const ";
1483  }
1484  constprefix = true;
1485 
1486  }
1487 
1488  if (len > 2 && strncmp(tname+cursor,"::",2) == 0) {
1489  cursor += 2;
1490  }
1491 
1492  unsigned int start_of_type = cursor;
1493  unsigned int end_of_type = 0;
1494  unsigned int mod_start_of_type = result.length();
1495  unsigned int prevScope = cursor;
1496  for ( ; cursor<len; ++cursor) {
1497  switch (tname[cursor]) {
1498  case ':': {
1499  if ((cursor+1)>=len || tname[cursor+1]!=':') {
1500  // we expected another ':', malformed, give up.
1501  if (modified) result += (tname+prevScope);
1502  return;
1503  }
1504  string scope;
1505  if (modified) {
1506  scope = result.substr(mod_start_of_type, string::npos);
1507  scope += std::string(tname+prevScope,cursor-prevScope);
1508  } else {
1509  scope = std::string(tname, start_of_type, cursor - start_of_type); // we need to try to avoid this copy
1510  }
1511  std::string scoperesult;
1512  bool isInlined = false;
1513  if (gInterpreterHelper->ExistingTypeCheck(scope, scoperesult)
1514  ||gInterpreterHelper->GetPartiallyDesugaredNameWithScopeHandling(scope, scoperesult)) {
1515  // it is a known type
1516  if (!scoperesult.empty()) {
1517  // and it is a typedef
1518  if (modified) {
1519  if (constprefix && scoperesult.compare(0,6,"const ",6) != 0) mod_start_of_type -= 6;
1520  result.replace(mod_start_of_type, string::npos,
1521  scoperesult);
1522  result += "::";
1523  } else {
1524  modified = true;
1525  mod_start_of_type = start_of_type;
1526  result += string(tname,0,start_of_type);
1527  //if (constprefix) result += "const ";
1528  result += scoperesult;
1529  result += "::";
1530  }
1531  } else if (modified) {
1532  result += std::string(tname+prevScope,cursor+2-prevScope);
1533  }
1534  } else if (!gInterpreterHelper->IsDeclaredScope(scope,isInlined)) {
1535  // the nesting namespace is not declared, just ignore it and move on
1536  if (modified) result += std::string(tname+prevScope,cursor+2-prevScope);
1537  } else if (isInlined) {
1538  // humm ... just skip it.
1539  if (!modified) {
1540  modified = true;
1541  mod_start_of_type = start_of_type;
1542  result += string(tname,0,start_of_type);
1543  //if (constprefix) result += "const ";
1544  result += string(tname,start_of_type,prevScope - start_of_type);
1545  }
1546  } else if (modified) {
1547  result += std::string(tname+prevScope,cursor+2-prevScope);
1548  }
1549  // Consume the 1st semi colon, the 2nd will be consume by the for loop.
1550  ++cursor;
1551  prevScope = cursor+1;
1552  break;
1553  }
1554  case '<': {
1555  // push information on stack
1556  if (modified) {
1557  result += std::string(tname+prevScope,cursor+1-prevScope);
1558  // above includes the '<' .... result += '<';
1559  }
1560  do {
1561  ++cursor;
1562  ResolveTypedefImpl(tname,len,cursor,modified,result);
1563  } while( cursor<len && tname[cursor] == ',' );
1564 
1565  while (cursor<len && tname[cursor+1]==' ') ++cursor;
1566 
1567  // Since we already checked the type, skip the next section
1568  // (respective the scope section and final type processing section)
1569  // as they would re-do the same job.
1570  if (cursor+2<len && tname[cursor+1]==':' && tname[cursor+2]==':') {
1571  if (modified) result += "::";
1572  cursor += 2;
1573  prevScope = cursor+1;
1574  }
1575  if ( (cursor+1)<len && tname[cursor+1] == ',') {
1576  ++cursor;
1577  if (modified) result += ',';
1578  return;
1579  }
1580  if ( (cursor+1)<len && tname[cursor+1] == '>') {
1581  ++cursor;
1582  if (modified) result += " >";
1583  return;
1584  }
1585  if ( (cursor+1) >= len) {
1586  return;
1587  }
1588  if (tname[cursor] != ' ') break;
1589  if (modified) prevScope = cursor+1;
1590  // If the 'current' character is a space we need to treat it,
1591  // since this the next case statement, we can just fall through,
1592  // otherwise we should need to do:
1593  // --cursor; break;
1594  }
1595  case ' ': {
1596  end_of_type = cursor;
1597  // let's see if we have 'long long' or 'unsigned int' or 'signed char' or what not.
1598  while ((cursor+1)<len && tname[cursor+1] == ' ') ++cursor;
1599 
1600  auto next = cursor+1;
1601  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] == ']'))
1602  {
1603  // A first const after the type needs to be move in the front.
1604  if (!modified) {
1605  modified = true;
1606  result += string(tname,0,start_of_type);
1607  result += "const ";
1608  mod_start_of_type = start_of_type + 6;
1609  result += string(tname,start_of_type,end_of_type-start_of_type);
1610  } else if (mod_start_of_type < result.length()) {
1611  result.insert(mod_start_of_type,"const ");
1612  mod_start_of_type += 6;
1613  } else {
1614  result += "const ";
1615  mod_start_of_type += 6;
1616  result += string(tname,start_of_type,end_of_type-start_of_type);
1617  }
1618  cursor += 5;
1619  end_of_type = cursor+1;
1620  prevScope = end_of_type;
1621  if ((next+5)==len || tname[next+5] == ',' || tname[next+5] == '>' || tname[next+5] == '[') {
1622  break;
1623  }
1624  } else if (next!=len && tname[next] != '*' && tname[next] != '&') {
1625  // the type is not ended yet.
1626  end_of_type = 0;
1627  break;
1628  }
1629  ++cursor;
1630  // Intentional fall through;
1631  }
1632  case '*':
1633  case '&': {
1634  if (tname[cursor] != ' ') end_of_type = cursor;
1635  // check and skip const (followed by *,&, ,) ... what about followed by ':','['?
1636  auto next = cursor+1;
1637  if (strncmp(tname+next,"const",5) == 0) {
1638  if ((next+5)==len || tname[next+5] == ' ' || tname[next+5] == '*' || tname[next+5] == '&' || tname[next+5] == ',' || tname[next+5] == '>' || tname[next+5] == '[') {
1639  next += 5;
1640  }
1641  }
1642  while (next<len &&
1643  (tname[next] == ' ' || tname[next] == '*' || tname[next] == '&')) {
1644  ++next;
1645  // check and skip const (followed by *,&, ,) ... what about followed by ':','['?
1646  if (strncmp(tname+next,"const",5) == 0) {
1647  if ((next+5)==len || tname[next+5] == ' ' || tname[next+5] == '*' || tname[next+5] == '&' || tname[next+5] == ',' || tname[next+5] == '>' || tname[next+5] == '[') {
1648  next += 5;
1649  }
1650  }
1651  }
1652  cursor = next-1;
1653 // if (modified && mod_start_of_type < result.length()) {
1654 // result += string(tname,end_of_type,cursor-end_of_type);
1655 // }
1656  break;
1657  }
1658  case ',': {
1659  if (modified && prevScope) {
1660  result += std::string(tname+prevScope,(end_of_type == 0 ? cursor : end_of_type)-prevScope);
1661  }
1662  ResolveTypedefProcessType(tname,len,cursor,constprefix,start_of_type,end_of_type,mod_start_of_type,
1663  modified, result);
1664  if (modified) result += ',';
1665  return;
1666  }
1667  case '>': {
1668  if (modified && prevScope) {
1669  result += std::string(tname+prevScope,(end_of_type == 0 ? cursor : end_of_type)-prevScope);
1670  }
1671  ResolveTypedefProcessType(tname,len,cursor,constprefix,start_of_type,end_of_type,mod_start_of_type,
1672  modified, result);
1673  if (modified) result += '>';
1674  return;
1675  }
1676  default:
1677  end_of_type = 0;
1678  }
1679  }
1680 
1681  if (prevScope && modified) result += std::string(tname+prevScope,(end_of_type == 0 ? cursor : end_of_type)-prevScope);
1682 
1683  ResolveTypedefProcessType(tname,len,cursor,constprefix,start_of_type,end_of_type,mod_start_of_type,
1684  modified, result);
1685 }
1686 
1687 
1688 ////////////////////////////////////////////////////////////////////////////////
1689 
1690 string TClassEdit::ResolveTypedef(const char *tname, bool /* resolveAll */)
1691 {
1692  // Return the name of type 'tname' with all its typedef components replaced
1693  // by the actual type its points to
1694  // For example for "typedef MyObj MyObjTypedef;"
1695  // vector<MyObjTypedef> return vector<MyObj>
1696  //
1697 
1698  if (tname == 0 || tname[0] == 0)
1699  return "";
1700  if (!gInterpreterHelper)
1701  return tname;
1702 
1703  std::string result;
1704 
1705  // Check if we already know it is a normalized typename or a registered
1706  // typedef (i.e. known to gROOT).
1707  if (gInterpreterHelper->ExistingTypeCheck(tname, result))
1708  {
1709  if (result.empty()) return tname;
1710  else return result;
1711  }
1712 
1713  unsigned int len = strlen(tname);
1714 
1715  unsigned int cursor = 0;
1716  bool modified = false;
1717  ResolveTypedefImpl(tname,len,cursor,modified,result);
1718 
1719  if (!modified) return tname;
1720  else return result;
1721 }
1722 
1723 
1724 ////////////////////////////////////////////////////////////////////////////////
1725 
1726 string TClassEdit::InsertStd(const char *tname)
1727 {
1728  // Return the name of type 'tname' with all STL classes prepended by "std::".
1729  // For example for "vector<set<auto_ptr<int*> > >" it returns
1730  // "std::vector<std::set<std::auto_ptr<int*> > >"
1731  //
1732 
1733  static const char* sSTLtypes[] = {
1734  "allocator",
1735  "auto_ptr",
1736  "bad_alloc",
1737  "bad_cast",
1738  "bad_exception",
1739  "bad_typeid",
1740  "basic_filebuf",
1741  "basic_fstream",
1742  "basic_ifstream",
1743  "basic_ios",
1744  "basic_iostream",
1745  "basic_istream",
1746  "basic_istringstream",
1747  "basic_ofstream",
1748  "basic_ostream",
1749  "basic_ostringstream",
1750  "basic_streambuf",
1751  "basic_string",
1752  "basic_stringbuf",
1753  "basic_stringstream",
1754  "binary_function",
1755  "binary_negate",
1756  "bitset",
1757  "char_traits",
1758  "codecvt_byname",
1759  "codecvt",
1760  "collate",
1761  "collate_byname",
1762  "compare",
1763  "complex",
1764  "ctype_byname",
1765  "ctype",
1766  "deque",
1767  "divides",
1768  "domain_error",
1769  "equal_to",
1770  "exception",
1771  "forward_list",
1772  "fpos",
1773  "greater_equal",
1774  "greater",
1775  "gslice_array",
1776  "gslice",
1777  "hash",
1778  "indirect_array",
1779  "invalid_argument",
1780  "ios_base",
1781  "istream_iterator",
1782  "istreambuf_iterator",
1783  "istrstream",
1784  "iterator_traits",
1785  "iterator",
1786  "length_error",
1787  "less_equal",
1788  "less",
1789  "list",
1790  "locale",
1791  "localedef utility",
1792  "locale utility",
1793  "logic_error",
1794  "logical_and",
1795  "logical_not",
1796  "logical_or",
1797  "map",
1798  "mask_array",
1799  "mem_fun",
1800  "mem_fun_ref",
1801  "messages",
1802  "messages_byname",
1803  "minus",
1804  "modulus",
1805  "money_get",
1806  "money_put",
1807  "moneypunct",
1808  "moneypunct_byname",
1809  "multimap",
1810  "multiplies",
1811  "multiset",
1812  "negate",
1813  "not_equal_to",
1814  "num_get",
1815  "num_put",
1816  "numeric_limits",
1817  "numpunct",
1818  "numpunct_byname",
1819  "ostream_iterator",
1820  "ostreambuf_iterator",
1821  "ostrstream",
1822  "out_of_range",
1823  "overflow_error",
1824  "pair",
1825  "plus",
1826  "pointer_to_binary_function",
1827  "pointer_to_unary_function",
1828  "priority_queue",
1829  "queue",
1830  "range_error",
1831  "raw_storage_iterator",
1832  "reverse_iterator",
1833  "runtime_error",
1834  "set",
1835  "slice_array",
1836  "slice",
1837  "stack",
1838  "string",
1839  "strstream",
1840  "strstreambuf",
1841  "time_get_byname",
1842  "time_get",
1843  "time_put_byname",
1844  "time_put",
1845  "unary_function",
1846  "unary_negate",
1847  "unique_pointer",
1848  "underflow_error",
1849  "unordered_map",
1850  "unordered_multimap",
1851  "unordered_multiset",
1852  "unordered_set",
1853  "valarray",
1854  "vector",
1855  "wstring"
1856  };
1857  static ShuttingDownSignaler<set<string>> sSetSTLtypes;
1858 
1859  if (tname==0 || tname[0]==0) return "";
1860 
1861  if (sSetSTLtypes.empty()) {
1862  // set up static set
1863  const size_t nSTLtypes = sizeof(sSTLtypes) / sizeof(const char*);
1864  for (size_t i = 0; i < nSTLtypes; ++i)
1865  sSetSTLtypes.insert(sSTLtypes[i]);
1866  }
1867 
1868  size_t b = 0;
1869  size_t len = strlen(tname);
1870  string ret;
1871  ret.reserve(len + 20); // expect up to 4 extra "std::" to insert
1872  string id;
1873  while (b < len) {
1874  // find beginning of next identifier
1875  bool precScope = false; // whether the identifier was preceded by "::"
1876  while (!(isalnum(tname[b]) || tname[b] == '_') && b < len) {
1877  precScope = (b < len - 2) && (tname[b] == ':') && (tname[b + 1] == ':');
1878  if (precScope) {
1879  ret += "::";
1880  b += 2;
1881  } else
1882  ret += tname[b++];
1883  }
1884 
1885  // now b is at the beginning of an identifier or len
1886  size_t e = b;
1887  // find end of identifier
1888  id.clear();
1889  while (e < len && (isalnum(tname[e]) || tname[e] == '_'))
1890  id += tname[e++];
1891  if (!id.empty()) {
1892  if (!precScope) {
1893  set<string>::const_iterator iSTLtype = sSetSTLtypes.find(id);
1894  if (iSTLtype != sSetSTLtypes.end())
1895  ret += "std::";
1896  }
1897 
1898  ret += id;
1899  b = e;
1900  }
1901  }
1902  return ret;
1903 }
1904 
1905 ////////////////////////////////////////////////////////////////////////////////
1906 /// An helper class to dismount the name and remount it changed whenever
1907 /// necessary
1908 
1909 class NameCleanerForIO {
1910  std::string fName;
1911  std::vector<std::unique_ptr<NameCleanerForIO>> fArgumentNodes = {};
1912  NameCleanerForIO* fMother;
1913  bool fHasChanged = false;
1914  bool AreAncestorsSTLContOrArray()
1915  {
1916  NameCleanerForIO* mother = fMother;
1917  if (!mother) return false;
1918  bool isSTLContOrArray = true;
1919  while (nullptr != mother){
1920  auto stlType = TClassEdit::IsSTLCont(mother->fName+"<>");
1921  isSTLContOrArray &= ROOT::kNotSTL != stlType || TClassEdit::IsStdArray(mother->fName+"<");
1922  mother = mother->fMother;
1923  }
1924 
1925  return isSTLContOrArray;
1926  }
1927 
1928 public:
1929  NameCleanerForIO(const std::string& clName = "",
1931  NameCleanerForIO* mother = nullptr):fMother(mother)
1932  {
1933  if (clName.back() != '>') {
1934  fName = clName;
1935  return;
1936  }
1937 
1938  std::vector<std::string> v;
1939  int dummy=0;
1940  TClassEdit::GetSplit(clName.c_str(), v, dummy, mode);
1941 
1942  // We could be in presence of templates such as A1<T1>::A2<T2>::A3<T3>
1943  auto argsEnd = v.end();
1944  auto argsBeginPlusOne = ++v.begin();
1945  auto argPos = std::find_if(argsBeginPlusOne, argsEnd,
1946  [](std::string& arg){return (!arg.empty() && arg.front() == ':');});
1947  if (argPos != argsEnd) {
1948  const int lenght = clName.size();
1949  int wedgeBalance = 0;
1950  int lastOpenWedge = 0;
1951  for (int i=lenght-1;i>-1;i--) {
1952  auto& c = clName.at(i);
1953  if (c == '<') {
1954  wedgeBalance++;
1955  lastOpenWedge = i;
1956  } else if (c == '>') {
1957  wedgeBalance--;
1958  } else if (c == ':' && 0 == wedgeBalance) {
1959  // This would be A1<T1>::A2<T2>
1960  auto nameToClean = clName.substr(0,i-1);
1961  NameCleanerForIO node(nameToClean, mode);
1962  auto cleanName = node.ToString();
1963  fHasChanged = node.HasChanged();
1964  // We got A1<T1>::A2<T2> cleaned
1965 
1966  // We build the changed A1<T1>::A2<T2>::A3
1967  cleanName += "::";
1968  // Now we get A3 and append it
1969  cleanName += clName.substr(i+1,lastOpenWedge-i-1);
1970 
1971  // We now get the args of what in our case is A1<T1>::A2<T2>::A3
1972  auto lastTemplate = &clName.data()[i+1];
1973 
1974  // We split it
1975  TClassEdit::GetSplit(lastTemplate, v, dummy, mode);
1976  // We now replace the name of the template
1977  v[0] = cleanName;
1978  break;
1979  }
1980  }
1981  }
1982 
1983  fName = v.front();
1984  unsigned int nargs = v.size() - 2;
1985  for (unsigned int i=0;i<nargs;++i) {
1986  fArgumentNodes.emplace_back(new NameCleanerForIO(v[i+1],mode,this));
1987  }
1988  }
1989 
1990  bool HasChanged() const {return fHasChanged;}
1991 
1992  std::string ToString()
1993  {
1994  std::string name(fName);
1995 
1996  if (fArgumentNodes.empty()) return name;
1997 
1998  // We have in hands a case like unique_ptr< ... >
1999  // Perhaps we could treat atomics as well like this?
2000  if (!fMother && TClassEdit::IsUniquePtr(fName+"<")) {
2001  name = fArgumentNodes.front()->ToString();
2002  // ROOT-9933: we remove const if present.
2003  TClassEdit::TSplitType tst(name.c_str());
2004  tst.ShortType(name, 1);
2005  fHasChanged = true;
2006  return name;
2007  }
2008 
2009  // Now we treat the case of the collections of unique ptrs
2010  auto stlContType = AreAncestorsSTLContOrArray();
2011  if (stlContType != ROOT::kNotSTL && TClassEdit::IsUniquePtr(fName+"<")) {
2012  name = fArgumentNodes.front()->ToString();
2013  name += "*";
2014  fHasChanged = true;
2015  return name;
2016  }
2017 
2018  name += "<";
2019  for (auto& node : fArgumentNodes) {
2020  name += node->ToString() + ",";
2021  fHasChanged |= node->HasChanged();
2022  }
2023  name.pop_back(); // Remove the last comma.
2024  name += name.back() == '>' ? " >" : ">"; // Respect name normalisation
2025  return name;
2026  }
2027 
2028  const std::string& GetName() {return fName;}
2029  const std::vector<std::unique_ptr<NameCleanerForIO>>* GetChildNodes() const {return &fArgumentNodes;}
2030 };
2031 
2032 ////////////////////////////////////////////////////////////////////////////////
2033 
2034 std::string TClassEdit::GetNameForIO(const std::string& templateInstanceName,
2035  TClassEdit::EModType mode,
2036  bool* hasChanged)
2037 {
2038  // Decompose template name into pieces and remount it applying the necessary
2039  // transformations necessary for the ROOT IO subsystem, namely:
2040  // - Transform std::unique_ptr<T> into T (for selections) (also nested)
2041  // - Transform std::unique_ptr<const T> into T (for selections) (also nested)
2042  // - Transform std::COLL<std::unique_ptr<T>> into std::COLL<T*> (also nested)
2043  // Name normalisation is respected (e.g. spaces).
2044  // The implementation uses an internal class defined in the cxx file.
2045  NameCleanerForIO node(templateInstanceName, mode);
2046  auto nameForIO = node.ToString();
2047  if (hasChanged) {
2048  *hasChanged = node.HasChanged();
2049  }
2050  return nameForIO;
2051 }
2052 
2053 ////////////////////////////////////////////////////////////////////////////////
2054 // We could introduce a tuple as return type, but we be consistent with the rest
2055 // of the code.
2056 bool TClassEdit::GetStdArrayProperties(const char* typeName,
2057  std::string& typeNameBuf,
2058  std::array<int, 5>& maxIndices,
2059  int& ndim)
2060 {
2061  if (!IsStdArray(typeName)) return false;
2062 
2063  // We have an array, it's worth continuing
2064  NameCleanerForIO node(typeName);
2065 
2066  // We now recurse updating the data according to what we find
2067  auto childNodes = node.GetChildNodes();
2068  for (ndim = 1;ndim <=5 ; ndim++) {
2069  maxIndices[ndim-1] = std::atoi(childNodes->back()->GetName().c_str());
2070  auto& frontNode = childNodes->front();
2071  typeNameBuf = frontNode->GetName();
2072  if (! IsStdArray(typeNameBuf+"<")) {
2073  typeNameBuf = frontNode->ToString();
2074  return true;
2075  }
2076  childNodes = frontNode->GetChildNodes();
2077  }
2078 
2079  return true;
2080 }
2081 
2082 
2083 ////////////////////////////////////////////////////////////////////////////////
2084 /// Demangle in a portable way the type id name.
2085 /// IMPORTANT: The caller is responsible for freeing the returned const char*
2086 
2087 char* TClassEdit::DemangleTypeIdName(const std::type_info& ti, int& errorCode)
2088 {
2089  const char* mangled_name = ti.name();
2090  return DemangleName(mangled_name, errorCode);
2091 }
2092 /*
2093 /// Result of splitting a function declaration into
2094 /// fReturnType fScopeName::fFunctionName<fFunctionTemplateArguments>(fFunctionParameters)
2095 struct FunctionSplitInfo {
2096  /// Return type of the function, might be empty if the function declaration string did not provide it.
2097  std::string fReturnType;
2098 
2099  /// Name of the scope qualification of the function, possibly empty
2100  std::string fScopeName;
2101 
2102  /// Name of the function
2103  std::string fFunctionName;
2104 
2105  /// Template arguments of the function template specialization, if any; will contain one element "" for
2106  /// `function<>()`
2107  std::vector<std::string> fFunctionTemplateArguments;
2108 
2109  /// Function parameters.
2110  std::vector<std::string> fFunctionParameters;
2111 };
2112 */
2113 
2114 namespace {
2115  /// Find the first occurrence of any of needle's characters in haystack that
2116  /// is not nested in a <>, () or [] pair.
2117  std::size_t FindNonNestedNeedles(std::string_view haystack, string_view needles)
2118  {
2119  std::stack<char> expected;
2120  for (std::size_t pos = 0, end = haystack.length(); pos < end; ++pos) {
2121  char c = haystack[pos];
2122  if (expected.empty()) {
2123  if (needles.find(c) != std::string_view::npos)
2124  return pos;
2125  } else {
2126  if (c == expected.top()) {
2127  expected.pop();
2128  continue;
2129  }
2130  }
2131  switch (c) {
2132  case '<': expected.emplace('>'); break;
2133  case '(': expected.emplace(')'); break;
2134  case '[': expected.emplace(']'); break;
2135  }
2136  }
2137  return std::string_view::npos;
2138  }
2139 
2140  /// Find the first occurrence of `::` that is not nested in a <>, () or [] pair.
2141  std::size_t FindNonNestedDoubleColons(std::string_view haystack)
2142  {
2143  std::size_t lenHaystack = haystack.length();
2144  std::size_t prevAfterColumn = 0;
2145  while (true) {
2146  std::size_t posColumn = FindNonNestedNeedles(haystack.substr(prevAfterColumn), ":");
2147  if (posColumn == std::string_view::npos)
2148  return std::string_view::npos;
2149  prevAfterColumn += posColumn;
2150  // prevAfterColumn must have "::", i.e. two characters:
2151  if (prevAfterColumn + 1 >= lenHaystack)
2152  return std::string_view::npos;
2153 
2154  ++prevAfterColumn; // done with first (or only) ':'
2155  if (haystack[prevAfterColumn] == ':')
2156  return prevAfterColumn - 1;
2157  ++prevAfterColumn; // That was not a ':'.
2158  }
2159 
2160  return std::string_view::npos;
2161  }
2162 
2163  std::string_view StripSurroundingSpace(std::string_view str)
2164  {
2165  while (!str.empty() && std::isspace(str[0]))
2166  str.remove_prefix(1);
2167  while (!str.empty() && std::isspace(str.back()))
2168  str.remove_suffix(1);
2169  return str;
2170  }
2171 
2172  std::string ToString(std::string_view sv)
2173  {
2174  // ROOT's string_view backport doesn't add the new std::string contructor and assignment;
2175  // convert to std::string instead and assign that.
2176  return std::string(sv.data(), sv.length());
2177  }
2178 } // unnamed namespace
2179 
2180 /// Split a function declaration into its different parts.
2182 {
2183  // General structure:
2184  // `...` last-space `...` (`...`)
2185  // The first `...` is the return type.
2186  // The second `...` is the (possibly scoped) function name.
2187  // The third `...` are the parameters.
2188  // The function name can be of the form `...`<`...`>
2189  std::size_t posArgs = FindNonNestedNeedles(decl, "(");
2190  std::string_view declNoArgs = decl.substr(0, posArgs);
2191 
2192  std::size_t prevAfterWhiteSpace = 0;
2193  static const char whitespace[] = " \t\n";
2194  while (declNoArgs.length() > prevAfterWhiteSpace) {
2195  std::size_t posWS = FindNonNestedNeedles(declNoArgs.substr(prevAfterWhiteSpace), whitespace);
2196  if (posWS == std::string_view::npos)
2197  break;
2198  prevAfterWhiteSpace += posWS + 1;
2199  while (declNoArgs.length() > prevAfterWhiteSpace
2200  && strchr(whitespace, declNoArgs[prevAfterWhiteSpace]))
2201  ++prevAfterWhiteSpace;
2202  }
2203 
2204  /// Include any '&*' in the return type:
2205  std::size_t endReturn = prevAfterWhiteSpace;
2206  while (declNoArgs.length() > endReturn
2207  && strchr("&* \t \n", declNoArgs[endReturn]))
2208  ++endReturn;
2209 
2210  result.fReturnType = ToString(StripSurroundingSpace(declNoArgs.substr(0, endReturn)));
2211 
2212  /// scope::anotherscope::functionName<tmplt>:
2213  std::string_view scopeFunctionTmplt = declNoArgs.substr(endReturn);
2214  std::size_t prevAtScope = FindNonNestedDoubleColons(scopeFunctionTmplt);
2215  while (prevAtScope != std::string_view::npos
2216  && scopeFunctionTmplt.length() > prevAtScope + 2) {
2217  std::size_t posScope = FindNonNestedDoubleColons(scopeFunctionTmplt.substr(prevAtScope + 2));
2218  if (posScope == std::string_view::npos)
2219  break;
2220  prevAtScope += posScope + 2;
2221  }
2222 
2223  std::size_t afterScope = prevAtScope + 2;
2224  if (prevAtScope == std::string_view::npos) {
2225  afterScope = 0;
2226  prevAtScope = 0;
2227  }
2228 
2229  result.fScopeName = ToString(StripSurroundingSpace(scopeFunctionTmplt.substr(0, prevAtScope)));
2230  std::string_view funcNameTmplArgs = scopeFunctionTmplt.substr(afterScope);
2231 
2232  result.fFunctionTemplateArguments.clear();
2233  std::size_t posTmpltOpen = FindNonNestedNeedles(funcNameTmplArgs, "<");
2234  if (posTmpltOpen != std::string_view::npos) {
2235  result.fFunctionName = ToString(StripSurroundingSpace(funcNameTmplArgs.substr(0, posTmpltOpen)));
2236 
2237  // Parse template parameters:
2238  std::string_view tmpltArgs = funcNameTmplArgs.substr(posTmpltOpen + 1);
2239  std::size_t posTmpltClose = FindNonNestedNeedles(tmpltArgs, ">");
2240  if (posTmpltClose != std::string_view::npos) {
2241  tmpltArgs = tmpltArgs.substr(0, posTmpltClose);
2242  std::size_t prevAfterArg = 0;
2243  while (tmpltArgs.length() > prevAfterArg) {
2244  std::size_t posComma = FindNonNestedNeedles(tmpltArgs.substr(prevAfterArg), ",");
2245  if (posComma == std::string_view::npos) {
2246  break;
2247  }
2248  result.fFunctionTemplateArguments.emplace_back(ToString(StripSurroundingSpace(tmpltArgs.substr(prevAfterArg, posComma))));
2249  prevAfterArg += posComma + 1;
2250  }
2251  // Add the trailing arg.
2252  result.fFunctionTemplateArguments.emplace_back(ToString(StripSurroundingSpace(tmpltArgs.substr(prevAfterArg))));
2253  }
2254  } else {
2255  result.fFunctionName = ToString(StripSurroundingSpace(funcNameTmplArgs));
2256  }
2257 
2258  result.fFunctionParameters.clear();
2259  if (posArgs != std::string_view::npos) {
2260  /// (params)
2261  std::string_view params = decl.substr(posArgs + 1);
2262  std::size_t posEndArgs = FindNonNestedNeedles(params, ")");
2263  if (posEndArgs != std::string_view::npos) {
2264  params = params.substr(0, posEndArgs);
2265  std::size_t prevAfterArg = 0;
2266  while (params.length() > prevAfterArg) {
2267  std::size_t posComma = FindNonNestedNeedles(params.substr(prevAfterArg), ",");
2268  if (posComma == std::string_view::npos) {
2269  result.fFunctionParameters.emplace_back(ToString(StripSurroundingSpace(params.substr(prevAfterArg))));
2270  break;
2271  }
2272  result.fFunctionParameters.emplace_back(ToString(StripSurroundingSpace(params.substr(prevAfterArg, posComma))));
2273  prevAfterArg += posComma + 1; // skip ','
2274  }
2275  }
2276  }
2277 
2278  return true;
2279 }
TClassEdit::FunctionSplitInfo
Result of splitting a function declaration into fReturnType fScopeName::fFunctionName<fFunctionTempla...
Definition: TClassEdit.h:237
c
#define c(i)
Definition: RSha256.hxx:119
n
const Int_t n
Definition: legend1.C:16
ROOT::kSTLdeque
@ kSTLdeque
Definition: ESTLType.h:44
ROOT::kSTLvector
@ kSTLvector
Definition: ESTLType.h:42
ROOT::kSTLset
@ kSTLset
Definition: ESTLType.h:47
Rstrstream.h
e
#define e(i)
Definition: RSha256.hxx:121
ROOT::kSTLunorderedmultimap
@ kSTLunorderedmultimap
Definition: ESTLType.h:57
ROOT::kSTLbitset
@ kSTLbitset
Definition: ESTLType.h:49
TClassEdit::GetNameForIO
std::string GetNameForIO(const std::string &templateInstanceName, TClassEdit::EModType mode=TClassEdit::kNone, bool *hasChanged=nullptr)
Definition: TClassEdit.cxx:2034
TClassEdit::GetNormalizedName
void GetNormalizedName(std::string &norm_name, std::string_view name)
Return the normalized name.
Definition: TClassEdit.cxx:831
TClassEdit::TInterpreterLookupHelper::GetPartiallyDesugaredNameWithScopeHandling
virtual bool GetPartiallyDesugaredNameWithScopeHandling(const std::string &, std::string &, bool=true)=0
TClassEdit::FunctionSplitInfo::fFunctionName
std::string fFunctionName
Name of the function.
Definition: TClassEdit.h:245
TClassEdit::GetStdArrayProperties
bool GetStdArrayProperties(const char *typeName, std::string &typeNameBuf, std::array< int, 5 > &maxIndices, int &ndim)
Definition: TClassEdit.cxx:2056
ROOT::kSTLunorderedmultiset
@ kSTLunorderedmultiset
Definition: ESTLType.h:55
ROOT::kNotSTL
@ kNotSTL
Definition: ESTLType.h:41
TClassEdit::TInterpreterLookupHelper::ExistingTypeCheck
virtual bool ExistingTypeCheck(const std::string &, std::string &)=0
TClassEdit::ShortType
std::string ShortType(const char *typeDesc, int mode)
Return the absolute type of typeDesc.
Definition: TClassEdit.cxx:1247
TClassEdit::STLArgs
int STLArgs(int kind)
Return number of arguments for STL container before allocator.
Definition: TClassEdit.cxx:555
TClassEdit::kLong64
@ kLong64
Definition: TClassEdit.h:84
output
static void output(int code)
Definition: gifencode.c:226
string_view
basic_string_view< char > string_view
Definition: libcpp_string_view.h:785
TClassEdit::FunctionSplitInfo::fScopeName
std::string fScopeName
Name of the scope qualification of the function, possibly empty.
Definition: TClassEdit.h:242
TClassEdit::kDropAlloc
@ kDropAlloc
Definition: TClassEdit.h:78
TClassEdit::IsStdClass
bool IsStdClass(const char *type)
return true if the class belongs to the std namespace
Definition: TClassEdit.cxx:1360
TClassEdit::GetLong64_Name
std::string GetLong64_Name(const char *original)
Replace 'long long' and 'unsigned long long' by 'Long64_t' and 'ULong64_t'.
Definition: TClassEdit.cxx:860
TClassEdit::IsVectorBool
bool IsVectorBool(const char *name)
Definition: TClassEdit.cxx:1394
TClassEdit::TSplitType::IsInSTL
ROOT::ESTLType IsInSTL() const
type : type name: vector<list<classA,allocator>,allocator>[::iterator] result: 0 : not stl container ...
Definition: TClassEdit.cxx:172
TClassEdit::TSplitType::IsSTLCont
int IsSTLCont(int testAlloc=0) const
type : type name: vector<list<classA,allocator>,allocator> testAlloc: if true, we test allocator,...
Definition: TClassEdit.cxx:189
TClassEdit::kDropDefaultAlloc
@ kDropDefaultAlloc
Definition: TClassEdit.h:77
TClassEdit::TSplitType
Definition: TClassEdit.h:137
TClassEdit::SplitFunction
bool SplitFunction(std::string_view decl, FunctionSplitInfo &result)
Split a function declaration into its different parts.
Definition: TClassEdit.cxx:2181
ROOT::kSTLlist
@ kSTLlist
Definition: ESTLType.h:43
TClassEdit::kDropAllDefault
@ kDropAllDefault
Definition: TClassEdit.h:83
v
@ v
Definition: rootcling_impl.cxx:3635
b
#define b(i)
Definition: RSha256.hxx:118
TClassEdit::kResolveTypedef
@ kResolveTypedef
Definition: TClassEdit.h:87
TClassEdit::TInterpreterLookupHelper::ShuttingDownSignal
virtual void ShuttingDownSignal()=0
IsDefElement
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
ROOT::kSTLmap
@ kSTLmap
Definition: ESTLType.h:45
id
XFontStruct * id
Definition: TGX11.cxx:109
TClassEdit::TSplitType::fElements
std::vector< std::string > fElements
Definition: TClassEdit.h:140
ResolveTypedefImpl
static void ResolveTypedefImpl(const char *tname, unsigned int len, unsigned int &cursor, bool &modified, std::string &result)
Definition: TClassEdit.cxx:1458
ROOT::ESTLType
ESTLType
Definition: ESTLType.h:34
TClassEdit::FunctionSplitInfo::fReturnType
std::string fReturnType
Return type of the function, might be empty if the function declaration string did not provide it.
Definition: TClassEdit.h:239
kNone
const Handle_t kNone
Definition: GuiTypes.h:87
TClassEdit::DemangleName
char * DemangleName(const char *mangled_name, int &errorCode)
Definition: TClassEdit.h:205
TClassEdit::IsSTLCont
ROOT::ESTLType IsSTLCont(std::string_view type)
type : type name: vector<list<classA,allocator>,allocator> result: 0 : not stl container code of cont...
Definition: TClassEdit.cxx:1320
TClassEdit::kNone
@ kNone
Definition: TClassEdit.h:75
ROOT::kSTLmultiset
@ kSTLmultiset
Definition: ESTLType.h:48
ROOT::kSTLforwardlist
@ kSTLforwardlist
Definition: ESTLType.h:53
TClassEdit::EComplexType
EComplexType
Definition: TClassEdit.h:110
StdLen
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
TClassEdit::CleanType
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 ...
Definition: TClassEdit.cxx:1174
TClassEdit::TInterpreterLookupHelper
Definition: TClassEdit.h:120
a
auto * a
Definition: textangle.C:12
RStringView.hxx
TClassEdit::IsSTLBitset
bool IsSTLBitset(const char *type)
Return true is the name is std::bitset<number> or bitset<number>
Definition: TClassEdit.cxx:1282
TClassEdit::kDropComparator
@ kDropComparator
Definition: TClassEdit.h:82
TClassEdit::TInterpreterLookupHelper::IsAlreadyPartiallyDesugaredName
virtual bool IsAlreadyPartiallyDesugaredName(const std::string &, const std::string &)=0
ROOT::Math::Util::ToString
std::string ToString(const T &val)
Utility function for conversion to strings.
Definition: Util.h:50
ROOT::kSTLunorderedset
@ kSTLunorderedset
Definition: ESTLType.h:54
TClassEdit::IsDefComp
bool IsDefComp(const char *comp, const char *classname)
return whether or not 'compare' is the STL default comparator for type 'classname'
Definition: TClassEdit.cxx:798
ROOT::kSTLmultimap
@ kSTLmultimap
Definition: ESTLType.h:46
TClassEdit::GetUnqualifiedName
const char * GetUnqualifiedName(const char *name)
Return the start of the unqualified name include in 'original'.
Definition: TClassEdit.cxx:894
TClassEdit::TSplitType::fNestedLocation
int fNestedLocation
Definition: TClassEdit.h:141
TClassEdit::TInterpreterLookupHelper::IsDeclaredScope
virtual bool IsDeclaredScope(const std::string &, bool &)=0
TClassEdit::IsInterpreterDetail
bool IsInterpreterDetail(const char *type)
Return true if the type is one the interpreter details which are only forward declared (ClassInfo_t e...
Definition: TClassEdit.cxx:1264
TClassEdit::IsDefHash
bool IsDefHash(const char *hashname, const char *classname)
return whether or not 'hashname' is the STL default hash for type 'classname'
Definition: TClassEdit.cxx:816
TClassEdit::IsDefPred
bool IsDefPred(const char *predname, const char *classname)
return whether or not 'predname' is the STL default predicate for type 'classname'
Definition: TClassEdit.cxx:807
TClassEdit::TSplitType::ShortType
void ShortType(std::string &answer, int mode)
Return the absolute type of typeDesc into the string answ.
Definition: TClassEdit.cxx:233
TClassEdit::InsertStd
std::string InsertStd(const char *tname)
Definition: TClassEdit.cxx:1726
RemoveStd
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
TClassEdit::GetSplit
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.
Definition: TClassEdit.cxx:981
TClassEdit::TSplitType::IsTemplate
bool IsTemplate()
Check if the type is a template.
Definition: TClassEdit.cxx:502
TClassEdit::IsUniquePtr
bool IsUniquePtr(std::string_view name)
Definition: TClassEdit.h:184
TClassEdit::TInterpreterLookupHelper::GetPartiallyDesugaredName
virtual void GetPartiallyDesugaredName(std::string &)=0
TClassEdit.h
dummy
static RooMathCoreReg dummy
Definition: RooMathCoreReg.cxx:27
TClassEdit::UnderlyingIsSTLCont
ROOT::ESTLType UnderlyingIsSTLCont(std::string_view type)
Return the type of STL collection, if any, that is the underlying type of the given type.
Definition: TClassEdit.cxx:1301
TClassEdit::TInterpreterLookupHelper::~TInterpreterLookupHelper
virtual ~TInterpreterLookupHelper()
Definition: TClassEdit.cxx:141
TClassEdit::EModType
EModType
Definition: TClassEdit.h:74
TClassEdit::Init
void Init(TClassEdit::TInterpreterLookupHelper *helper)
Definition: TClassEdit.cxx:154
name
char name[80]
Definition: TGX11.cxx:110
TClassEdit::kDropStd
@ kDropStd
Definition: TClassEdit.h:85
ROOT::kSTLunorderedmap
@ kSTLunorderedmap
Definition: ESTLType.h:56
ROOT::Math::Chebyshev::T
double T(double x)
Definition: ChebyshevPol.h:52
TClassEdit::ResolveTypedef
std::string ResolveTypedef(const char *tname, bool resolveAll=false)
Definition: TClassEdit.cxx:1690
TClassEdit::STLKind
ROOT::ESTLType STLKind(std::string_view type)
Converts STL container name to number.
Definition: TClassEdit.cxx:511
findNameEnd
static size_t findNameEnd(const std::string_view full)
Definition: TClassEdit.cxx:568
type
int type
Definition: TGX11.cxx:121
TClassEdit::FunctionSplitInfo::fFunctionParameters
std::vector< std::string > fFunctionParameters
Function parameters.
Definition: TClassEdit.h:252
TClassEdit::kKeepOuterConst
@ kKeepOuterConst
Definition: TClassEdit.h:86
ResolveTypedefProcessType
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)
Definition: TClassEdit.cxx:1403
TClassEdit::FunctionSplitInfo::fFunctionTemplateArguments
std::vector< std::string > fFunctionTemplateArguments
Template arguments of the function template specialization, if any; will contain one element "" for f...
Definition: TClassEdit.h:249
TClassEdit::GetComplexType
EComplexType GetComplexType(const char *)
Definition: TClassEdit.cxx:120
TClassEdit::kDropStlDefault
@ kDropStlDefault
Definition: TClassEdit.h:81
R__FindTrailing
static void R__FindTrailing(std::string &full, std::string &stars)
Definition: TClassEdit.cxx:914
TClassEdit::DemangleTypeIdName
char * DemangleTypeIdName(const std::type_info &ti, int &errorCode)
Demangle in a portable way the type id name.
Definition: TClassEdit.cxx:2087
TClassEdit::IsDefAlloc
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
TClassEdit::TSplitType::TSplitType
TSplitType(const char *type2split, EModType mode=TClassEdit::kNone)
default constructor
Definition: TClassEdit.cxx:162
TClassEdit::IsStdArray
bool IsStdArray(std::string_view name)
Definition: TClassEdit.h:186