capi_maps.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  1. """
  2. Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
  3. Copyright 2011 -- present NumPy Developers.
  4. Permission to use, modify, and distribute this software is given under the
  5. terms of the NumPy License.
  6. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
  7. """
  8. from . import __version__
  9. f2py_version = __version__.version
  10. import copy
  11. import os
  12. import re
  13. from . import cb_rules
  14. from ._isocbind import iso_c2py_map, iso_c_binding_map, isoc_c2pycode_map
  15. # The environment provided by auxfuncs.py is needed for some calls to eval.
  16. # As the needed functions cannot be determined by static inspection of the
  17. # code, it is safest to use import * pending a major refactoring of f2py.
  18. from .auxfuncs import *
  19. from .crackfortran import markoutercomma
  20. __all__ = [
  21. 'getctype', 'getstrlength', 'getarrdims', 'getpydocsign',
  22. 'getarrdocsign', 'getinit', 'sign2map', 'routsign2map', 'modsign2map',
  23. 'cb_sign2map', 'cb_routsign2map', 'common_sign2map', 'process_f2cmap_dict'
  24. ]
  25. depargs = []
  26. lcb_map = {}
  27. lcb2_map = {}
  28. # forced casting: mainly caused by the fact that Python or Numeric
  29. # C/APIs do not support the corresponding C types.
  30. c2py_map = {'double': 'float',
  31. 'float': 'float', # forced casting
  32. 'long_double': 'float', # forced casting
  33. 'char': 'int', # forced casting
  34. 'signed_char': 'int', # forced casting
  35. 'unsigned_char': 'int', # forced casting
  36. 'short': 'int', # forced casting
  37. 'unsigned_short': 'int', # forced casting
  38. 'int': 'int', # forced casting
  39. 'long': 'int',
  40. 'long_long': 'long',
  41. 'unsigned': 'int', # forced casting
  42. 'complex_float': 'complex', # forced casting
  43. 'complex_double': 'complex',
  44. 'complex_long_double': 'complex', # forced casting
  45. 'string': 'string',
  46. 'character': 'bytes',
  47. }
  48. c2capi_map = {'double': 'NPY_DOUBLE',
  49. 'float': 'NPY_FLOAT',
  50. 'long_double': 'NPY_LONGDOUBLE',
  51. 'char': 'NPY_BYTE',
  52. 'unsigned_char': 'NPY_UBYTE',
  53. 'signed_char': 'NPY_BYTE',
  54. 'short': 'NPY_SHORT',
  55. 'unsigned_short': 'NPY_USHORT',
  56. 'int': 'NPY_INT',
  57. 'unsigned': 'NPY_UINT',
  58. 'long': 'NPY_LONG',
  59. 'unsigned_long': 'NPY_ULONG',
  60. 'long_long': 'NPY_LONGLONG',
  61. 'unsigned_long_long': 'NPY_ULONGLONG',
  62. 'complex_float': 'NPY_CFLOAT',
  63. 'complex_double': 'NPY_CDOUBLE',
  64. 'complex_long_double': 'NPY_CDOUBLE',
  65. 'string': 'NPY_STRING',
  66. 'character': 'NPY_STRING'}
  67. c2pycode_map = {'double': 'd',
  68. 'float': 'f',
  69. 'long_double': 'g',
  70. 'char': 'b',
  71. 'unsigned_char': 'B',
  72. 'signed_char': 'b',
  73. 'short': 'h',
  74. 'unsigned_short': 'H',
  75. 'int': 'i',
  76. 'unsigned': 'I',
  77. 'long': 'l',
  78. 'unsigned_long': 'L',
  79. 'long_long': 'q',
  80. 'unsigned_long_long': 'Q',
  81. 'complex_float': 'F',
  82. 'complex_double': 'D',
  83. 'complex_long_double': 'G',
  84. 'string': 'S',
  85. 'character': 'c'}
  86. # https://docs.python.org/3/c-api/arg.html#building-values
  87. c2buildvalue_map = {'double': 'd',
  88. 'float': 'f',
  89. 'char': 'b',
  90. 'signed_char': 'b',
  91. 'short': 'h',
  92. 'int': 'i',
  93. 'long': 'l',
  94. 'long_long': 'L',
  95. 'complex_float': 'N',
  96. 'complex_double': 'N',
  97. 'complex_long_double': 'N',
  98. 'string': 'y',
  99. 'character': 'c'}
  100. f2cmap_all = {'real': {'': 'float', '4': 'float', '8': 'double',
  101. '12': 'long_double', '16': 'long_double'},
  102. 'integer': {'': 'int', '1': 'signed_char', '2': 'short',
  103. '4': 'int', '8': 'long_long',
  104. '-1': 'unsigned_char', '-2': 'unsigned_short',
  105. '-4': 'unsigned', '-8': 'unsigned_long_long'},
  106. 'complex': {'': 'complex_float', '8': 'complex_float',
  107. '16': 'complex_double', '24': 'complex_long_double',
  108. '32': 'complex_long_double'},
  109. 'complexkind': {'': 'complex_float', '4': 'complex_float',
  110. '8': 'complex_double', '12': 'complex_long_double',
  111. '16': 'complex_long_double'},
  112. 'logical': {'': 'int', '1': 'char', '2': 'short', '4': 'int',
  113. '8': 'long_long'},
  114. 'double complex': {'': 'complex_double'},
  115. 'double precision': {'': 'double'},
  116. 'byte': {'': 'char'},
  117. }
  118. # Add ISO_C handling
  119. c2pycode_map.update(isoc_c2pycode_map)
  120. c2py_map.update(iso_c2py_map)
  121. f2cmap_all, _ = process_f2cmap_dict(f2cmap_all, iso_c_binding_map, c2py_map)
  122. # End ISO_C handling
  123. f2cmap_default = copy.deepcopy(f2cmap_all)
  124. f2cmap_mapped = []
  125. def load_f2cmap_file(f2cmap_file):
  126. global f2cmap_all, f2cmap_mapped
  127. f2cmap_all = copy.deepcopy(f2cmap_default)
  128. if f2cmap_file is None:
  129. # Default value
  130. f2cmap_file = '.f2py_f2cmap'
  131. if not os.path.isfile(f2cmap_file):
  132. return
  133. # User defined additions to f2cmap_all.
  134. # f2cmap_file must contain a dictionary of dictionaries, only. For
  135. # example, {'real':{'low':'float'}} means that Fortran 'real(low)' is
  136. # interpreted as C 'float'. This feature is useful for F90/95 users if
  137. # they use PARAMETERS in type specifications.
  138. try:
  139. outmess(f'Reading f2cmap from {f2cmap_file!r} ...\n')
  140. with open(f2cmap_file) as f:
  141. d = eval(f.read().lower(), {}, {})
  142. f2cmap_all, f2cmap_mapped = process_f2cmap_dict(f2cmap_all, d, c2py_map, True)
  143. outmess('Successfully applied user defined f2cmap changes\n')
  144. except Exception as msg:
  145. errmess(f'Failed to apply user defined f2cmap changes: {msg}. Skipping.\n')
  146. cformat_map = {'double': '%g',
  147. 'float': '%g',
  148. 'long_double': '%Lg',
  149. 'char': '%d',
  150. 'signed_char': '%d',
  151. 'unsigned_char': '%hhu',
  152. 'short': '%hd',
  153. 'unsigned_short': '%hu',
  154. 'int': '%d',
  155. 'unsigned': '%u',
  156. 'long': '%ld',
  157. 'unsigned_long': '%lu',
  158. 'long_long': '%ld',
  159. 'complex_float': '(%g,%g)',
  160. 'complex_double': '(%g,%g)',
  161. 'complex_long_double': '(%Lg,%Lg)',
  162. 'string': '\\"%s\\"',
  163. 'character': "'%c'",
  164. }
  165. # Auxiliary functions
  166. def getctype(var):
  167. """
  168. Determines C type
  169. """
  170. ctype = 'void'
  171. if isfunction(var):
  172. if 'result' in var:
  173. a = var['result']
  174. else:
  175. a = var['name']
  176. if a in var['vars']:
  177. return getctype(var['vars'][a])
  178. else:
  179. errmess(f'getctype: function {a} has no return value?!\n')
  180. elif issubroutine(var):
  181. return ctype
  182. elif ischaracter_or_characterarray(var):
  183. return 'character'
  184. elif isstring_or_stringarray(var):
  185. return 'string'
  186. elif 'typespec' in var and var['typespec'].lower() in f2cmap_all:
  187. typespec = var['typespec'].lower()
  188. f2cmap = f2cmap_all[typespec]
  189. ctype = f2cmap[''] # default type
  190. if 'kindselector' in var:
  191. if '*' in var['kindselector']:
  192. try:
  193. ctype = f2cmap[var['kindselector']['*']]
  194. except KeyError:
  195. errmess('getctype: "%s %s %s" not supported.\n' %
  196. (var['typespec'], '*', var['kindselector']['*']))
  197. elif 'kind' in var['kindselector']:
  198. if typespec + 'kind' in f2cmap_all:
  199. f2cmap = f2cmap_all[typespec + 'kind']
  200. try:
  201. ctype = f2cmap[var['kindselector']['kind']]
  202. except KeyError:
  203. if typespec in f2cmap_all:
  204. f2cmap = f2cmap_all[typespec]
  205. try:
  206. ctype = f2cmap[str(var['kindselector']['kind'])]
  207. except KeyError:
  208. errmess('getctype: "%s(kind=%s)" is mapped to C "%s" (to override define dict(%s = dict(%s="<C typespec>")) in %s/.f2py_f2cmap file).\n'
  209. % (typespec, var['kindselector']['kind'], ctype,
  210. typespec, var['kindselector']['kind'], os.getcwd()))
  211. elif not isexternal(var):
  212. errmess(f'getctype: No C-type found in "{var}", assuming void.\n')
  213. return ctype
  214. def f2cexpr(expr):
  215. """Rewrite Fortran expression as f2py supported C expression.
  216. Due to the lack of a proper expression parser in f2py, this
  217. function uses a heuristic approach that assumes that Fortran
  218. arithmetic expressions are valid C arithmetic expressions when
  219. mapping Fortran function calls to the corresponding C function/CPP
  220. macros calls.
  221. """
  222. # TODO: support Fortran `len` function with optional kind parameter
  223. expr = re.sub(r'\blen\b', 'f2py_slen', expr)
  224. return expr
  225. def getstrlength(var):
  226. if isstringfunction(var):
  227. if 'result' in var:
  228. a = var['result']
  229. else:
  230. a = var['name']
  231. if a in var['vars']:
  232. return getstrlength(var['vars'][a])
  233. else:
  234. errmess(f'getstrlength: function {a} has no return value?!\n')
  235. if not isstring(var):
  236. errmess(
  237. f'getstrlength: expected a signature of a string but got: {repr(var)}\n')
  238. len = '1'
  239. if 'charselector' in var:
  240. a = var['charselector']
  241. if '*' in a:
  242. len = a['*']
  243. elif 'len' in a:
  244. len = f2cexpr(a['len'])
  245. if re.match(r'\(\s*(\*|:)\s*\)', len) or re.match(r'(\*|:)', len):
  246. if isintent_hide(var):
  247. errmess('getstrlength:intent(hide): expected a string with defined length but got: %s\n' % (
  248. repr(var)))
  249. len = '-1'
  250. return len
  251. def getarrdims(a, var, verbose=0):
  252. ret = {}
  253. if isstring(var) and not isarray(var):
  254. ret['size'] = getstrlength(var)
  255. ret['rank'] = '0'
  256. ret['dims'] = ''
  257. elif isscalar(var):
  258. ret['size'] = '1'
  259. ret['rank'] = '0'
  260. ret['dims'] = ''
  261. elif isarray(var):
  262. dim = copy.copy(var['dimension'])
  263. ret['size'] = '*'.join(dim)
  264. try:
  265. ret['size'] = repr(eval(ret['size']))
  266. except Exception:
  267. pass
  268. ret['dims'] = ','.join(dim)
  269. ret['rank'] = repr(len(dim))
  270. ret['rank*[-1]'] = repr(len(dim) * [-1])[1:-1]
  271. for i in range(len(dim)): # solve dim for dependencies
  272. v = []
  273. if dim[i] in depargs:
  274. v = [dim[i]]
  275. else:
  276. for va in depargs:
  277. if re.match(r'.*?\b%s\b.*' % va, dim[i]):
  278. v.append(va)
  279. for va in v:
  280. if depargs.index(va) > depargs.index(a):
  281. dim[i] = '*'
  282. break
  283. ret['setdims'], i = '', -1
  284. for d in dim:
  285. i = i + 1
  286. if d not in ['*', ':', '(*)', '(:)']:
  287. ret['setdims'] = '%s#varname#_Dims[%d]=%s,' % (
  288. ret['setdims'], i, d)
  289. if ret['setdims']:
  290. ret['setdims'] = ret['setdims'][:-1]
  291. ret['cbsetdims'], i = '', -1
  292. for d in var['dimension']:
  293. i = i + 1
  294. if d not in ['*', ':', '(*)', '(:)']:
  295. ret['cbsetdims'] = '%s#varname#_Dims[%d]=%s,' % (
  296. ret['cbsetdims'], i, d)
  297. elif isintent_in(var):
  298. outmess('getarrdims:warning: assumed shape array, using 0 instead of %r\n'
  299. % (d))
  300. ret['cbsetdims'] = '%s#varname#_Dims[%d]=%s,' % (
  301. ret['cbsetdims'], i, 0)
  302. elif verbose:
  303. errmess(
  304. f'getarrdims: If in call-back function: array argument {repr(a)} must have bounded dimensions: got {repr(d)}\n')
  305. if ret['cbsetdims']:
  306. ret['cbsetdims'] = ret['cbsetdims'][:-1]
  307. # if not isintent_c(var):
  308. # var['dimension'].reverse()
  309. return ret
  310. def getpydocsign(a, var):
  311. global lcb_map
  312. if isfunction(var):
  313. if 'result' in var:
  314. af = var['result']
  315. else:
  316. af = var['name']
  317. if af in var['vars']:
  318. return getpydocsign(af, var['vars'][af])
  319. else:
  320. errmess(f'getctype: function {af} has no return value?!\n')
  321. return '', ''
  322. sig, sigout = a, a
  323. opt = ''
  324. if isintent_in(var):
  325. opt = 'input'
  326. elif isintent_inout(var):
  327. opt = 'in/output'
  328. out_a = a
  329. if isintent_out(var):
  330. for k in var['intent']:
  331. if k[:4] == 'out=':
  332. out_a = k[4:]
  333. break
  334. init = ''
  335. ctype = getctype(var)
  336. if hasinitvalue(var):
  337. init, showinit = getinit(a, var)
  338. init = f', optional\\n Default: {showinit}'
  339. if isscalar(var):
  340. if isintent_inout(var):
  341. sig = '%s : %s rank-0 array(%s,\'%s\')%s' % (a, opt, c2py_map[ctype],
  342. c2pycode_map[ctype], init)
  343. else:
  344. sig = f'{a} : {opt} {c2py_map[ctype]}{init}'
  345. sigout = f'{out_a} : {c2py_map[ctype]}'
  346. elif isstring(var):
  347. if isintent_inout(var):
  348. sig = '%s : %s rank-0 array(string(len=%s),\'c\')%s' % (
  349. a, opt, getstrlength(var), init)
  350. else:
  351. sig = f'{a} : {opt} string(len={getstrlength(var)}){init}'
  352. sigout = f'{out_a} : string(len={getstrlength(var)})'
  353. elif isarray(var):
  354. dim = var['dimension']
  355. rank = repr(len(dim))
  356. sig = '%s : %s rank-%s array(\'%s\') with bounds (%s)%s' % (a, opt, rank,
  357. c2pycode_map[
  358. ctype],
  359. ','.join(dim), init)
  360. if a == out_a:
  361. sigout = '%s : rank-%s array(\'%s\') with bounds (%s)'\
  362. % (a, rank, c2pycode_map[ctype], ','.join(dim))
  363. else:
  364. sigout = '%s : rank-%s array(\'%s\') with bounds (%s) and %s storage'\
  365. % (out_a, rank, c2pycode_map[ctype], ','.join(dim), a)
  366. elif isexternal(var):
  367. ua = ''
  368. if a in lcb_map and lcb_map[a] in lcb2_map and 'argname' in lcb2_map[lcb_map[a]]:
  369. ua = lcb2_map[lcb_map[a]]['argname']
  370. if not ua == a:
  371. ua = f' => {ua}'
  372. else:
  373. ua = ''
  374. sig = f'{a} : call-back function{ua}'
  375. sigout = sig
  376. else:
  377. errmess(
  378. f'getpydocsign: Could not resolve docsignature for "{a}".\n')
  379. return sig, sigout
  380. def getarrdocsign(a, var):
  381. ctype = getctype(var)
  382. if isstring(var) and (not isarray(var)):
  383. sig = f'{a} : rank-0 array(string(len={getstrlength(var)}),\'c\')'
  384. elif isscalar(var):
  385. sig = f'{a} : rank-0 array({c2py_map[ctype]},\'{c2pycode_map[ctype]}\')'
  386. elif isarray(var):
  387. dim = var['dimension']
  388. rank = repr(len(dim))
  389. sig = '%s : rank-%s array(\'%s\') with bounds (%s)' % (a, rank,
  390. c2pycode_map[
  391. ctype],
  392. ','.join(dim))
  393. return sig
  394. def getinit(a, var):
  395. if isstring(var):
  396. init, showinit = '""', "''"
  397. else:
  398. init, showinit = '', ''
  399. if hasinitvalue(var):
  400. init = var['=']
  401. showinit = init
  402. if iscomplex(var) or iscomplexarray(var):
  403. ret = {}
  404. try:
  405. v = var["="]
  406. if ',' in v:
  407. ret['init.r'], ret['init.i'] = markoutercomma(
  408. v[1:-1]).split('@,@')
  409. else:
  410. v = eval(v, {}, {})
  411. ret['init.r'], ret['init.i'] = str(v.real), str(v.imag)
  412. except Exception:
  413. raise ValueError(
  414. f'getinit: expected complex number `(r,i)\' but got `{init}\' as initial value of {a!r}.')
  415. if isarray(var):
  416. init = f"(capi_c.r={ret['init.r']},capi_c.i={ret['init.i']},capi_c)"
  417. elif isstring(var):
  418. if not init:
  419. init, showinit = '""', "''"
  420. if init[0] == "'":
  421. init = '"%s"' % (init[1:-1].replace('"', '\\"'))
  422. if init[0] == '"':
  423. showinit = f"'{init[1:-1]}'"
  424. return init, showinit
  425. def get_elsize(var):
  426. if isstring(var) or isstringarray(var):
  427. elsize = getstrlength(var)
  428. # override with user-specified length when available:
  429. elsize = var['charselector'].get('f2py_len', elsize)
  430. return elsize
  431. if ischaracter(var) or ischaracterarray(var):
  432. return '1'
  433. # for numerical types, PyArray_New* functions ignore specified
  434. # elsize, so we just return 1 and let elsize be determined at
  435. # runtime, see fortranobject.c
  436. return '1'
  437. def sign2map(a, var):
  438. """
  439. varname,ctype,atype
  440. init,init.r,init.i,pytype
  441. vardebuginfo,vardebugshowvalue,varshowvalue
  442. varrformat
  443. intent
  444. """
  445. out_a = a
  446. if isintent_out(var):
  447. for k in var['intent']:
  448. if k[:4] == 'out=':
  449. out_a = k[4:]
  450. break
  451. ret = {'varname': a, 'outvarname': out_a, 'ctype': getctype(var)}
  452. intent_flags = []
  453. for f, s in isintent_dict.items():
  454. if f(var):
  455. intent_flags.append(f'F2PY_{s}')
  456. if intent_flags:
  457. # TODO: Evaluate intent_flags here.
  458. ret['intent'] = '|'.join(intent_flags)
  459. else:
  460. ret['intent'] = 'F2PY_INTENT_IN'
  461. if isarray(var):
  462. ret['varrformat'] = 'N'
  463. elif ret['ctype'] in c2buildvalue_map:
  464. ret['varrformat'] = c2buildvalue_map[ret['ctype']]
  465. else:
  466. ret['varrformat'] = 'O'
  467. ret['init'], ret['showinit'] = getinit(a, var)
  468. if hasinitvalue(var) and iscomplex(var) and not isarray(var):
  469. ret['init.r'], ret['init.i'] = markoutercomma(
  470. ret['init'][1:-1]).split('@,@')
  471. if isexternal(var):
  472. ret['cbnamekey'] = a
  473. if a in lcb_map:
  474. ret['cbname'] = lcb_map[a]
  475. ret['maxnofargs'] = lcb2_map[lcb_map[a]]['maxnofargs']
  476. ret['nofoptargs'] = lcb2_map[lcb_map[a]]['nofoptargs']
  477. ret['cbdocstr'] = lcb2_map[lcb_map[a]]['docstr']
  478. ret['cblatexdocstr'] = lcb2_map[lcb_map[a]]['latexdocstr']
  479. else:
  480. ret['cbname'] = a
  481. errmess('sign2map: Confused: external %s is not in lcb_map%s.\n' % (
  482. a, list(lcb_map.keys())))
  483. if isstring(var):
  484. ret['length'] = getstrlength(var)
  485. if isarray(var):
  486. ret = dictappend(ret, getarrdims(a, var))
  487. dim = copy.copy(var['dimension'])
  488. if ret['ctype'] in c2capi_map:
  489. ret['atype'] = c2capi_map[ret['ctype']]
  490. ret['elsize'] = get_elsize(var)
  491. # Debug info
  492. if debugcapi(var):
  493. il = [isintent_in, 'input', isintent_out, 'output',
  494. isintent_inout, 'inoutput', isrequired, 'required',
  495. isoptional, 'optional', isintent_hide, 'hidden',
  496. iscomplex, 'complex scalar',
  497. l_and(isscalar, l_not(iscomplex)), 'scalar',
  498. isstring, 'string', isarray, 'array',
  499. iscomplexarray, 'complex array', isstringarray, 'string array',
  500. iscomplexfunction, 'complex function',
  501. l_and(isfunction, l_not(iscomplexfunction)), 'function',
  502. isexternal, 'callback',
  503. isintent_callback, 'callback',
  504. isintent_aux, 'auxiliary',
  505. ]
  506. rl = []
  507. for i in range(0, len(il), 2):
  508. if il[i](var):
  509. rl.append(il[i + 1])
  510. if isstring(var):
  511. rl.append(f"slen({a})={ret['length']}")
  512. if isarray(var):
  513. ddim = ','.join(
  514. map(lambda x, y: f'{x}|{y}', var['dimension'], dim))
  515. rl.append(f'dims({ddim})')
  516. if isexternal(var):
  517. ret['vardebuginfo'] = f"debug-capi:{a}=>{ret['cbname']}:{','.join(rl)}"
  518. else:
  519. ret['vardebuginfo'] = 'debug-capi:%s %s=%s:%s' % (
  520. ret['ctype'], a, ret['showinit'], ','.join(rl))
  521. if isscalar(var):
  522. if ret['ctype'] in cformat_map:
  523. ret['vardebugshowvalue'] = f"debug-capi:{a}={cformat_map[ret['ctype']]}"
  524. if isstring(var):
  525. ret['vardebugshowvalue'] = 'debug-capi:slen(%s)=%%d %s=\\"%%s\\"' % (
  526. a, a)
  527. if isexternal(var):
  528. ret['vardebugshowvalue'] = f'debug-capi:{a}=%p'
  529. if ret['ctype'] in cformat_map:
  530. ret['varshowvalue'] = f"#name#:{a}={cformat_map[ret['ctype']]}"
  531. ret['showvalueformat'] = f"{cformat_map[ret['ctype']]}"
  532. if isstring(var):
  533. ret['varshowvalue'] = '#name#:slen(%s)=%%d %s=\\"%%s\\"' % (a, a)
  534. ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, var)
  535. if hasnote(var):
  536. ret['note'] = var['note']
  537. return ret
  538. def routsign2map(rout):
  539. """
  540. name,NAME,begintitle,endtitle
  541. rname,ctype,rformat
  542. routdebugshowvalue
  543. """
  544. global lcb_map
  545. name = rout['name']
  546. fname = getfortranname(rout)
  547. ret = {'name': name,
  548. 'texname': name.replace('_', '\\_'),
  549. 'name_lower': name.lower(),
  550. 'NAME': name.upper(),
  551. 'begintitle': gentitle(name),
  552. 'endtitle': gentitle(f'end of {name}'),
  553. 'fortranname': fname,
  554. 'FORTRANNAME': fname.upper(),
  555. 'callstatement': getcallstatement(rout) or '',
  556. 'usercode': getusercode(rout) or '',
  557. 'usercode1': getusercode1(rout) or '',
  558. }
  559. if '_' in fname:
  560. ret['F_FUNC'] = 'F_FUNC_US'
  561. else:
  562. ret['F_FUNC'] = 'F_FUNC'
  563. if '_' in name:
  564. ret['F_WRAPPEDFUNC'] = 'F_WRAPPEDFUNC_US'
  565. else:
  566. ret['F_WRAPPEDFUNC'] = 'F_WRAPPEDFUNC'
  567. lcb_map = {}
  568. if 'use' in rout:
  569. for u in rout['use'].keys():
  570. if u in cb_rules.cb_map:
  571. for un in cb_rules.cb_map[u]:
  572. ln = un[0]
  573. if 'map' in rout['use'][u]:
  574. for k in rout['use'][u]['map'].keys():
  575. if rout['use'][u]['map'][k] == un[0]:
  576. ln = k
  577. break
  578. lcb_map[ln] = un[1]
  579. elif rout.get('externals'):
  580. errmess('routsign2map: Confused: function %s has externals %s but no "use" statement.\n' % (
  581. ret['name'], repr(rout['externals'])))
  582. ret['callprotoargument'] = getcallprotoargument(rout, lcb_map) or ''
  583. if isfunction(rout):
  584. if 'result' in rout:
  585. a = rout['result']
  586. else:
  587. a = rout['name']
  588. ret['rname'] = a
  589. ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, rout)
  590. ret['ctype'] = getctype(rout['vars'][a])
  591. if hasresultnote(rout):
  592. ret['resultnote'] = rout['vars'][a]['note']
  593. rout['vars'][a]['note'] = ['See elsewhere.']
  594. if ret['ctype'] in c2buildvalue_map:
  595. ret['rformat'] = c2buildvalue_map[ret['ctype']]
  596. else:
  597. ret['rformat'] = 'O'
  598. errmess('routsign2map: no c2buildvalue key for type %s\n' %
  599. (repr(ret['ctype'])))
  600. if debugcapi(rout):
  601. if ret['ctype'] in cformat_map:
  602. ret['routdebugshowvalue'] = 'debug-capi:%s=%s' % (
  603. a, cformat_map[ret['ctype']])
  604. if isstringfunction(rout):
  605. ret['routdebugshowvalue'] = 'debug-capi:slen(%s)=%%d %s=\\"%%s\\"' % (
  606. a, a)
  607. if isstringfunction(rout):
  608. ret['rlength'] = getstrlength(rout['vars'][a])
  609. if ret['rlength'] == '-1':
  610. errmess('routsign2map: expected explicit specification of the length of the string returned by the fortran function %s; taking 10.\n' % (
  611. repr(rout['name'])))
  612. ret['rlength'] = '10'
  613. if hasnote(rout):
  614. ret['note'] = rout['note']
  615. rout['note'] = ['See elsewhere.']
  616. return ret
  617. def modsign2map(m):
  618. """
  619. modulename
  620. """
  621. if ismodule(m):
  622. ret = {'f90modulename': m['name'],
  623. 'F90MODULENAME': m['name'].upper(),
  624. 'texf90modulename': m['name'].replace('_', '\\_')}
  625. else:
  626. ret = {'modulename': m['name'],
  627. 'MODULENAME': m['name'].upper(),
  628. 'texmodulename': m['name'].replace('_', '\\_')}
  629. ret['restdoc'] = getrestdoc(m) or []
  630. if hasnote(m):
  631. ret['note'] = m['note']
  632. ret['usercode'] = getusercode(m) or ''
  633. ret['usercode1'] = getusercode1(m) or ''
  634. if m['body']:
  635. ret['interface_usercode'] = getusercode(m['body'][0]) or ''
  636. else:
  637. ret['interface_usercode'] = ''
  638. ret['pymethoddef'] = getpymethoddef(m) or ''
  639. if 'gil_used' in m:
  640. ret['gil_used'] = m['gil_used']
  641. if 'coutput' in m:
  642. ret['coutput'] = m['coutput']
  643. if 'f2py_wrapper_output' in m:
  644. ret['f2py_wrapper_output'] = m['f2py_wrapper_output']
  645. return ret
  646. def cb_sign2map(a, var, index=None):
  647. ret = {'varname': a}
  648. ret['varname_i'] = ret['varname']
  649. ret['ctype'] = getctype(var)
  650. if ret['ctype'] in c2capi_map:
  651. ret['atype'] = c2capi_map[ret['ctype']]
  652. ret['elsize'] = get_elsize(var)
  653. if ret['ctype'] in cformat_map:
  654. ret['showvalueformat'] = f"{cformat_map[ret['ctype']]}"
  655. if isarray(var):
  656. ret = dictappend(ret, getarrdims(a, var))
  657. ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, var)
  658. if hasnote(var):
  659. ret['note'] = var['note']
  660. var['note'] = ['See elsewhere.']
  661. return ret
  662. def cb_routsign2map(rout, um):
  663. """
  664. name,begintitle,endtitle,argname
  665. ctype,rctype,maxnofargs,nofoptargs,returncptr
  666. """
  667. ret = {'name': f"cb_{rout['name']}_in_{um}",
  668. 'returncptr': ''}
  669. if isintent_callback(rout):
  670. if '_' in rout['name']:
  671. F_FUNC = 'F_FUNC_US'
  672. else:
  673. F_FUNC = 'F_FUNC'
  674. ret['callbackname'] = f"{F_FUNC}({rout['name'].lower()},{rout['name'].upper()})"
  675. ret['static'] = 'extern'
  676. else:
  677. ret['callbackname'] = ret['name']
  678. ret['static'] = 'static'
  679. ret['argname'] = rout['name']
  680. ret['begintitle'] = gentitle(ret['name'])
  681. ret['endtitle'] = gentitle(f"end of {ret['name']}")
  682. ret['ctype'] = getctype(rout)
  683. ret['rctype'] = 'void'
  684. if ret['ctype'] == 'string':
  685. ret['rctype'] = 'void'
  686. else:
  687. ret['rctype'] = ret['ctype']
  688. if ret['rctype'] != 'void':
  689. if iscomplexfunction(rout):
  690. ret['returncptr'] = """
  691. #ifdef F2PY_CB_RETURNCOMPLEX
  692. return_value=
  693. #endif
  694. """
  695. else:
  696. ret['returncptr'] = 'return_value='
  697. if ret['ctype'] in cformat_map:
  698. ret['showvalueformat'] = f"{cformat_map[ret['ctype']]}"
  699. if isstringfunction(rout):
  700. ret['strlength'] = getstrlength(rout)
  701. if isfunction(rout):
  702. if 'result' in rout:
  703. a = rout['result']
  704. else:
  705. a = rout['name']
  706. if hasnote(rout['vars'][a]):
  707. ret['note'] = rout['vars'][a]['note']
  708. rout['vars'][a]['note'] = ['See elsewhere.']
  709. ret['rname'] = a
  710. ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, rout)
  711. if iscomplexfunction(rout):
  712. ret['rctype'] = """
  713. #ifdef F2PY_CB_RETURNCOMPLEX
  714. #ctype#
  715. #else
  716. void
  717. #endif
  718. """
  719. elif hasnote(rout):
  720. ret['note'] = rout['note']
  721. rout['note'] = ['See elsewhere.']
  722. nofargs = 0
  723. nofoptargs = 0
  724. if 'args' in rout and 'vars' in rout:
  725. for a in rout['args']:
  726. var = rout['vars'][a]
  727. if l_or(isintent_in, isintent_inout)(var):
  728. nofargs = nofargs + 1
  729. if isoptional(var):
  730. nofoptargs = nofoptargs + 1
  731. ret['maxnofargs'] = repr(nofargs)
  732. ret['nofoptargs'] = repr(nofoptargs)
  733. if hasnote(rout) and isfunction(rout) and 'result' in rout:
  734. ret['routnote'] = rout['note']
  735. rout['note'] = ['See elsewhere.']
  736. return ret
  737. def common_sign2map(a, var): # obsolete
  738. ret = {'varname': a, 'ctype': getctype(var)}
  739. if isstringarray(var):
  740. ret['ctype'] = 'char'
  741. if ret['ctype'] in c2capi_map:
  742. ret['atype'] = c2capi_map[ret['ctype']]
  743. ret['elsize'] = get_elsize(var)
  744. if ret['ctype'] in cformat_map:
  745. ret['showvalueformat'] = f"{cformat_map[ret['ctype']]}"
  746. if isarray(var):
  747. ret = dictappend(ret, getarrdims(a, var))
  748. elif isstring(var):
  749. ret['size'] = getstrlength(var)
  750. ret['rank'] = '1'
  751. ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, var)
  752. if hasnote(var):
  753. ret['note'] = var['note']
  754. var['note'] = ['See elsewhere.']
  755. # for strings this returns 0-rank but actually is 1-rank
  756. ret['arrdocstr'] = getarrdocsign(a, var)
  757. return ret