capi_maps.py 31 KB

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