-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathTCling.cxx
9673 lines (8388 loc) · 357 KB
/
TCling.cxx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @(#)root/meta:$Id$
// vim: sw=3 ts=3 expandtab foldmethod=indent
/*************************************************************************
* Copyright (C) 1995-2012, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/** \class TCling
This class defines an interface to the cling C++ interpreter.
Cling is a full ANSI compliant C++-11 interpreter based on
clang/LLVM technology.
*/
#include "TCling.h"
#include "ROOT/FoundationUtils.hxx"
#include "TClingBaseClassInfo.h"
#include "TClingCallFunc.h"
#include "TClingClassInfo.h"
#include "TClingDataMemberInfo.h"
#include "TClingMethodArgInfo.h"
#include "TClingMethodInfo.h"
#include "TClingRdictModuleFileExtension.h"
#include "TClingTypedefInfo.h"
#include "TClingTypeInfo.h"
#include "TClingValue.h"
#include "TROOT.h"
#include "TApplication.h"
#include "TGlobal.h"
#include "TDataType.h"
#include "TClass.h"
#include "TClassEdit.h"
#include "TClassTable.h"
#include "TClingCallbacks.h"
#include "TClingDiagnostics.h"
#include "TBaseClass.h"
#include "TDataMember.h"
#include "TMemberInspector.h"
#include "TMethod.h"
#include "TMethodArg.h"
#include "TFunctionTemplate.h"
#include "TObjArray.h"
#include "TObjString.h"
#include "TString.h"
#include "THashList.h"
#include "TVirtualPad.h"
#include "TSystem.h"
#include "TVirtualMutex.h"
#include "TError.h"
#include "TEnv.h"
#include "TEnum.h"
#include "TEnumConstant.h"
#include "THashTable.h"
#include "RConversionRuleParser.h"
#include "RConfigure.h"
#include "compiledata.h"
#include "strlcpy.h"
#include "snprintf.h"
#include "TClingUtils.h"
#include "TVirtualCollectionProxy.h"
#include "TVirtualStreamerInfo.h"
#include "TListOfDataMembers.h"
#include "TListOfEnums.h"
#include "TListOfEnumsWithLock.h"
#include "TListOfFunctions.h"
#include "TListOfFunctionTemplates.h"
#include "TMemFile.h"
#include "TProtoClass.h"
#include "TStreamerInfo.h" // This is here to avoid to use the plugin manager
#include "ThreadLocalStorage.h"
#include "TFile.h"
#include "TKey.h"
#include "ClingRAII.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclarationName.h"
#include "clang/AST/GlobalDecl.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/Type.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/CodeGen/ModuleBuilder.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Parse/Parser.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Sema.h"
#include "clang/Serialization/ASTReader.h"
#include "clang/Serialization/GlobalModuleIndex.h"
#include "cling/Interpreter/ClangInternalState.h"
#include "cling/Interpreter/DynamicLibraryManager.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/LookupHelper.h"
#include "cling/Interpreter/Value.h"
#include "cling/Interpreter/Transaction.h"
#include "cling/MetaProcessor/MetaProcessor.h"
#include "cling/Utils/AST.h"
#include "cling/Utils/ParserStateRAII.h"
#include "cling/Utils/SourceNormalization.h"
#include "cling/Interpreter/Exception.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
#include "llvm/Object/ELFObjectFile.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Object/SymbolicFile.h"
#include "llvm/Support/FileSystem.h"
#include <algorithm>
#include <iostream>
#include <cassert>
#include <map>
#include <set>
#include <stdexcept>
#include <stdint.h>
#include <fstream>
#include <sstream>
#include <string>
#include <tuple>
#include <typeinfo>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include <functional>
#include <optional>
#ifndef R__WIN32
#include <cxxabi.h>
#define R__DLLEXPORT __attribute__ ((visibility ("default")))
#include <sys/stat.h>
#endif
#include <limits.h>
#include <stdio.h>
#ifdef __APPLE__
#include <dlfcn.h>
#include <mach-o/dyld.h>
#include <mach-o/loader.h>
#endif // __APPLE__
#ifdef R__UNIX
#include <dlfcn.h>
#endif
#if defined(R__LINUX) || defined(R__FBSD)
# ifndef _GNU_SOURCE
# define _GNU_SOURCE
# endif
# include <link.h> // dl_iterate_phdr()
#endif
#if defined(__CYGWIN__)
#include <sys/cygwin.h>
#define HMODULE void *
extern "C" {
__declspec(dllimport) void * __stdcall GetCurrentProcess();
__declspec(dllimport) bool __stdcall EnumProcessModules(void *, void **, unsigned long, unsigned long *);
__declspec(dllimport) unsigned long __stdcall GetModuleFileNameExW(void *, void *, wchar_t *, unsigned long);
}
#endif
// Fragment copied from LLVM's raw_ostream.cpp
#if defined(_MSC_VER)
#ifndef STDIN_FILENO
# define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
# define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
# define STDERR_FILENO 2
#endif
#ifndef R__WIN32
//#if defined(HAVE_UNISTD_H)
# include <unistd.h>
//#endif
#else
#include "Windows4Root.h"
#include <Psapi.h>
#include <direct.h>
#undef GetModuleFileName
#define RTLD_DEFAULT ((void *)::GetModuleHandle(NULL))
#define dlsym(library, function_name) ::GetProcAddress((HMODULE)library, function_name)
#define dlopen(library_name, flags) ::LoadLibraryA(library_name)
#define dlclose(library) ::FreeLibrary((HMODULE)library)
#define R__DLLEXPORT __declspec(dllexport)
#endif
#endif
//______________________________________________________________________________
// These functions are helpers for debugging issues with non-LLVMDEV builds.
//
R__DLLEXPORT clang::DeclContext* TCling__DEBUG__getDeclContext(clang::Decl* D) {
return D->getDeclContext();
}
R__DLLEXPORT clang::NamespaceDecl* TCling__DEBUG__DCtoNamespace(clang::DeclContext* DC) {
return llvm::dyn_cast<clang::NamespaceDecl>(DC);
}
R__DLLEXPORT clang::RecordDecl* TCling__DEBUG__DCtoRecordDecl(clang::DeclContext* DC) {
return llvm::dyn_cast<clang::RecordDecl>(DC);
}
R__DLLEXPORT void TCling__DEBUG__dump(clang::DeclContext* DC) {
return DC->dumpDeclContext();
}
R__DLLEXPORT void TCling__DEBUG__dump(clang::Decl* D) {
return D->dump();
}
R__DLLEXPORT void TCling__DEBUG__dump(clang::FunctionDecl* FD) {
return FD->dump();
}
R__DLLEXPORT void TCling__DEBUG__decl_dump(void* D) {
return ((clang::Decl*)D)->dump();
}
R__DLLEXPORT void TCling__DEBUG__printName(clang::Decl* D) {
if (clang::NamedDecl* ND = llvm::dyn_cast<clang::NamedDecl>(D)) {
std::string name;
{
llvm::raw_string_ostream OS(name);
ND->getNameForDiagnostic(OS, D->getASTContext().getPrintingPolicy(),
true /*Qualified*/);
}
printf("%s\n", name.c_str());
}
}
//______________________________________________________________________________
// These functions are helpers for testing issues directly rather than
// relying on side effects.
// This is used for the test for ROOT-7462/ROOT-6070
R__DLLEXPORT bool TCling__TEST_isInvalidDecl(clang::Decl* D) {
return D->isInvalidDecl();
}
R__DLLEXPORT bool TCling__TEST_isInvalidDecl(ClassInfo_t *input) {
TClingClassInfo *info( (TClingClassInfo*) input);
assert(info && info->IsValid());
return info->GetDecl()->isInvalidDecl();
}
using std::string, std::vector;
using namespace clang;
using namespace ROOT;
namespace {
static const std::string gInterpreterClassDef = R"ICF(
#undef ClassDef
#define ClassDef(name, id) \
_ClassDefInterp_(name,id,virtual,) \
static int DeclFileLine() { return __LINE__; }
#undef ClassDefNV
#define ClassDefNV(name, id) \
_ClassDefInterp_(name,id,,) \
static int DeclFileLine() { return __LINE__; }
#undef ClassDefOverride
#define ClassDefOverride(name, id) \
_ClassDefInterp_(name,id,,override) \
static int DeclFileLine() { return __LINE__; }
)ICF";
static const std::string gNonInterpreterClassDef = R"ICF(
#define __ROOTCLING__ 1
#undef ClassDef
#define ClassDef(name,id) \
_ClassDefOutline_(name,id,virtual,) \
static int DeclFileLine() { return __LINE__; }
#undef ClassDefNV
#define ClassDefNV(name, id)\
_ClassDefOutline_(name,id,,)\
static int DeclFileLine() { return __LINE__; }
#undef ClassDefOverride
#define ClassDefOverride(name, id)\
_ClassDefOutline_(name,id,,override)\
static int DeclFileLine() { return __LINE__; }
)ICF";
// The macros below use ::Error, so let's ensure it is included
static const std::string gClassDefInterpMacro = R"ICF(
#include "TError.h"
#define _ClassDefInterp_(name,id,virtual_keyword, overrd) \
private: \
public: \
static TClass *Class() { static TClass* sIsA = 0; if (!sIsA) sIsA = TClass::GetClass(#name); return sIsA; } \
static const char *Class_Name() { return #name; } \
virtual_keyword Bool_t CheckTObjectHashConsistency() const overrd { return true; } \
static Version_t Class_Version() { return id; } \
static TClass *Dictionary() { return 0; } \
virtual_keyword TClass *IsA() const overrd { return name::Class(); } \
virtual_keyword void ShowMembers(TMemberInspector&insp) const overrd { ::ROOT::Class_ShowMembers(name::Class(), this, insp); } \
virtual_keyword void Streamer(TBuffer&) overrd { ::Error("Streamer", "Cannot stream interpreted class."); } \
void StreamerNVirtual(TBuffer&ClassDef_StreamerNVirtual_b) { name::Streamer(ClassDef_StreamerNVirtual_b); } \
static const char *DeclFileName() { return __FILE__; } \
static int ImplFileLine() { return 0; } \
static const char *ImplFileName() { return __FILE__; }
)ICF";
}
R__EXTERN int optind;
// The functions are used to bridge cling/clang/llvm compiled with no-rtti and
// ROOT (which uses rtti)
////////////////////////////////////////////////////////////////////////////////
/// Print a StackTrace!
extern "C"
void TCling__PrintStackTrace() {
gSystem->StackTrace();
}
////////////////////////////////////////////////////////////////////////////////
/// Load a library.
extern "C" int TCling__LoadLibrary(const char *library)
{
return gSystem->Load(library, "", false);
}
////////////////////////////////////////////////////////////////////////////////
/// Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
extern "C" void TCling__RestoreInterpreterMutex(void *delta)
{
((TCling*)gCling)->ApplyToInterpreterMutex(delta);
}
////////////////////////////////////////////////////////////////////////////////
/// Lookup libraries in LD_LIBRARY_PATH and DYLD_LIBRARY_PATH with mangled_name,
/// which is extracted by error messages we get from callback from cling. Return true
/// when the missing library was autoloaded.
extern "C" bool TCling__LibraryLoadingFailed(const std::string& errmessage, const std::string& libStem, bool permanent, bool resolved)
{
return ((TCling*)gCling)->LibraryLoadingFailed(errmessage, libStem, permanent, resolved);
}
////////////////////////////////////////////////////////////////////////////////
/// Reset the interpreter lock to the state it had before interpreter-related
/// calls happened.
extern "C" void *TCling__ResetInterpreterMutex()
{
return ((TCling*)gCling)->RewindInterpreterMutex();
}
////////////////////////////////////////////////////////////////////////////////
/// Lock the interpreter.
extern "C" void *TCling__LockCompilationDuringUserCodeExecution()
{
if (gInterpreterMutex) {
gInterpreterMutex->Lock();
}
return nullptr;
}
////////////////////////////////////////////////////////////////////////////////
/// Unlock the interpreter.
extern "C" void TCling__UnlockCompilationDuringUserCodeExecution(void* /*state*/)
{
if (gInterpreterMutex) {
gInterpreterMutex->UnLock();
}
}
////////////////////////////////////////////////////////////////////////////////
/// Update TClingClassInfo for a class (e.g. upon seeing a definition).
static void TCling__UpdateClassInfo(const NamedDecl* TD)
{
static Bool_t entered = kFALSE;
static vector<const NamedDecl*> updateList;
Bool_t topLevel;
if (entered) topLevel = kFALSE;
else {
entered = kTRUE;
topLevel = kTRUE;
}
if (topLevel) {
((TCling*)gInterpreter)->UpdateClassInfoWithDecl(TD);
} else {
// If we are called indirectly from within another call to
// TCling::UpdateClassInfo, we delay the update until the dictionary loading
// is finished (i.e. when we return to the top level TCling::UpdateClassInfo).
// This allows for the dictionary to be fully populated when we actually
// update the TClass object. The updating of the TClass sometimes
// (STL containers and when there is an emulated class) forces the building
// of the TClass object's real data (which needs the dictionary info).
updateList.push_back(TD);
}
if (topLevel) {
while (!updateList.empty()) {
((TCling*)gInterpreter)->UpdateClassInfoWithDecl(updateList.back());
updateList.pop_back();
}
entered = kFALSE;
}
}
void TCling::UpdateEnumConstants(TEnum* enumObj, TClass* cl) const {
const clang::Decl* D = static_cast<const clang::Decl*>(enumObj->GetDeclId());
if(const clang::EnumDecl* ED = dyn_cast<clang::EnumDecl>(D)) {
// Add the constants to the enum type.
for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin(),
EDE = ED->enumerator_end(); EDI != EDE; ++EDI) {
// Get name of the enum type.
std::string constbuf;
if (const NamedDecl* END = llvm::dyn_cast<NamedDecl>(*EDI)) {
PrintingPolicy Policy((*EDI)->getASTContext().getPrintingPolicy());
llvm::raw_string_ostream stream(constbuf);
// Don't trigger fopen of the source file to count lines:
Policy.AnonymousTagLocations = false;
(END)->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
}
const char* constantName = constbuf.c_str();
// Get value of the constant.
Long64_t value;
const llvm::APSInt valAPSInt = (*EDI)->getInitVal();
if (valAPSInt.isSigned()) {
value = valAPSInt.getSExtValue();
} else {
value = valAPSInt.getZExtValue();
}
// Create the TEnumConstant or update it if existing
TEnumConstant* enumConstant = nullptr;
TClingClassInfo* tcCInfo = (TClingClassInfo*)(cl ? cl->GetClassInfo() : nullptr);
TClingDataMemberInfo* tcDmInfo = new TClingDataMemberInfo(GetInterpreterImpl(), *EDI, tcCInfo);
DataMemberInfo_t* dmInfo = (DataMemberInfo_t*) tcDmInfo;
if (TObject* encAsTObj = enumObj->GetConstants()->FindObject(constantName)){
((TEnumConstant*)encAsTObj)->Update(dmInfo);
} else {
enumConstant = new TEnumConstant(dmInfo, constantName, value, enumObj);
}
// Add the global constants to the list of Globals.
if (!cl) {
TCollection* globals = gROOT->GetListOfGlobals(false);
if (!globals->FindObject(constantName)) {
globals->Add(enumConstant);
}
}
}
}
}
TEnum* TCling::CreateEnum(void *VD, TClass *cl) const
{
// Handle new enum declaration for either global and nested enums.
// Create the enum type.
TEnum* enumType = nullptr;
const clang::Decl* D = static_cast<const clang::Decl*>(VD);
std::string buf;
if (const EnumDecl* ED = llvm::dyn_cast<EnumDecl>(D)) {
// Get name of the enum type.
PrintingPolicy Policy(ED->getASTContext().getPrintingPolicy());
llvm::raw_string_ostream stream(buf);
// Don't trigger fopen of the source file to count lines:
Policy.AnonymousTagLocations = false;
ED->getNameForDiagnostic(stream, Policy, /*Qualified=*/false);
// If the enum is unnamed we do not add it to the list of enums i.e unusable.
}
if (buf.empty()) {
return nullptr;
}
const char* name = buf.c_str();
enumType = new TEnum(name, VD, cl);
UpdateEnumConstants(enumType, cl);
return enumType;
}
void TCling::HandleNewDecl(const void* DV, bool isDeserialized, std::set<TClass*> &modifiedTClasses) {
// Handle new declaration.
// Record the modified class, struct and namespaces in 'modifiedTClasses'.
const clang::Decl* D = static_cast<const clang::Decl*>(DV);
if (!D->isCanonicalDecl() && !isa<clang::NamespaceDecl>(D)
&& !dyn_cast<clang::RecordDecl>(D)) return;
if (isa<clang::FunctionDecl>(D->getDeclContext())
|| isa<clang::TagDecl>(D->getDeclContext()))
return;
// Don't list templates.
if (const clang::CXXRecordDecl* RD = dyn_cast<clang::CXXRecordDecl>(D)) {
if (RD->getDescribedClassTemplate())
return;
} else if (const clang::FunctionDecl* FD = dyn_cast<clang::FunctionDecl>(D)) {
if (FD->getDescribedFunctionTemplate())
return;
}
if (const RecordDecl *TD = dyn_cast<RecordDecl>(D)) {
if (TD->isCanonicalDecl() || TD->isThisDeclarationADefinition())
TCling__UpdateClassInfo(TD);
}
else if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
// Mostly just for EnumDecl (the other TagDecl are handled
// by the 'RecordDecl' if statement.
TCling__UpdateClassInfo(TD);
} else if (const NamespaceDecl* NSD = dyn_cast<NamespaceDecl>(D)) {
TCling__UpdateClassInfo(NSD);
}
// We care about declarations on the global scope.
if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
return;
// Enums are lazyly created, thus we don not need to handle them here.
if (isa<EnumDecl>(ND))
return;
// ROOT says that global is enum(lazylycreated)/var/field declared on the global
// scope.
if (!(isa<VarDecl>(ND)))
return;
// Skip if already in the list.
if (gROOT->GetListOfGlobals()->FindObject(ND->getNameAsString().c_str()))
return;
// Put the global constants and global enums in the corresponding lists.
gROOT->GetListOfGlobals()->Add(new TGlobal((DataMemberInfo_t *)
new TClingDataMemberInfo(GetInterpreterImpl(),
cast<ValueDecl>(ND), nullptr)));
}
}
extern "C"
void TCling__GetNormalizedContext(const ROOT::TMetaUtils::TNormalizedCtxt*& normCtxt)
{
// We are sure in this context of the type of the interpreter
normCtxt = &( (TCling*) gInterpreter)->GetNormalizedContext();
}
extern "C"
void TCling__UpdateListsOnCommitted(const cling::Transaction &T, cling::Interpreter*) {
((TCling*)gCling)->UpdateListsOnCommitted(T);
}
extern "C"
void TCling__UpdateListsOnUnloaded(const cling::Transaction &T) {
((TCling*)gCling)->UpdateListsOnUnloaded(T);
}
extern "C"
void TCling__InvalidateGlobal(const clang::Decl *D) {
((TCling*)gCling)->InvalidateGlobal(D);
}
extern "C"
void TCling__TransactionRollback(const cling::Transaction &T) {
((TCling*)gCling)->TransactionRollback(T);
}
extern "C" void TCling__LibraryLoadedRTTI(const void* dyLibHandle,
const char* canonicalName) {
((TCling*)gCling)->LibraryLoaded(dyLibHandle, canonicalName);
}
extern "C" void TCling__RegisterRdictForLoadPCM(const std::string &pcmFileNameFullPath, llvm::StringRef *pcmContent)
{
((TCling *)gCling)->RegisterRdictForLoadPCM(pcmFileNameFullPath, pcmContent);
}
extern "C" void TCling__LibraryUnloadedRTTI(const void* dyLibHandle,
const char* canonicalName) {
((TCling*)gCling)->LibraryUnloaded(dyLibHandle, canonicalName);
}
extern "C"
TObject* TCling__GetObjectAddress(const char *Name, void *&LookupCtx) {
return ((TCling*)gCling)->GetObjectAddress(Name, LookupCtx);
}
extern "C" const Decl* TCling__GetObjectDecl(TObject *obj) {
return ((TClingClassInfo*)obj->IsA()->GetClassInfo())->GetDecl();
}
extern "C" R__DLLEXPORT TInterpreter *CreateInterpreter(void* interpLibHandle,
const char* argv[])
{
auto tcling = new TCling("C++", "cling C++ Interpreter", argv, interpLibHandle);
return tcling;
}
extern "C" R__DLLEXPORT void DestroyInterpreter(TInterpreter *interp)
{
delete interp;
}
// Load library containing specified class. Returns 0 in case of error
// and 1 in case if success.
extern "C" int TCling__AutoLoadCallback(const char* className)
{
return ((TCling*)gCling)->AutoLoad(className);
}
extern "C" int TCling__AutoParseCallback(const char* className)
{
return ((TCling*)gCling)->AutoParse(className);
}
extern "C" const char* TCling__GetClassSharedLibs(const char* className, bool skipCore)
{
return ((TCling*)gCling)->GetClassSharedLibs(className, skipCore);
}
// Returns 0 for failure 1 for success
extern "C" int TCling__IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl* nsDecl)
{
return ((TCling*)gCling)->IsAutoLoadNamespaceCandidate(nsDecl);
}
extern "C" int TCling__CompileMacro(const char *fileName, const char *options)
{
string file(fileName);
string opt(options);
return gSystem->CompileMacro(file.c_str(), opt.c_str());
}
extern "C" void TCling__SplitAclicMode(const char* fileName, string &mode,
string &args, string &io, string &fname)
{
string file(fileName);
TString f, amode, arguments, aclicio;
f = gSystem->SplitAclicMode(file.c_str(), amode, arguments, aclicio);
mode = amode.Data(); args = arguments.Data();
io = aclicio.Data(); fname = f.Data();
}
//______________________________________________________________________________
//
//
//
#ifdef R__WIN32
extern "C" {
char *__unDName(char *demangled, const char *mangled, int out_len,
void * (* pAlloc )(size_t), void (* pFree )(void *),
unsigned short int flags);
}
#endif
////////////////////////////////////////////////////////////////////////////////
/// Find a template decl within N nested namespaces, 0<=N<inf
/// Assumes 1 and only 1 template present and 1 and only 1 entity contained
/// by the namespace. Example: `ns1::ns2::..::%nsN::%myTemplate`
/// Returns nullptr in case of error
static clang::ClassTemplateDecl* FindTemplateInNamespace(clang::Decl* decl)
{
using namespace clang;
if (NamespaceDecl* nsd = llvm::dyn_cast<NamespaceDecl>(decl)){
return FindTemplateInNamespace(*nsd->decls_begin());
}
if (ClassTemplateDecl* ctd = llvm::dyn_cast<ClassTemplateDecl>(decl)){
return ctd;
}
return nullptr; // something went wrong.
}
//______________________________________________________________________________
//
//
//
int TCling_GenerateDictionary(const std::vector<std::string> &classes,
const std::vector<std::string> &headers,
const std::vector<std::string> &fwdDecls,
const std::vector<std::string> &unknown)
{
//This function automatically creates the "LinkDef.h" file for templated
//classes then executes CompileMacro on it.
//The name of the file depends on the class name, and it's not generated again
//if the file exist.
if (classes.empty()) {
return 0;
}
// Use the name of the first class as the main name.
const std::string& className = classes[0];
//(0) prepare file name
TString fileName = "AutoDict_";
std::string::const_iterator sIt;
for (sIt = className.begin(); sIt != className.end(); ++sIt) {
if (*sIt == '<' || *sIt == '>' ||
*sIt == ' ' || *sIt == '*' ||
*sIt == ',' || *sIt == '&' ||
*sIt == ':') {
fileName += '_';
}
else {
fileName += *sIt;
}
}
if (classes.size() > 1) {
Int_t chk = 0;
std::vector<std::string>::const_iterator it = classes.begin();
while ((++it) != classes.end()) {
for (UInt_t cursor = 0; cursor != it->length(); ++cursor) {
chk = chk * 3 + it->at(cursor);
}
}
fileName += TString::Format("_%u", chk);
}
fileName += ".cxx";
if (gSystem->AccessPathName(fileName) != 0) {
//file does not exist
//(1) prepare file data
// If STL, also request iterators' operators.
// vector is special: we need to check whether
// vector::iterator is a typedef to pointer or a
// class.
static const std::set<std::string> sSTLTypes {
"vector","list","forward_list","deque","map","unordered_map","multimap",
"unordered_multimap","set","unordered_set","multiset","unordered_multiset",
"queue","priority_queue","stack","iterator"};
std::vector<std::string>::const_iterator it;
std::string fileContent("");
for (it = headers.begin(); it != headers.end(); ++it) {
fileContent += "#include \"" + *it + "\"\n";
}
for (it = unknown.begin(); it != unknown.end(); ++it) {
TClass* cl = TClass::GetClass(it->c_str());
if (cl && cl->GetDeclFileName()) {
TString header = gSystem->BaseName(cl->GetDeclFileName());
TString dir = gSystem->GetDirName(cl->GetDeclFileName());
TString dirbase(gSystem->BaseName(dir));
while (dirbase.Length() && dirbase != "."
&& dirbase != "include" && dirbase != "inc"
&& dirbase != "prec_stl") {
gSystem->PrependPathName(dirbase, header);
dir = gSystem->GetDirName(dir);
}
fileContent += TString("#include \"") + header + "\"\n";
}
}
for (it = fwdDecls.begin(); it != fwdDecls.end(); ++it) {
fileContent += "class " + *it + ";\n";
}
fileContent += "#ifdef __CLING__ \n";
fileContent += "#pragma link C++ nestedclasses;\n";
fileContent += "#pragma link C++ nestedtypedefs;\n";
for (it = classes.begin(); it != classes.end(); ++it) {
std::string n(*it);
size_t posTemplate = n.find('<');
std::set<std::string>::const_iterator iSTLType = sSTLTypes.end();
if (posTemplate != std::string::npos) {
n.erase(posTemplate, std::string::npos);
if (n.compare(0, 5, "std::") == 0) {
n.erase(0, 5);
}
iSTLType = sSTLTypes.find(n);
}
fileContent += "#pragma link C++ class ";
fileContent += *it + "+;\n" ;
if (iSTLType == sSTLTypes.end()) {
// Not an STL class; we need to allow the I/O of contained
// classes (now that we have a dictionary for them).
fileContent += "#pragma link C++ class " + *it + "::*+;\n" ;
}
}
fileContent += "#endif\n";
//end(1)
//(2) prepare the file
FILE* filePointer;
filePointer = fopen(fileName, "w");
if (filePointer == nullptr) {
//can't open a file
return 1;
}
//end(2)
//write data into the file
fprintf(filePointer, "%s", fileContent.c_str());
fclose(filePointer);
}
//(3) checking if we can compile a macro, if not then cleaning
Int_t oldErrorIgnoreLevel = gErrorIgnoreLevel;
gErrorIgnoreLevel = kWarning; // no "Info: creating library..."
Int_t ret = gSystem->CompileMacro(fileName, "k");
gErrorIgnoreLevel = oldErrorIgnoreLevel;
if (ret == 0) { //can't compile a macro
return 2;
}
//end(3)
return 0;
}
int TCling_GenerateDictionary(const std::string& className,
const std::vector<std::string> &headers,
const std::vector<std::string> &fwdDecls,
const std::vector<std::string> &unknown)
{
//This function automatically creates the "LinkDef.h" file for templated
//classes then executes CompileMacro on it.
//The name of the file depends on the class name, and it's not generated again
//if the file exist.
std::vector<std::string> classes;
classes.push_back(className);
return TCling_GenerateDictionary(classes, headers, fwdDecls, unknown);
}
//______________________________________________________________________________
//
//
//
// It is a "fantom" method to synchronize user keyboard input
// and ROOT prompt line (for WIN32)
const char* fantomline = "TRint::EndOfLineAction();";
//______________________________________________________________________________
//
//
//
void* TCling::fgSetOfSpecials = nullptr;
//______________________________________________________________________________
//
// llvm error handler through exceptions; see also cling/UserInterface
//
namespace {
// Handle fatal llvm errors by throwing an exception.
// Yes, throwing exceptions in error handlers is bad.
// Doing nothing is pretty terrible, too.
void exceptionErrorHandler(void * /*user_data*/,
const char *reason,
bool /*gen_crash_diag*/) {
throw std::runtime_error(std::string(">>> Interpreter compilation error:\n") + reason);
}
}
//______________________________________________________________________________
//
//
//
////////////////////////////////////////////////////////////////////////////////
namespace{
// An instance of this class causes the diagnostics of clang to be suppressed
// during its lifetime
class clangDiagSuppr {
public:
clangDiagSuppr(clang::DiagnosticsEngine& diag): fDiagEngine(diag){
fOldDiagValue = fDiagEngine.getIgnoreAllWarnings();
fDiagEngine.setIgnoreAllWarnings(true);
}
~clangDiagSuppr() {
fDiagEngine.setIgnoreAllWarnings(fOldDiagValue);
}
private:
clang::DiagnosticsEngine& fDiagEngine;
bool fOldDiagValue;
};
}
////////////////////////////////////////////////////////////////////////////////
/// Allow calling autoparsing from TMetaUtils
bool TClingLookupHelper__AutoParse(const char *cname)
{
return gCling->AutoParse(cname);
}
////////////////////////////////////////////////////////////////////////////////
/// Try hard to avoid looking up in the Cling database as this could enduce
/// an unwanted autoparsing.
bool TClingLookupHelper__ExistingTypeCheck(const std::string &tname,
std::string &result)
{
result.clear();
unsigned long offset = 0;
if (strncmp(tname.c_str(), "const ", 6) == 0) {
offset = 6;
}
unsigned long end = tname.length();
while( end && (tname[end-1]=='&' || tname[end-1]=='*' || tname[end-1]==']') ) {
if ( tname[end-1]==']' ) {
--end;
while ( end && tname[end-1]!='[' ) --end;
}
--end;
}
std::string innerbuf;
const char *inner;
if (end != tname.length()) {
innerbuf = tname.substr(offset,end-offset);
inner = innerbuf.c_str();
} else {
inner = tname.c_str()+offset;
}
//if (strchr(tname.c_str(),'[')!=0) fprintf(stderr,"DEBUG: checking on %s vs %s %lu %lu\n",tname.c_str(),inner,offset,end);
if (gROOT->GetListOfClasses()->FindObject(inner)
|| TClassTable::Check(inner,result) ) {
// This is a known class.
return true;
}
THashTable *typeTable = dynamic_cast<THashTable*>( gROOT->GetListOfTypes() );
TDataType *type = (TDataType *)typeTable->THashTable::FindObject( inner );
if (type) {
// This is a raw type and an already loaded typedef.
const char *newname = type->GetFullTypeName();
if (type->GetType() == kLong64_t) {
newname = "Long64_t";
} else if (type->GetType() == kULong64_t) {
newname = "ULong64_t";
}
if (strcmp(inner,newname) == 0) {
return true;
}
if (offset) result = "const ";
result += newname;
if ( end != tname.length() ) {
result += tname.substr(end,tname.length()-end);
}
if (result == tname) result.clear();
return true;
}
// Check if the name is an enumerator
const auto lastPos = TClassEdit::GetUnqualifiedName(inner);
if (lastPos != inner) // Main switch: case 1 - scoped enum, case 2 global enum
{
// We have a scope
// All of this C gymnastic is to avoid allocations on the heap
const auto enName = lastPos;
const auto scopeNameSize = ((Long64_t)lastPos - (Long64_t)inner) / sizeof(decltype(*lastPos)) - 2;
char *scopeName = new char[scopeNameSize + 1];
strncpy(scopeName, inner, scopeNameSize);
scopeName[scopeNameSize] = '\0';
// Check if the scope is in the list of classes
if (auto scope = static_cast<TClass *>(gROOT->GetListOfClasses()->FindObject(scopeName))) {
auto enumTable = dynamic_cast<const THashList *>(scope->GetListOfEnums(false));
if (enumTable && enumTable->THashList::FindObject(enName)) { delete [] scopeName; return true; }
}
// It may still be in one of the loaded protoclasses
else if (auto scope = static_cast<TProtoClass *>(gClassTable->GetProtoNorm(scopeName))) {
auto listOfEnums = scope->GetListOfEnums();
if (listOfEnums) { // it could be null: no enumerators in the protoclass
auto enumTable = dynamic_cast<const THashList *>(listOfEnums);
if (enumTable && enumTable->THashList::FindObject(enName)) { delete [] scopeName; return true; }
}
}
delete [] scopeName;
} else
{
// We don't have any scope: this could only be a global enum
auto enumTable = dynamic_cast<const THashList *>(gROOT->GetListOfEnums());
if (enumTable && enumTable->THashList::FindObject(inner)) return true;
}
if (gCling->GetClassSharedLibs(inner))
{
// This is a class name.
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////