capi_maps.py 31 KB

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