forked from rca/PySPICE
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmkwrapper.py
More file actions
1328 lines (1041 loc) · 43.3 KB
/
mkwrapper.py
File metadata and controls
1328 lines (1041 loc) · 43.3 KB
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
#!/usr/bin/env python
#
# Generate a SPICE python wrapper
#
# Run this command by providing the location of the unpacked toolkit
# directory:
#
# mkwrapper.py /path/to/cspice/toolkit
#
# Author: Roberto Aguilar, roberto.c.aguilar@jpl.nasa.gov
#
# Released under the BSD license, see LICENSE for details
#
# $Id$
import os, sys
import traceback
import pprint
from cStringIO import StringIO
spiceintType = 'BAD'
spiceintType1 = 'B'
# This is a parameter class that is used to hold all the information about a
# parameter. Initially there is nothing in it. The object is populated with
# arbritrary information as the items are needed. This is controlled using
# the setattr and getattr functions in the class
class Container(dict):
def __getattr__(self, key):
val = self.get(key, None)
return val
def __setattr__(self, key, val):
self[key] = val
# look for these types of functions in the input stream in order to
# generate the wrappers.
function_types = ('ConstSpiceChar', 'SpiceBoolean', 'SpiceChar', 'SpiceDouble', 'SpiceInt', 'void')
### fix for output arguments mislabeled as inputs in source files
### - Key is variable name (e.g. 'c')
### - Value is tuple of toolkit routine names (e.g. 'whtevr_c') where that
### variable name should be an output but is labeled as an input
### in the -Brief_I/O sections of the source file
mislabeled_outputs = dict( c=('wndifd_c','wnintd_c','wnunid_c',)
, mout=('xpose_c','xpose6_c',)
)
fixparam = dict( cvals=dict( gcpool_c='SpiceChar * cvals')
)
### Rename these to something else
RESERVED_NAMES = ('free',)
# Reasons for excluding the following functions
### N0065
# edterm_c - TEMPORARY: new function in N0065, can't handle [ ]
# illumg_c - no .c in V0065?
# spkw20_c - problem with cdata[]
# utf_c - for internal use by GF system only
###
# bodvar_c - deprecated
# bschoc_c, etc. - how to support const void * array
# ckw05_c - how to support SpiceCK05Subtype
# maxd_c - variable length inputs
# spkw18_c - how to support SpiceSPK18Subtype
# dafgs_c - how to deal with an array that doesn't have the number of elements
# dasec_c - how to handle void types in parameter list
# dafgh_c - does function actually exist? I found no C file ...
# ucase_c - not needed for python
# gfevnt_c, gffove_c, gfocce_c, gfudb_c, gfuds_c, uddc_c, uddf_c - how to support callbacks
exclude_list = (
### N0065
'edterm_c', 'illumg_c', 'spkw20_c'
, 'udf_c'
,
'cnames',
'bodvar_c',
'bschoc_c', 'bsrchc_c', 'dafac_c', 'dafec_c', 'dasac_c', 'ekacec_c',
'ekaclc_c', 'ekbseg_c', 'ekifld_c', 'ekucec_c', 'esrchc_c',
'getelm_c', 'isrchc_c', 'kxtrct_c', 'lmpool_c', 'lstlec_c', 'lstltc_c',
'mequg_c', 'mtxmg_c', 'mtxvg_c', 'mxmg_c', 'mtmtg_c', 'mxmtg_c', 'mxvg_c',
'orderc_c', 'pcpool_c', 'swpool_c', 'vtmvg_c', 'xposeg_c',
'ckw05_c',
'maxd_c', 'maxi_c', 'mind_c', 'mini_c',
'spkw18_c',
'dafgs_c', 'dafps_c', 'dafus_c', 'getfov_c',
'ckw01_c', 'ckw02_c', 'ckw03_c', 'spk14a_c', 'spkw02_c', 'spkw03_c',
'spkw05_c', 'spkw08_c', 'spkw09_c', 'spkw10_c', 'spkw12_c', 'spkw13_c',
'dasec_c', 'ekpsel_c', 'ekrcec_c', 'gnpool_c',
'dafgh_c', 'prefix_c',
'lcase_c', 'ucase_c', 'getcml_c', 'lparse_c', 'lparsm_c', 'prompt_c',
'putcml_c', 'reordc_c', 'shellc_c', 'sumad_c', 'sumai_c',
'gfevnt_c', 'gffove_c', 'gfocce_c', 'gfudb_c', 'gfuds_c', 'uddc_c', 'uddf_c',
)
module_defs = []
cspice_src = None
DEBUG = 'DEBUG_MKWRAPPER' in os.environ # set it on when string is the right one
INPUT_TYPE = 0
OUTPUT_TYPE = 1
INOUTPUT_TYPE = 2
IOTYPE = { 'I':INPUT_TYPE, 'O':OUTPUT_TYPE, 'I/O': INOUTPUT_TYPE, 'I-O': INOUTPUT_TYPE, 'I,O': INOUTPUT_TYPE }
IOTYPEkeys = IOTYPE.keys()
def debug(string):
if DEBUG: sys.stderr.write("%s\n" % str(string))
def determine_py_type(param_obj):
type = param_obj.type
param_obj.py_string = ''
param_obj.spice_obj = None
# functions to get a python object or spice object, respectively, for the
# given variable
param_obj.get_py_fn = None
param_obj.get_spice_fn = None
# determine the type of python variable this would be
if type in ('SpiceChar', 'ConstSpiceChar', 'SpiceChar'):
param_obj.py_string = 's'
elif type in ('ConstSpiceDouble', 'SpiceDouble'):
param_obj.py_string = 'd'
elif type in ('ConstSpiceBoolean', 'SpiceBoolean'):
param_obj.py_string = 'O'
param_obj.get_py_fn = 'get_py_boolean'
elif type in ('ConstSpiceInt', 'SpiceInt'):
# Use an "l" or an "i" from the SpiceInt typedef
global spiceintType1
param_obj.py_string = spiceintType1
elif type == 'SpiceCell':
param_obj.py_string = 'O'
param_obj.spice_obj = 'Cell'
param_obj.get_py_fn = 'get_py_cell'
param_obj.get_spice_fn = 'get_spice_cell'
elif type in ('ConstSpiceEllipse', 'SpiceEllipse'):
param_obj.py_string = 'O'
param_obj.spice_obj = 'Ellipse'
param_obj.get_py_fn = 'get_py_ellipse'
param_obj.get_spice_fn = 'get_spice_ellipse'
elif type == 'SpiceEKAttDsc':
param_obj.py_string = 'O'
param_obj.spice_obj = 'EkAttDsc'
param_obj.get_py_fn = 'get_py_ekattdsc'
param_obj.get_spice_fn = 'get_spice_ekattdsc'
elif type == 'SpiceEKSegSum':
param_obj.py_string = 'O'
param_obj.spice_obj = 'EkSegSum'
param_obj.get_py_fn = 'get_py_eksegsum'
param_obj.get_spice_fn = 'get_spice_eksegsum'
elif type in ('ConstSpicePlane', 'SpicePlane'):
param_obj.py_string = 'O'
param_obj.spice_obj = 'Plane'
param_obj.get_py_fn = 'get_py_plane'
param_obj.get_spice_fn = 'get_spice_plane'
elif type in ('int'):
param_obj.py_string = 'i'
sys.stderr.write('Warning: suspect type: %s for %s\n' % (type,param_obj.name,))
elif type in ('void'):
param_obj.py_string = ''
else:
sys.stderr.write('Warning: Unknown type: %s\n' % type)
def get_doc(function_name):
doc = StringIO()
# the sections of documentation we want
sections = [
'-Abstract',
'-Brief_I/O',
'-Detailed_Input',
'-Detailed_Output',
]
if function_name[-1:]=='_':
src_file = "%s/%s.c" % (cspice_src, function_name[:-1])
else:
src_file = "%s/%s.c" % (cspice_src, function_name)
if os.path.exists(src_file):
f = open(src_file, 'r')
# loop for going through the entire source file
while 1:
input = f.readline()
input_len = len(input)
if not input: break
input = input.rstrip()
# skip blank lines
if input == "": continue
#print "input: %s" % input
split = input.split()
if split[0] in sections:
while 1:
if not input:
doc.write('\\n')
else:
doc.write('%s\\n' % input.replace('\\', '\\\\').replace('"', '\\"'))
input = f.readline()
input_len = len(input)
input = input.rstrip()
if not input:
continue
elif input[0] == '-':
f.seek(f.tell()-input_len)
break
# t = f.readlines()
f.close()
return '"%s"' % doc.getvalue()
def gen_wrapper(prototype, buffer):
prototype = remove_extra_spaces(prototype)
manually_build_returnVal = False
input_list = []
input_name_list = []
output_list = []
output_name_list = []
# keep track of whether a character string was found as an output.
# if one was found, one of the inputs to the C function is the
# length of the string. since python takes care of this behind
# the scenes, there will not be a length input from the python
# script, so pass in the size of the locally made string (most
# likely STRING_LEN above).
string_output_num = 0
# parse up the given prototype into its fundamental pieces. this function
# returns a container object with all the information parsed up.
prototype_obj = parse_prototype(prototype)
### Save function name to shorter local variable
funcnm = prototype_obj.function_name
### Do not make interfaces for
### - FORTRAN-replacement f2c routines, named *_
### - CSPICE private routines, named zz*
if funcnm[-1:]=='_': return False
if funcnm[:2]=='zz': return False
# check the exclude list before continuing
if funcnm in exclude_list: return False
# dig out the document string from the source file
doc = get_doc(funcnm)
### From doc string, get I, I/O or O for each argument
### from text between lines containing -Brief_I/O and
### -Detailed_Input
### E.g. with the following sample text, populate the
### dictionary as follows:
### ioDict = dict(keywd='I', string='I/O', substr='O')
###...
###-Brief_I/O
###
### VARIABLE I/O DESCRIPTION
### -------- --- --------------------------------------------------
### center,
### vec1,
### vec2 I Center and two generating vectors for an ellipse.
### v1, v2 I Input vectors.
### keywd I Word that marks the beginning of text of interest.
### string I/O String containing a sequence of words, and
### this is a line that starts with more than 10 spaces
### substr O String from end of keywd to beginning of first
###
### The function returns ...
###
###-Detailed_Input
###...
ioDict = Container()
ioDict.defArgSequence = []
sentinelStart = '-Brief_I/O'
sentinelEnd = '-Detailed_Input'
sentinels = [ sentinelStart, sentinelEnd ]
toks = doc.split('\\n') ### + sentinels
toks.reverse()
try:
for sentinel in sentinels:
bridesmaids = []
for lin in iter( lambda: toks.pop().rstrip(' \r '), sentinel ):
### Skip if
### - this is not between the Start and End sentinels
if sentinel!=sentinelEnd: continue
### - line starts with 10 spaces
if not lin[:10].split():
bridesmaids = []
continue
### - line has fewer than three tokens
lintoks = lin.split()
if len(lintoks)<3:
### For single-token lines, if token ends with a continuation comma,
### then add it to bridesmaids for addition to ioDict with next
### line that has I, O or I/O defined
if len(lintoks)==1 and lintoks[0][-1:]==',':
bridesmaids += [ lintoks[0][:-1].lower() ]
continue
argnames, io = lintoks[:2]
toks2 = argnames.split(',')
while len(toks2)>1: bridesmaids += [ toks2.pop(0) ]
argname = toks2[0]
### - argname is empty (should not be possible)
if len(argname)<1:
bridesmaids = []
continue
if not ( io.upper() in IOTYPEkeys ):
bridesmaids = []
continue
argname = argname.lower()
io = io.upper()
### - argname has uppercase in it
if argname != lintoks[0]:
if argname=='variable': continue
fmt = "### %%s case argument: %s? [%s]" % (lintoks[0], str(dict(func=funcnm,lin=lin,sentinel=sentinel)),)
if argname.upper() != lintoks[0]:
pass ##print( fmt % "Mixed" )
else:
pass ##print( fmt % "Upper" )
### If second token (toks[1] == io) is I, I/O or O,
### then add it to IO dictionary, after bridesmaids
bridesmaids.append( argname )
###print( (bridesmaids,argname,) )
ioDict.defArgSequence += bridesmaids
while bridesmaids: ioDict[bridesmaids.pop(0)] = io
###print( (bridesmaids,ioDict,) )
ioDict.ioDictStatus = 'success'
### Protect against absence of a sentinel when
except:
ioDict['__STATUS__'] = 'failure'
traceback.print_exc()
pass
# the string that is passed to PyArg_ParseTuple for getting the
# arguments list and Py_BuildValue for returning results
parse_tuple_string = ""
extra_parse_tuple_string = ""
buildvalue_string = ""
# remove the _c suffix for the python function name
python_function_name = funcnm.rsplit('_c',1)[0]
# Add the C function prototype to the source code output.
t = '/* %s */' % prototype
prototype_comment_list = []
while len(t) > 80:
count = 79
while t[count-1] != ',' and count > 1:
count -= 1
prototype_comment_list.append(t[:count])
t = t[count:]
if t:
prototype_comment_list.append(t)
### Indent comments after the first to make them slightly easier to read
pfx = '\n' + ( ' '*(5 + len(prototype.split('(')[0])) )
prototype_comment = pfx.join(prototype_comment_list)
# declare the function for this wrapper
buffer.write(
"\n%s\nstatic PyObject * spice_%s(PyObject *self, PyObject *args)\n{" % \
(prototype_comment, python_function_name));
buffer.write( "\n /* %s */\n" % ( str(ioDict),) )
# split up the inputs from the outputs so that only inputs have to
# be provided to the function from python and the outputs are
# returned to python, e.g. et = utc2et("SOME DATE")
###last_item = None
###t_type = None
t_type = INPUT_TYPE
for param in prototype_obj.params:
#debug('')
if param == 'void':
if len(prototype_obj.params)>1:
sys.stderr.write('Warning: void argument in list of more than one argument from %s()\n' % (funcnm,) )
continue
debug( "%s: %s" % (funcnm,str(param),) )
param_info = parse_param(param,funcnm=funcnm)
if param_info is None:
sys.stderr.write( "### Could not parse_param: '%s'\n" % ( str(param), ) )
continue
#debug("parsed %s() param: %s" % (funcnm,param_info,) )
### New code (BTCarcich, 2012-01):
if True:
try:
### Handle nconsistencies in argument names between declarations
### in CSPICE headers and in CSPICE functions in *_c.c
ioDictArgName = ioDict.defArgSequence.pop(0)
override=''
if ioDictArgName in mislabeled_outputs:
if funcnm in mislabeled_outputs[ioDictArgName]:
override = ' /* N.B. OUTPUT MISLABELED AS INPUT IN (-Brief_I/O section)\n of %s.c HAS BEEN OVERRIDDEN: */\n' % funcnm
ioDict[ioDictArgName] = 'O'
if not (param_info.name in ioDict):
ioDict[param_info.name] = ioDict[ioDictArgName]
buffer.write( '\n%s /* %s() using param_type ioDict["%s"]=%s for %s */' % ( override, funcnm, ioDictArgName, ioDict[ioDictArgName], param_info.name, ) )
t_type = IOTYPE[ioDict[param_info.name]]
except:
traceback.print_exc()
print( dict(func=funcnm,ioDict=ioDict,param=param) )
raise Exception("I don't know if %s is an input or output" % param)
### Disabled old code:
else:
if param_info.is_array and not param_info.is_const:
t_type = OUTPUT_TYPE
elif param_info.is_const or not param_info.is_pointer:
t_type = INPUT_TYPE
elif param_info.is_pointer:
t_type = OUTPUT_TYPE
else:
raise Exception("I don't know if %s is an input or output" % param)
# tack the parameter type onto the param_info tuple
param_info.param_type = t_type
# if the last param was counted as an output, but this param
# is an input, bring the last entered item to this list
# because it was miscategorized
#
# TODO: This is a HUGE hack and would be nice to find an alternate
# way of deciding this).
###if last_item is not None and \
### t_type == INPUT_TYPE and last_item.param_type == OUTPUT_TYPE:
### output_list.remove(last_item)
### input_list.append(last_item)
if t_type == INPUT_TYPE or t_type == INOUTPUT_TYPE:
input_list.append(param_info)
if t_type == OUTPUT_TYPE or t_type == INOUTPUT_TYPE:
output_list.append(param_info)
###last_item = param_info
#debug("param after hack: %s" % param_info)
#debug("")
#debug( pprint.pformat( (funcnm,dict(inp=input_list,out=output_list,),) ) )
# parse the outputs
if output_list:
buffer.write("\n /* variables for outputs */")
#print 'function_name: %s' % function_name
# the bodv* functions pass in 'maxn', which is the number of elements in
# the output array 'values'. detect this case and allocate memory for the
# values array.
#
# the allocate_memory variable points to the last input variable, which
# should be the variable pointing to the max number of items in the array
if funcnm.startswith('bodv'):
output_list[-1].make_pointer = True
output_list[-1].allocate_memory = input_list[-1].name
manually_build_returnVal = True
pass
py_to_c_conversions = [];
extra_inoutput_name_list = []
for output in output_list:
#print output
# declare the variable
buffer.write("\n %s" % output.type)
if output.type=='SpiceCell':
output.make_pointer = True
if output.make_pointer:
buffer.write(" *")
buffer.write(" %s" % output.name)
# this item may be an array pointer, so only add the brackets
# if no memory allocation was done for this variable
if output.is_array and not output.allocate_memory:
for count in output.num_elements:
try:
buffer.write("[%d]" % count)
except:
buffer.write("[]")
if output.type == 'SpiceChar' and not output.is_array:
string_output_num += 1
buffer.write("[STRING_LEN]")
buffer.write(";")
# if this output has a get_spice_fn function associated with it,
# and is a SpiceCell, and is an output only, then in reality it
# will need an input argument to define its size, so declare a
# variable for the conversion
if output.type=='SpiceCell' and output.get_spice_fn and output.param_type==OUTPUT_TYPE:
py_output_name = "py_%s" % output.name
buffer.write("\n PyObject * %s = NULL;" % py_output_name)
py_to_c_conversions.append("%s = %s(%s);" % (output.name, output.get_spice_fn, py_output_name))
extra_inoutput_name_list.append( py_output_name )
extra_parse_tuple_string += output.py_string
output_name_list.append(output.name)
# parse the inputs
if input_list:
buffer.write("\n /* variables for inputs */")
# in the loop below, the variables are being declared as type
# 'reg_type'. this is because python was not properly parsing the
# arguments passed in from Python when using SPICE variable types.
for input in input_list:
input_name = input.name
# if a character string output was detected and this variable has the
# string 'len' in it, skip adding it to the ParseTuple string.
if 'len' in input_name and string_output_num > 0:
buffer.write("\n %s %s = STRING_LEN;" % \
(input.reg_type, input_name)
)
else:
parse_tuple_string += input.py_string
if input.is_pointer:
pointer_string = " * "
else:
pointer_string = " "
### if this is both an input and an output, then do not declare it
if input.param_type == INPUT_TYPE:
buffer.write("\n %s%s%s" % (
input.reg_type, pointer_string, input_name))
if input.is_array:
for count in input.num_elements:
buffer.write("[%s]" % count)
buffer.write(";")
# if this input has a get_spice_fn function associated with it,
# declare a variable for the conversion
if input.get_spice_fn:
input_name = "py_%s" % input_name
buffer.write("\n PyObject * %s = NULL;" % input_name)
py_to_c_conversions.append("%s = %s(%s);" % (input.name, input.get_spice_fn, input_name))
# if this is an array, put in the right amount of elements
# into the ParseTuple parameter list (one per element).
# Also, the list coming in can be 1D, 2D, or 3D.
if input.is_array:
input_name_list += get_array_sizes(
input.num_elements, input_name)
else:
input_name_list.append(input_name)
# other variables needed below
buffer.write('\n\n char failed = 0;')
if not manually_build_returnVal and output_list:
if len(output_list)!=1 or output_list[0].name!='found':
buffer.write('\n char buildvalue_string[STRING_LEN] = "";')
if output_list and ( len(output_list) != 1 or output_list[0].name!='found' ):
buffer.write('\n PyObject *returnVal;')
# configure the input string list for parsing the args tuple
input_list_string = "&" + ", &".join( input_name_list + extra_inoutput_name_list )
# if the function type is not void, declare a variable for the
# result.
if prototype_obj.type != "void":
buffer.write("\n\n /* variable for result */")
if prototype_obj.is_pointer:
t_pointer = " * "
else:
t_pointer = " "
buffer.write("\n %s%sresult;" % (prototype_obj.type, t_pointer))
buffer.write("\n")
# generate the PyArg_ParseTuple call if there were any inputs to
# this function
if input_name_list+extra_inoutput_name_list:
buffer.write(
('\n PYSPICE_CHECK_RETURN_STATUS(' +
'PyArg_ParseTuple(args, "%s", %s));') % \
(parse_tuple_string+extra_parse_tuple_string, input_list_string))
# if there are any Python -> C conversions that need to occur, add them here.
if py_to_c_conversions:
buffer.write('\n %s\n' % '\n '.join(py_to_c_conversions))
for output in output_list:
# see if memory needs to be allocated for this variable
if output.allocate_memory:
buffer.write("\n\n %s = PyMem_Malloc(sizeof(%s) * %s);" % \
(output.name, output.type, output.allocate_memory))
# build the input name list for calling the C function
input_name_list = []
for input in input_list:
### if this is both an input and an output, then do not declare it
if input.param_type == INPUT_TYPE:
input_name_list.append(input.name)
# combine the input name list and the output name list for the C
# function call
if input_list:
input_list_string = ", ".join(input_name_list)
else:
input_list_string = ""
# build the output name list for calling the C function
t_list = []
for output in output_list:
if any([output.is_array,
output.type == "SpiceChar",
output.make_pointer,
output.allocate_memory]):
t_list.append(output.name)
else:
t_list.append("&" + output.name)
if t_list:
output_list_string = ', '.join(t_list)
else:
output_list_string = ''
#debug("output list: %s" % output_list_string)
if input_list_string and output_list_string:
param_list_string = "%s, %s" % (input_list_string, output_list_string)
elif input_list_string:
param_list_string = input_list_string
else:
param_list_string = output_list_string
# debug(param_list_string)
# Call the C function
if prototype_obj.type != "void":
buffer.write("\n result = %s(%s);" % (funcnm, param_list_string))
else:
buffer.write("\n %s(%s);" % (funcnm, param_list_string))
# run the macro to check to see if an exception was raised. once the
# check is made, see if the failed boolean was set. this is an indication
# that the function should free any allocated memory and return NULL.
buffer.write("\n\n PYSPICE_CHECK_FAILED;\n")
buffer.write('\n if(failed) {')
for output in output_list:
if output.allocate_memory:
buffer.write('\n PyMem_Free(%s);' % output.name)
buffer.write('\n return NULL;')
buffer.write('\n }\n')
# loop through the output to build the value strings for each output if
# the return value is not being built up manually
if not manually_build_returnVal:
if output_list:
buffer.write('\n /* put together the output buildvalue string */')
for output in output_list:
if output.allocate_memory:
buffer.write(
('\n make_buildvalue_tuple(buildvalue_string, ' +
'"%s", %s);') % (output.py_string, output.name)
)
elif output.name != 'found':
if output.is_array==1 and output.py_string=='s': sfx='#'
else : sfx=''
buffer.write(
'\n strcat(buildvalue_string, "%s%s");' % (output.py_string,sfx,)
)
buffer.write('\n')
# If the called function is a void, return PyNone, or else figure out what
# to return.
if output_list:
# output_list_string = ', '.join(output_list)
#debug('output_list: '.format(output_list))
if manually_build_returnVal:
#debug('in manual returnVal build')
make_manual_returnVal(buffer, output_list)
else:
#debug('in automatic returnVal build')
make_automatic_returnVal(buffer, output_list)
elif prototype_obj.type == "void":
buffer.write("\n Py_INCREF(Py_None);")
buffer.write("\n return Py_None;")
elif prototype_obj.type == "SpiceBoolean":
buffer.write("\n if(result) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; }")
elif prototype_obj.type in ("ConstSpiceChar", "SpiceDouble", "SpiceInt"):
buffer.write('\n return Py_BuildValue("%s", result);' % prototype_obj.py_string)
else:
pass # for now; TODO: figure out what to do
buffer.write("\n}");
if not doc:
buffer.write('\nPyDoc_STRVAR(%s_doc, "");\n' % python_function_name)
else:
buffer.write('\nPyDoc_STRVAR(%s_doc, %s);\n' % (python_function_name, doc))
# add this functions definition to the module_defs list
module_defs.append('{"%s", spice_%s, METH_VARARGS, %s_doc},' % \
(python_function_name, python_function_name, python_function_name))
### Callers only check for True or false; buffer argument is modified in place
return True
### Old: return buffer.getvalue()
def get_array_sizes(list, name):
"""
Expand the elements of an array for 1, 2, and 3D arrays
"""
t_list = []
if len(list) == 1:
for t in range(0, list[0]):
t_list.append(name + "[%s]" % t)
elif len(list) == 2:
for t1 in range(0, list[0]):
for t2 in range(0, list[1]):
t_list.append(name + "[%s][%s]" % (t1, t2))
elif len(list) == 3:
for t1 in range(0, list[0]):
for t2 in range(0, list[1]):
for t3 in range(0, list[2]):
t_list.append(name + "[%s][%s][%s]" % (t1, t2, t3))
return t_list
def make_automatic_returnVal(buffer, output_list):
"""
The outputs parameters and their dimensions are defined so this function
can be used.
"""
# put together the outputs
t_list = []
# Check_found is used to indicate whether a found variable was
# passed along with other output variables. check_found is set to
# True if the found variable indicating that the additional
# outputs are valid. This way, if nothing was found, the function
# returns None instead of the output variables requested.
check_found = False
for output in output_list:
# if the length of the output list is only 1 and it's found,
# return true or false, otherwise, if found is false return None.
if output.name == "found":
if len(output_list) == 1:
buffer.write(
'\n if(found) { Py_RETURN_TRUE; } ' +
'else { Py_RETURN_FALSE; }'
)
else:
check_found = True
# Do not add found to the t_list and output_list_string vars
continue
# If the output is an array, expand out all the elements in order
# to build a python tuple out of them (This seems sub-optimal, I
# have to read some more python C documentation).
if output.is_array:
if output.is_array==1 and output.py_string=='s':
t_list.append(output.name)
t_list.append(str(output.num_elements[0]))
else:
t_list += get_array_sizes(output.num_elements, output.name)
elif(output.get_py_fn):
if(output.type=='SpiceCell'):
t_list.append('%s(%s)' % (output.get_py_fn, output.name))
else:
t_list.append('%s(&%s)' % (output.get_py_fn, output.name))
else:
t_list.append(output.name)
output_list_string = ", ".join(t_list)
if output_list_string:
if check_found:
buffer.write(
'\n if(!found) {\n Py_INCREF(Py_None);\n return Py_None;\n } else {\n ')
else:
buffer.write('\n ')
buffer.write(
'returnVal = Py_BuildValue(buildvalue_string, %s);' % \
(output_list_string))
for output in output_list:
if output.allocate_memory:
buffer.write('\n PyMem_Free(%s);' % output.name)
buffer.write('\n return returnVal;');
if check_found:
buffer.write('\n }\n')
def make_manual_returnVal(buffer, output_list):
"""
This returnVal function is used when the output dimensions are dynamic.
For instance, a double * and an integer specifying the number of elements
in that array are passed in. In order to properly build the return tuple,
this function can be used.
"""
buffer.write('\n {\n int i = 0;')
buffer.write('\n PyObject *t = NULL;')
buffer.write(
'\n returnVal = PyTuple_New(%d);' % len(output_list))
count = 0;
for count in range(len(output_list)):
output = output_list[count]
if output.allocate_memory:
buffer.write('\n t = PyTuple_New(%s);' % output_list[0].name)
buffer.write(
'\n for(i = 0; i < %s; ++ i) {' % output_list[0].name
)
buffer.write(
'\n PyTuple_SET_ITEM(t, i, Py_BuildValue("%s", %s[i]));' % \
(output.py_string, output.name)
)
buffer.write('\n }')
buffer.write('\n PyTuple_SET_ITEM(returnVal, %d, t);' % count)
else:
buffer.write(
'\n PyTuple_SET_ITEM(returnVal, %d, Py_BuildValue("%s", %s));' % \
(count, output.py_string, output.name)
)
buffer.write('\n }\n return returnVal;');
def get_type(type):
reg_type = type
# determine the type of python variable this would be
if type in ('SpiceChar', 'ConstSpiceChar', 'SpiceChar'):
reg_type = 'char'
elif type in ('ConstSpiceDouble', 'SpiceDouble'):
reg_type = 'double'
elif type in ('ConstSpiceBoolean', 'SpiceBoolean'):
reg_type = 'char'
elif type in ('ConstSpiceInt', 'SpiceInt'):
# put a long for a spice int since they are long integers
global spiceintType
reg_type = spiceintType
return reg_type
def get_tuple_py_string(param_obj, curr_depth=0):
"""
Put together the tuple string based on the number of elements in
the given elements list. if this was a one demensional array, the
list would simply be, for example [3], where 3 is the number of
elements in the array. A 3x3 2D array would be [3, 3] a 3x3x3 3D
array is: [3, 3, 3]. The output for these examples would be:
(xxx)
((xxx)(xxx)(xxx))
(((xxx)(xxx)(xxx))((xxx)(xxx)(xxx))((xxx)(xxx)(xxx)))
"""
list = param_obj.num_elements
char = param_obj.py_string
t = "("
for i in range(0, list[curr_depth]):
if curr_depth < (len(list) - 1):
t += get_tuple_py_string(param_obj, (curr_depth+1))
else:
t += char
t += ")"
return t
def fixNameCollision(name):
if name in RESERVED_NAMES:
return name + '_'
else:
return name
def parse_param(param,funcnm=False):
"""
Take the given parameter and break it up into the type of
variable, the variable name and whether it's a pointer.
"""
param_obj = Container()
param = remove_extra_spaces(param)
param_split = param.split(" ")
param_obj.original = param
#debug('param: %s' % param)
#debug('param_split: %s' % str(param_split))
index = 0
type = param_split[index]
index += 1
if type == 'const':
param_obj.is_const = True
type = param_split[index]
index += 1
else:
param_obj.is_const = False
param_obj.type = type
param_obj.reg_type = get_type(type)
try:
name = param_split[index]
index += 1
# check to see if the second element in the split list is a
# pointer, if so, set the is_pointer var to True and set the name