-
Notifications
You must be signed in to change notification settings - Fork 0
/
r.cxx
2780 lines (2278 loc) · 76.1 KB
/
r.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
/* -----------------------------------------------------------------------------
* This file is part of SWIG, which is licensed as a whole under version 3
* (or any later version) of the GNU General Public License. Some additional
* terms also apply to certain portions of SWIG. The full details of the SWIG
* license and copyrights can be found in the LICENSE and COPYRIGHT files
* included with the SWIG source code as distributed by the SWIG developers
* and at http://www.swig.org/legal.html.
*
* r.cxx
*
* R language module for SWIG.
* ----------------------------------------------------------------------------- */
#include "swigmod.h"
static const double DEFAULT_NUMBER = .0000123456712312312323;
static String* replaceInitialDash(const String *name)
{
String *retval;
if (!Strncmp(name, "_", 1)) {
retval = Copy(name);
Insert(retval, 0, "s");
} else {
retval = Copy(name);
}
return retval;
}
static String * getRTypeName(SwigType *t, int *outCount = NULL) {
String *b = SwigType_base(t);
List *els = SwigType_split(t);
int count = 0;
int i;
if(Strncmp(b, "struct ", 7) == 0)
Replace(b, "struct ", "", DOH_REPLACE_FIRST);
/* Printf(stdout, "<getRTypeName> %s,base = %s\n", t, b);
for(i = 0; i < Len(els); i++)
Printf(stdout, "%d) %s, ", i, Getitem(els,i));
Printf(stdout, "\n"); */
for(i = 0; i < Len(els); i++) {
String *el = Getitem(els, i);
if(Strcmp(el, "p.") == 0 || Strncmp(el, "a(", 2) == 0) {
count++;
Append(b, "Ref");
}
}
if(outCount)
*outCount = count;
String *tmp = NewString("");
char *retName = Char(SwigType_manglestr(t));
Insert(tmp, 0, retName);
return tmp;
/*
if(count)
return(b);
Delete(b);
return(NewString(""));
*/
}
/*********************
Tries to get the name of the R class corresponding to the given type
e.g. struct A * is ARef, struct A** is ARefRef.
Now handles arrays, i.e. struct A[2]
****************/
static String *getRClassName(String *retType, int /*addRef*/ = 1, int upRef=0) {
String *tmp = NewString("");
SwigType *resolved = SwigType_typedef_resolve_all(retType);
char *retName = Char(SwigType_manglestr(resolved));
if (upRef) {
Printf(tmp, "_p%s", retName);
} else{
Insert(tmp, 0, retName);
}
return tmp;
/*
#if 1
List *l = SwigType_split(retType);
int n = Len(l);
if(!l || n == 0) {
#ifdef R_SWIG_VERBOSE
if (debugMode)
Printf(stdout, "SwigType_split return an empty list for %s\n",
retType);
#endif
return(tmp);
}
String *el = Getitem(l, n-1);
char *ptr = Char(el);
if(strncmp(ptr, "struct ", 7) == 0)
ptr += 7;
Printf(tmp, "%s", ptr);
if(addRef) {
for(int i = 0; i < n; i++) {
if(Strcmp(Getitem(l, i), "p.") == 0 ||
Strncmp(Getitem(l, i), "a(", 2) == 0)
Printf(tmp, "Ref");
}
}
#else
char *retName = Char(SwigType_manglestr(retType));
if(!retName)
return(tmp);
if(addRef) {
while(retName && strlen(retName) > 1 && strncmp(retName, "_p", 2) == 0) {
retName += 2;
Printf(tmp, "Ref");
}
}
if(retName[0] == '_')
retName ++;
Insert(tmp, 0, retName);
#endif
return tmp;
*/
}
/*********************
Tries to get the name of the R class corresponding to the given type
e.g. struct A * is ARef, struct A** is ARefRef.
Now handles arrays, i.e. struct A[2]
****************/
static String * getRClassNameCopyStruct(String *retType, int addRef) {
String *tmp = NewString("");
#if 1
List *l = SwigType_split(retType);
int n = Len(l);
if(!l || n == 0) {
#ifdef R_SWIG_VERBOSE
Printf(stdout, "SwigType_split return an empty list for %s\n", retType);
#endif
return(tmp);
}
String *el = Getitem(l, n-1);
char *ptr = Char(el);
if(strncmp(ptr, "struct ", 7) == 0)
ptr += 7;
Printf(tmp, "%s", ptr);
if(addRef) {
for(int i = 0; i < n; i++) {
if(Strcmp(Getitem(l, i), "p.") == 0 ||
Strncmp(Getitem(l, i), "a(", 2) == 0)
Printf(tmp, "Ref");
}
}
#else
char *retName = Char(SwigType_manglestr(retType));
if(!retName)
return(tmp);
if(addRef) {
while(retName && strlen(retName) > 1 &&
strncmp(retName, "_p", 2) == 0) {
retName += 2;
Printf(tmp, "Ref");
}
}
if(retName[0] == '_')
retName ++;
Insert(tmp, 0, retName);
#endif
return tmp;
}
/*********************************
Write the elements of a list to the File*, one element per line.
If quote is true, surround the element with "element".
This takes care of inserting a tab in front of each line and also
a comma after each element, except the last one.
**********************************/
static void writeListByLine(List *l, File *out, bool quote = 0) {
int i, n = Len(l);
for(i = 0; i < n; i++)
Printf(out, "%s%s%s%s%s\n", tab8,
quote ? "\"" :"",
Getitem(l, i),
quote ? "\"" :"", i < n-1 ? "," : "");
}
static const char *usage = "\
R Options (available with -r)\n\
-copystruct - Emit R code to copy C structs (on by default)\n\
-cppcast - Enable C++ casting operators (default) \n\
-debug - Output debug\n\
-dll <name> - Name of the DLL (without the .dll or .so suffix).\n\
Default is the module name.\n\
-gc - Aggressive garbage collection\n\
-memoryprof - Add memory profile\n\
-namespace - Output NAMESPACE file\n\
-no-init-code - Turn off the generation of the R_init_<pkgname> code\n\
(registration information still generated)\n\
-package <name> - Package name for the PACKAGE argument of the R .Call()\n\
invocations. Default is the module name.\n\
";
/************
Display the help for this module on the screen/console.
*************/
static void showUsage() {
fputs(usage, stdout);
}
static bool expandTypedef(SwigType *t) {
if (SwigType_isenum(t)) return false;
String *prefix = SwigType_prefix(t);
if (Strncmp(prefix, "f", 1)) return false;
if (Strncmp(prefix, "p.f", 3)) return false;
return true;
}
/*****
Determine whether we should add a .copy argument to the S function
that wraps/interfaces to the routine that returns the given type.
*****/
static int addCopyParameter(SwigType *type) {
int ok = 0;
ok = Strncmp(type, "struct ", 7) == 0 || Strncmp(type, "p.struct ", 9) == 0;
if(!ok) {
ok = Strncmp(type, "p.", 2);
}
return(ok);
}
static void replaceRClass(String *tm, SwigType *type) {
String *tmp = getRClassName(type);
String *tmp_base = getRClassName(type, 0);
String *tmp_ref = getRClassName(type, 1, 1);
Replaceall(tm, "$R_class", tmp);
Replaceall(tm, "$*R_class", tmp_base);
Replaceall(tm, "$&R_class", tmp_ref);
Delete(tmp); Delete(tmp_base); Delete(tmp_ref);
}
static double getNumber(String *value) {
double d = DEFAULT_NUMBER;
if(Char(value)) {
if(sscanf(Char(value), "%lf", &d) != 1)
return(DEFAULT_NUMBER);
}
return(d);
}
class R : public Language {
public:
R();
void registerClass(Node *n);
void main(int argc, char *argv[]);
int top(Node *n);
void dispatchFunction(Node *n);
int functionWrapper(Node *n);
int constantWrapper(Node *n);
int variableWrapper(Node *n);
int classDeclaration(Node *n);
int enumDeclaration(Node *n);
int membervariableHandler(Node *n);
int typedefHandler(Node *n);
static List *Swig_overload_rank(Node *n,
bool script_lang_wrapping);
int memberfunctionHandler(Node *n) {
if (debugMode)
Printf(stdout, "<memberfunctionHandler> %s %s\n",
Getattr(n, "name"),
Getattr(n, "type"));
member_name = Getattr(n, "sym:name");
processing_class_member_function = 1;
int status = Language::memberfunctionHandler(n);
processing_class_member_function = 0;
return status;
}
/* Grab the name of the current class being processed so that we can
deal with members of that class. */
int classHandler(Node *n){
if(!ClassMemberTable)
ClassMemberTable = NewHash();
class_name = Getattr(n, "name");
int status = Language::classHandler(n);
class_name = NULL;
return status;
}
// Not used:
String *runtimeCode();
protected:
int addRegistrationRoutine(String *rname, int nargs);
int outputRegistrationRoutines(File *out);
int outputCommandLineArguments(File *out);
int generateCopyRoutines(Node *n);
int DumpCode(Node *n);
int OutputMemberReferenceMethod(String *className, int isSet, List *el, File *out);
int OutputArrayMethod(String *className, List *el, File *out);
int OutputClassMemberTable(Hash *tb, File *out);
int OutputClassMethodsTable(File *out);
int OutputClassAccessInfo(Hash *tb, File *out);
int defineArrayAccessors(SwigType *type);
void addNamespaceFunction(String *name) {
if(!namespaceFunctions)
namespaceFunctions = NewList();
Append(namespaceFunctions, name);
}
void addNamespaceMethod(String *name) {
if(!namespaceMethods)
namespaceMethods = NewList();
Append(namespaceMethods, name);
}
String* processType(SwigType *t, Node *n, int *nargs = NULL);
String *createFunctionPointerHandler(SwigType *t, Node *n, int *nargs);
int addFunctionPointerProxy(String *name, Node *n, SwigType *t, String *s_paramTypes) {
/*XXX Do we need to put the t in there to get the return type later. */
if(!functionPointerProxyTable)
functionPointerProxyTable = NewHash();
Setattr(functionPointerProxyTable, name, n);
Setattr(SClassDefs, name, name);
Printv(s_classes, "setClass('",
name,
"',\n", tab8,
"prototype = list(parameterTypes = c(", s_paramTypes, "),\n",
tab8, tab8, tab8,
"returnType = '", SwigType_manglestr(t), "'),\n", tab8,
"contains = 'CRoutinePointer')\n\n##\n", NIL);
return SWIG_OK;
}
void addSMethodInfo(String *name,
String *argType, int nargs);
// Simple initialization such as constant strings that can be reused.
void init();
void addAccessor(String *memberName, Wrapper *f,
String *name, int isSet = -1);
static int getFunctionPointerNumArgs(Node *n, SwigType *tt);
protected:
bool copyStruct;
bool memoryProfile;
bool aggressiveGc;
// Strings into which we cumulate the generated code that is to be written
//vto the files.
String *sfile;
String *f_init;
String *s_classes;
String *f_begin;
String *f_runtime;
String *f_wrapper;
String *s_header;
String *f_wrappers;
String *s_init;
String *s_init_routine;
String *s_namespace;
// State variables that carry information across calls to functionWrapper()
// from member accessors and class declarations.
String *opaqueClassDeclaration;
int processing_variable;
int processing_member_access_function;
String *member_name;
String *class_name;
int processing_class_member_function;
List *class_member_functions;
List *class_member_set_functions;
/* */
Hash *ClassMemberTable;
Hash *ClassMethodsTable;
Hash *SClassDefs;
Hash *SMethodInfo;
// Information about routines that are generated and to be registered with
// R for dynamic lookup.
Hash *registrationTable;
Hash *functionPointerProxyTable;
List *namespaceFunctions;
List *namespaceMethods;
List *namespaceClasses; // Probably can do this from ClassMemberTable.
// Store a copy of the command line.
// Need only keep a string that has it formatted.
char **Argv;
int Argc;
bool inCPlusMode;
// State variables that we remember from the command line settings
// potentially that govern the code we generate.
String *DllName;
String *Rpackage;
bool noInitializationCode;
bool outputNamespaceInfo;
String *UnProtectWrapupCode;
// Static members
static bool debugMode;
};
R::R() :
copyStruct(false),
memoryProfile(false),
aggressiveGc(false),
sfile(0),
f_init(0),
s_classes(0),
f_begin(0),
f_runtime(0),
f_wrapper(0),
s_header(0),
f_wrappers(0),
s_init(0),
s_init_routine(0),
s_namespace(0),
opaqueClassDeclaration(0),
processing_variable(0),
processing_member_access_function(0),
member_name(0),
class_name(0),
processing_class_member_function(0),
class_member_functions(0),
class_member_set_functions(0),
ClassMemberTable(0),
ClassMethodsTable(0),
SClassDefs(0),
SMethodInfo(0),
registrationTable(0),
functionPointerProxyTable(0),
namespaceFunctions(0),
namespaceMethods(0),
namespaceClasses(0),
Argv(0),
Argc(0),
inCPlusMode(false),
DllName(0),
Rpackage(0),
noInitializationCode(false),
outputNamespaceInfo(false),
UnProtectWrapupCode(0) {
}
bool R::debugMode = false;
int R::getFunctionPointerNumArgs(Node *n, SwigType *tt) {
(void) tt;
n = Getattr(n, "type");
if (debugMode)
Printf(stdout, "type: %s\n", n);
ParmList *parms = Getattr(n, "parms");
if (debugMode)
Printf(stdout, "parms = %p\n", parms);
return ParmList_len(parms);
}
void R::addSMethodInfo(String *name, String *argType, int nargs) {
(void) argType;
if(!SMethodInfo)
SMethodInfo = NewHash();
if (debugMode)
Printf(stdout, "[addMethodInfo] %s\n", name);
Hash *tb = Getattr(SMethodInfo, name);
if(!tb) {
tb = NewHash();
Setattr(SMethodInfo, name, tb);
}
String *str = Getattr(tb, "max");
int max = -1;
if(str)
max = atoi(Char(str));
if(max < nargs) {
if(str) Delete(str);
str = NewStringf("%d", max);
Setattr(tb, "max", str);
}
}
/*
Returns the name of the new routine.
*/
String * R::createFunctionPointerHandler(SwigType *t, Node *n, int *numArgs) {
String *funName = SwigType_manglestr(t);
/* See if we have already processed this one. */
if(functionPointerProxyTable && Getattr(functionPointerProxyTable, funName))
return funName;
if (debugMode)
Printf(stdout, "<createFunctionPointerHandler> Defining %s\n", t);
SwigType *rettype = Copy(Getattr(n, "type"));
SwigType *funcparams = SwigType_functionpointer_decompose(rettype);
String *rtype = SwigType_str(rettype, 0);
// ParmList *parms = Getattr(n, "parms");
// memory leak
ParmList *parms = SwigType_function_parms(SwigType_del_pointer(Copy(t)), n);
if (debugMode) {
Printf(stdout, "Type: %s\n", t);
Printf(stdout, "Return type: %s\n", SwigType_base(t));
}
bool isVoidType = Strcmp(rettype, "void") == 0;
if (debugMode)
Printf(stdout, "%s is void ? %s (%s)\n", funName, isVoidType ? "yes" : "no", rettype);
Wrapper *f = NewWrapper();
/* Go through argument list, attach lnames for arguments */
int i = 0;
Parm *p = parms;
for (i = 0; p; p = nextSibling(p), ++i) {
String *arg = Getattr(p, "name");
String *lname;
if (!arg && Cmp(Getattr(p, "type"), "void")) {
lname = NewStringf("s_arg%d", i+1);
Setattr(p, "name", lname);
} else
lname = arg;
Setattr(p, "lname", lname);
}
Swig_typemap_attach_parms("out", parms, f);
Swig_typemap_attach_parms("scoerceout", parms, f);
Swig_typemap_attach_parms("scheck", parms, f);
Printf(f->def, "%s %s(", rtype, funName);
emit_parameter_variables(parms, f);
emit_return_variable(n, rettype, f);
// emit_attach_parmmaps(parms,f);
/* Using weird name and struct to avoid potential conflicts. */
Wrapper_add_local(f, "r_swig_cb_data", "RCallbackFunctionData *r_swig_cb_data = R_SWIG_getCallbackFunctionData()");
String *lvar = NewString("r_swig_cb_data");
Wrapper_add_local(f, "r_tmp", "SEXP r_tmp"); // for use in converting arguments to R objects for call.
Wrapper_add_local(f, "r_nprotect", "int r_nprotect = 0"); // for use in converting arguments to R objects for call.
Wrapper_add_local(f, "r_vmax", "char * r_vmax= 0"); // for use in converting arguments to R objects for call.
// Add local for error code in return value. This is not in emit_return_variable because that assumes an out typemap
// whereas the type makes are reverse
Wrapper_add_local(f, "ecode", "int ecode = 0");
p = parms;
int nargs = ParmList_len(parms);
if(numArgs) {
*numArgs = nargs;
if (debugMode)
Printf(stdout, "Setting number of parameters to %d\n", *numArgs);
}
String *setExprElements = NewString("");
String *s_paramTypes = NewString("");
for(i = 0; p; i++) {
SwigType *tt = Getattr(p, "type");
SwigType *name = Getattr(p, "name");
String *tm = Getattr(p, "tmap:out");
Printf(f->def, "%s %s", SwigType_str(tt, 0), name);
if(tm) {
Replaceall(tm, "$1", name);
if (SwigType_isreference(tt)) {
String *tmp = NewString("");
Append(tmp, "*");
Append(tmp, name);
Replaceall(tm, tmp, name);
}
Replaceall(tm, "$result", "r_tmp");
replaceRClass(tm, Getattr(p,"type"));
Replaceall(tm,"$owner", "R_SWIG_EXTERNAL");
}
Printf(setExprElements, "%s\n", tm);
Printf(setExprElements, "SETCAR(r_swig_cb_data->el, %s);\n", "r_tmp");
Printf(setExprElements, "r_swig_cb_data->el = CDR(r_swig_cb_data->el);\n\n");
Printf(s_paramTypes, "'%s'", SwigType_manglestr(tt));
p = nextSibling(p);
if(p) {
Printf(f->def, ", ");
Printf(s_paramTypes, ", ");
}
}
Printf(f->def, ") {\n");
Printf(f->code, "Rf_protect(%s->expr = Rf_allocVector(LANGSXP, %d));\n", lvar, nargs + 1);
Printf(f->code, "r_nprotect++;\n");
Printf(f->code, "r_swig_cb_data->el = r_swig_cb_data->expr;\n\n");
Printf(f->code, "SETCAR(r_swig_cb_data->el, r_swig_cb_data->fun);\n");
Printf(f->code, "r_swig_cb_data->el = CDR(r_swig_cb_data->el);\n\n");
Printf(f->code, "%s\n\n", setExprElements);
Printv(f->code, "r_swig_cb_data->retValue = R_tryEval(",
"r_swig_cb_data->expr,",
" R_GlobalEnv,",
" &r_swig_cb_data->errorOccurred",
");\n",
NIL);
Printv(f->code, "\n",
"if(r_swig_cb_data->errorOccurred) {\n",
"R_SWIG_popCallbackFunctionData(1);\n",
"Rf_error(\"error in calling R function as a function pointer (",
funName,
")\");\n",
"}\n",
NIL);
if(!isVoidType) {
/* Need to deal with the return type of the function pointer, not the function pointer itself.
So build a new node that has the relevant pieces.
XXX Have to be a little more clever so that we can deal with struct A * - the * is getting lost.
Is this still true? If so, will a SwigType_push() solve things?
*/
Parm *bbase = NewParmNode(rettype, n);
String *returnTM = Swig_typemap_lookup("in", bbase, Swig_cresult_name(), f);
if(returnTM) {
String *tm = returnTM;
Replaceall(tm,"$input", "r_swig_cb_data->retValue");
Replaceall(tm,"$target", Swig_cresult_name());
replaceRClass(tm, rettype);
Replaceall(tm,"$owner", "R_SWIG_EXTERNAL");
Replaceall(tm,"$disown","0");
Printf(f->code, "%s\n", tm);
}
Delete(bbase);
}
Printv(f->code, "R_SWIG_popCallbackFunctionData(1);\n", NIL);
Printv(f->code, "\n", UnProtectWrapupCode, NIL);
if (SwigType_isreference(rettype)) {
Printv(f->code, "return *", Swig_cresult_name(), ";\n", NIL);
} else if(!isVoidType)
Printv(f->code, "return ", Swig_cresult_name(), ";\n", NIL);
Printv(f->code, "\n}\n", NIL);
Replaceall(f->code, "SWIG_exception_fail", "SWIG_exception_noreturn");
/* To coerce correctly in S, we really want to have an extra/intermediate
function that handles the scoerceout.
We need to check if any of the argument types have an entry in
that map. If none do, the ignore and call the function straight.
Otherwise, generate the a marshalling function.
Need to be able to find it in S. Or use an entirely generic one
that evaluates the expressions.
Handle errors in the evaluation of the function by restoring
the stack, if there is one in use for this function (i.e. no
userData).
*/
Wrapper_print(f, f_wrapper);
addFunctionPointerProxy(funName, n, t, s_paramTypes);
Delete(s_paramTypes);
Delete(rtype);
Delete(rettype);
Delete(funcparams);
DelWrapper(f);
return funName;
}
void R::init() {
UnProtectWrapupCode =
NewStringf("%s", "vmaxset(r_vmax);\nif(r_nprotect) Rf_unprotect(r_nprotect);\n\n");
SClassDefs = NewHash();
sfile = NewString("");
f_init = NewString("");
s_header = NewString("");
f_begin = NewString("");
f_runtime = NewString("");
f_wrapper = NewString("");
s_classes = NewString("");
s_init = NewString("");
s_init_routine = NewString("");
}
#if 0
int R::cDeclaration(Node *n) {
SwigType *t = Getattr(n, "type");
SwigType *name = Getattr(n, "name");
if (debugMode)
Printf(stdout, "cDeclaration (%s): %s\n", name, SwigType_lstr(t, 0));
return Language::cDeclaration(n);
}
#endif
/**
Method from Language that is called to start the entire
processing off, i.e. the generation of the code.
It is called after the input has been read and parsed.
Here we open the output streams and generate the code.
***/
int R::top(Node *n) {
String *module = Getattr(n, "name");
if(!Rpackage)
Rpackage = Copy(module);
if(!DllName)
DllName = Copy(module);
if(outputNamespaceInfo) {
s_namespace = NewString("");
Swig_register_filebyname("snamespace", s_namespace);
Printf(s_namespace, "useDynLib(%s)\n", DllName);
}
/* Associate the different streams with names so that they can be used in %insert directives by the
typemap code. */
Swig_register_filebyname("sinit", s_init);
Swig_register_filebyname("sinitroutine", s_init_routine);
Swig_register_filebyname("begin", f_begin);
Swig_register_filebyname("runtime", f_runtime);
Swig_register_filebyname("init", f_init);
Swig_register_filebyname("header", s_header);
Swig_register_filebyname("wrapper", f_wrapper);
Swig_register_filebyname("s", sfile);
Swig_register_filebyname("sclasses", s_classes);
Swig_banner(f_begin);
Printf(f_runtime, "\n");
Printf(f_runtime, "#define SWIGR\n");
Printf(f_runtime, "\n");
Swig_banner_target_lang(s_init, "#");
outputCommandLineArguments(s_init);
Printf(f_wrapper, "#ifdef __cplusplus\n");
Printf(f_wrapper, "extern \"C\" {\n");
Printf(f_wrapper, "#endif\n\n");
Language::top(n);
Printf(f_wrapper, "#ifdef __cplusplus\n");
Printf(f_wrapper, "}\n");
Printf(f_wrapper, "#endif\n");
String *type_table = NewString("");
SwigType_emit_type_table(f_runtime,f_wrapper);
Delete(type_table);
if(ClassMemberTable) {
//XXX OutputClassAccessInfo(ClassMemberTable, sfile);
Delete(ClassMemberTable);
ClassMemberTable = NULL;
}
Printf(f_init,"}\n");
if(registrationTable)
outputRegistrationRoutines(f_init);
/* Now arrange to write the 2 files - .S and .c. */
DumpCode(n);
Delete(sfile);
Delete(s_classes);
Delete(s_init);
Delete(f_wrapper);
Delete(f_init);
Delete(s_header);
Delete(f_runtime);
Delete(f_begin);
return SWIG_OK;
}
/*****************************************************
Write the generated code to the .S and the .c files.
****************************************************/
int R::DumpCode(Node *n) {
String *output_filename = NewString("");
/* The name of the file in which we will generate the S code. */
Printf(output_filename, "%s%s.R", SWIG_output_directory(), Rpackage);
#ifdef R_SWIG_VERBOSE
Printf(stdout, "Writing S code to %s\n", output_filename);
#endif
File *scode = NewFile(output_filename, "w", SWIG_output_files());
if (!scode) {
FileErrorDisplay(output_filename);
SWIG_exit(EXIT_FAILURE);
}
Delete(output_filename);
Printf(scode, "%s\n\n", s_init);
Printf(scode, "%s\n\n", s_classes);
Printf(scode, "%s\n", sfile);
Delete(scode);
String *outfile = Getattr(n,"outfile");
File *runtime = NewFile(outfile,"w", SWIG_output_files());
if (!runtime) {
FileErrorDisplay(outfile);
SWIG_exit(EXIT_FAILURE);
}
Printf(runtime, "%s", f_begin);
Printf(runtime, "%s\n", f_runtime);
Printf(runtime, "%s\n", s_header);
Printf(runtime, "%s\n", f_wrapper);
Printf(runtime, "%s\n", f_init);
Delete(runtime);
if(outputNamespaceInfo) {
output_filename = NewString("");
Printf(output_filename, "%sNAMESPACE", SWIG_output_directory());
File *ns = NewFile(output_filename, "w", SWIG_output_files());
if (!ns) {
FileErrorDisplay(output_filename);
SWIG_exit(EXIT_FAILURE);
}
Delete(output_filename);
Printf(ns, "%s\n", s_namespace);
Printf(ns, "\nexport(\n");
writeListByLine(namespaceFunctions, ns);
Printf(ns, ")\n");
Printf(ns, "\nexportMethods(\n");
writeListByLine(namespaceFunctions, ns, 1);
Printf(ns, ")\n");
Delete(ns);
Delete(s_namespace);
}
return SWIG_OK;
}
/*
We may need to do more.... so this is left as a
stub for the moment.
*/
int R::OutputClassAccessInfo(Hash *tb, File *out) {
int n = OutputClassMemberTable(tb, out);
OutputClassMethodsTable(out);
return n;
}
/************************************************************************
Currently this just writes the information collected about the
different methods of the C++ classes that have been processed
to the console.
This will be used later to define S4 generics and methods.
**************************************************************************/
int R::OutputClassMethodsTable(File *) {
Hash *tb = ClassMethodsTable;
if(!tb)
return SWIG_OK;
List *keys = Keys(tb);
String *key;
int i, n = Len(keys);
if (debugMode) {
for(i = 0; i < n ; i++ ) {
key = Getitem(keys, i);
Printf(stdout, "%d) %s\n", i, key);
List *els = Getattr(tb, key);
int nels = Len(els);
Printf(stdout, "\t");
for(int j = 0; j < nels; j+=2) {
Printf(stdout, "%s%s", Getitem(els, j), j < nels - 1 ? ", " : "");
Printf(stdout, "%s\n", Getitem(els, j+1));
}
Printf(stdout, "\n");
}
}
return SWIG_OK;
}
/*
Iterate over the <class name>_set and <>_get
elements and generate the $ and $<- functions
that provide constrained access to the member
fields in these elements.
tb - a hash table that is built up in functionWrapper
as we process each membervalueHandler.
The entries are indexed by <class name>_set and
<class_name>_get. Each entry is a List *.
out - the stram where the code is to be written. This is the S
code stream as we generate only S code here..
*/
int R::OutputClassMemberTable(Hash *tb, File *out) {
List *keys = Keys(tb), *el;
String *key;
int i, n = Len(keys);
/* Loop over all the <Class>_set and <Class>_get entries in the table. */
if(n && outputNamespaceInfo) {
Printf(s_namespace, "exportClasses(");
}
for(i = 0; i < n; i++) {
key = Getitem(keys, i);
el = Getattr(tb, key);
String *className = Getitem(el, 0);
char *ptr = Char(key);
ptr = &ptr[Len(key) - 3];
int isSet = strcmp(ptr, "set") == 0;
// OutputArrayMethod(className, el, out);
OutputMemberReferenceMethod(className, isSet, el, out);
if(outputNamespaceInfo)
Printf(s_namespace, "\"%s\"%s", className, i < n-1 ? "," : "");
}
if(n && outputNamespaceInfo) {
Printf(s_namespace, ")\n");
}