Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions doc/release/upcoming_changes/24555.improvement.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
``iso_c_binding`` support for ``f2py``
--------------------------------------
Previously, users would have to define their own custom ``f2cmap`` file to use
type mappings defined by the Fortran2003 ``iso_c_binding`` intrinsic module.
These type maps are now natively supported by ``f2py``
10 changes: 10 additions & 0 deletions doc/release/upcoming_changes/24555.new_feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
``bind(c)`` support for ``f2py``
--------------------------------
Both functions and subroutines can be annotated with ``bind(c)``. ``f2py`` will
handle both the correct type mapping, and preserve the unique label for other
``C`` interfaces.

**Note:** ``bind(c, name = 'routine_name_other_than_fortran_routine')`` is not
honored by the ``f2py`` bindings by design, since ``bind(c)`` with the ``name``
is meant to guarantee only the same name in ``C`` and ``Fortran``, not in
``Python`` and ``Fortran``.
46 changes: 46 additions & 0 deletions numpy/f2py/_isocbind.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
iso_c_binding_map = {
'integer': {
'c_int': 'int',
'c_short': 'short int',
'c_long': 'long int',
'c_long_long': 'long long int',
'c_signed_char': 'signed char',
'c_size_t': 'size_t',
'c_int8_t': 'int8_t',
'c_int16_t': 'int16_t',
'c_int32_t': 'int32_t',
'c_int64_t': 'int64_t',
'c_int_least8_t': 'int_least8_t',
'c_int_least16_t': 'int_least16_t',
'c_int_least32_t': 'int_least32_t',
'c_int_least64_t': 'int_least64_t',
'c_int_fast8_t': 'int_fast8_t',
'c_int_fast16_t': 'int_fast16_t',
'c_int_fast32_t': 'int_fast32_t',
'c_int_fast64_t': 'int_fast64_t',
'c_intmax_t': 'intmax_t',
'c_intptr_t': 'intptr_t',
'c_ptrdiff_t': 'intptr_t',
},
'real': {
'c_float': 'float',
'c_double': 'double',
'c_long_double': 'long double'
},
'complex': {
'c_float_complex': 'float _Complex',
'c_double_complex': 'double _Complex',
'c_long_double_complex': 'long double _Complex'
},
'logical': {
'c_bool': '_Bool'
},
'character': {
'c_char': 'char'
}
}

isoc_kindmap = {}
for fortran_type, c_type_dict in iso_c_binding_map.items():
for c_type in c_type_dict.keys():
isoc_kindmap[c_type] = fortran_type
26 changes: 25 additions & 1 deletion numpy/f2py/auxfuncs.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import sys
import types
from functools import reduce
from copy import deepcopy

from . import __version__
from . import cfuncs
Expand Down Expand Up @@ -47,7 +48,8 @@
'isunsigned_chararray', 'isunsigned_long_long',
'isunsigned_long_longarray', 'isunsigned_short',
'isunsigned_shortarray', 'l_and', 'l_not', 'l_or', 'outmess',
'replace', 'show', 'stripcomma', 'throw_error', 'isattr_value'
'replace', 'show', 'stripcomma', 'throw_error', 'isattr_value',
'deep_merge'
]


Expand Down Expand Up @@ -888,3 +890,25 @@ def applyrules(rules, d, var={}):
if ret[k] == []:
del ret[k]
return ret

def deep_merge(dict1, dict2):
"""Recursively merge two dictionaries into a new dictionary.

Parameters:
- dict1: The base dictionary.
- dict2: The dictionary to merge into a copy of dict1.
If a key exists in both, the dict2 value will take precedence.

Returns:
- A new merged dictionary.
"""
merged_dict = deepcopy(dict1)
for key, value in dict2.items():
if key in merged_dict:
if isinstance(merged_dict[key], dict) and isinstance(value, dict):
merged_dict[key] = deep_merge(merged_dict[key], value)
else:
merged_dict[key] = value
else:
merged_dict[key] = value
return merged_dict
2 changes: 2 additions & 0 deletions numpy/f2py/capi_maps.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import os
from .crackfortran import markoutercomma
from . import cb_rules
from ._isocbind import iso_c_binding_map

# The environment provided by auxfuncs.py is needed for some calls to eval.
# As the needed functions cannot be determined by static inspection of the
Expand Down Expand Up @@ -130,6 +131,7 @@
'byte': {'': 'char'},
}

f2cmap_all = deep_merge(f2cmap_all, iso_c_binding_map)
f2cmap_default = copy.deepcopy(f2cmap_all)

f2cmap_mapped = []
Expand Down
27 changes: 23 additions & 4 deletions numpy/f2py/crackfortran.py
Original file line number Diff line number Diff line change
Expand Up @@ -696,7 +696,8 @@ def _simplifyargs(argsline):
return ','.join(a)

crackline_re_1 = re.compile(r'\s*(?P<result>\b[a-z]+\w*\b)\s*=.*', re.I)

crackline_bind_1 = re.compile(r'\s*(?P<bind>\b[a-z]+\w*\b)\s*=.*', re.I)
crackline_bindlang = re.compile(r'\s*bind\(\s*(?P<lang>[^,]+)\s*,\s*name\s*=\s*"(?P<lang_name>[^"]+)"\s*\)', re.I)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These long templates are pretty much unreadable. Might be nice to use a generated parser at some point.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah they take forever to write too 😅, would be nice to explore Lark at some time. The problem is most parsers don't actually support regex based parsing (which is needed for fortran because of the whitespace stuff).


def crackline(line, reset=0):
"""
Expand Down Expand Up @@ -967,12 +968,22 @@ def _resolvetypedefpattern(line):
return m1.group('name'), attrs, m1.group('params')
return None, [], None

def parse_name_for_bind(line):
pattern = re.compile(r'bind\(\s*(?P<lang>[^,]+)(?:\s*,\s*name\s*=\s*["\'](?P<name>[^"\']+)["\']\s*)?\)', re.I)
match = pattern.search(line)
bind_statement = None
if match:
bind_statement = match.group(0)
# Remove the 'bind' construct from the line.
line = line[:match.start()] + line[match.end():]
return line, bind_statement

def _resolvenameargspattern(line):
line, bind_cname = parse_name_for_bind(line)
line = markouterparen(line)
m1 = nameargspattern.match(line)
if m1:
return m1.group('name'), m1.group('args'), m1.group('result'), m1.group('bind')
return m1.group('name'), m1.group('args'), m1.group('result'), bind_cname
m1 = operatorpattern.match(line)
if m1:
name = m1.group('scheme') + '(' + m1.group('name') + ')'
Expand Down Expand Up @@ -1022,7 +1033,7 @@ def analyzeline(m, case, line):
args = []
result = None
else:
name, args, result, _ = _resolvenameargspattern(m.group('after'))
name, args, result, bindcline = _resolvenameargspattern(m.group('after'))
if name is None:
if block == 'block data':
name = '_BLOCK_DATA_'
Expand Down Expand Up @@ -1140,6 +1151,14 @@ def analyzeline(m, case, line):
except Exception:
pass
if block in ['function', 'subroutine']: # set global attributes
# name is fortran name
if bindcline:
bindcdat = re.search(crackline_bindlang, bindcline)
if bindcdat:
groupcache[groupcounter]['bindlang'] = {name : {}}
groupcache[groupcounter]['bindlang'][name]["lang"] = bindcdat.group('lang')
if bindcdat.group('lang_name'):
groupcache[groupcounter]['bindlang'][name]["name"] = bindcdat.group('lang_name')
try:
groupcache[groupcounter]['vars'][name] = appenddecl(
groupcache[groupcounter]['vars'][name], groupcache[groupcounter - 2]['vars'][''])
Expand Down Expand Up @@ -1173,7 +1192,7 @@ def analyzeline(m, case, line):
groupcounter = groupcounter - 1 # end interface

elif case == 'entry':
name, args, result, bind = _resolvenameargspattern(m.group('after'))
name, args, result, _= _resolvenameargspattern(m.group('after'))
if name is not None:
if args:
args = rmbadname([x.strip()
Expand Down
18 changes: 18 additions & 0 deletions numpy/f2py/func2subr.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
issubroutine, issubroutine_wrap, outmess, show
)

from ._isocbind import isoc_kindmap

def var2fixfortran(vars, a, fa=None, f90mode=None):
if fa is None:
Expand Down Expand Up @@ -70,6 +71,13 @@ def var2fixfortran(vars, a, fa=None, f90mode=None):
vardef = '%s(%s)' % (vardef, ','.join(vars[a]['dimension']))
return vardef

def useiso_c_binding(rout):
useisoc = False
for key, value in rout['vars'].items():
kind_value = value.get('kindselector', {}).get('kind')
if kind_value in isoc_kindmap:
return True
return useisoc

def createfuncwrapper(rout, signature=0):
assert isfunction(rout)
Expand Down Expand Up @@ -117,6 +125,7 @@ def add(line, ret=ret):
l1 = l_tmpl.replace('@@@NAME@@@', newname)
rl = None

useisoc = useiso_c_binding(rout)
sargs = ', '.join(args)
if f90mode:
# gh-23598 fix warning
Expand All @@ -129,8 +138,12 @@ def add(line, ret=ret):
(rout['modulename'], name, sargs))
if not signature:
add('use %s, only : %s' % (rout['modulename'], fortranname))
if useisoc:
add('use iso_c_binding')
else:
add('subroutine f2pywrap%s (%s)' % (name, sargs))
if useisoc:
add('use iso_c_binding')
if not need_interface:
add('external %s' % (fortranname))
rl = l_tmpl.replace('@@@NAME@@@', '') + ' ' + fortranname
Expand Down Expand Up @@ -218,14 +231,19 @@ def add(line, ret=ret):

args = rout['args']

useisoc = useiso_c_binding(rout)
sargs = ', '.join(args)
if f90mode:
add('subroutine f2pywrap_%s_%s (%s)' %
(rout['modulename'], name, sargs))
if useisoc:
add('use iso_c_binding')
if not signature:
add('use %s, only : %s' % (rout['modulename'], fortranname))
else:
add('subroutine f2pywrap%s (%s)' % (name, sargs))
if useisoc:
add('use iso_c_binding')
if not need_interface:
add('external %s' % (fortranname))

Expand Down
17 changes: 17 additions & 0 deletions numpy/f2py/tests/src/isocintrin/isoCtests.f90
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
module coddity
use iso_c_binding, only: c_double, c_int
implicit none
contains
subroutine c_add(a, b, c) bind(c, name="c_add")
real(c_double), intent(in) :: a, b
real(c_double), intent(out) :: c
c = a + b
end subroutine c_add
! gh-9693
function wat(x, y) result(z) bind(c)
integer(c_int), intent(in) :: x, y
integer(c_int) :: z

z = x + 7
end function wat
Comment thread
HaoZeke marked this conversation as resolved.
Resolved
end module coddity
19 changes: 19 additions & 0 deletions numpy/f2py/tests/test_isoc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from . import util
import numpy as np

class TestISOC(util.F2PyTest):
sources = [
util.getpath("tests", "src", "isocintrin", "isoCtests.f90"),
]

# gh-24553
def test_c_double(self):
out = self.module.coddity.c_add(1, 2)
exp_out = 3
assert out == exp_out

# gh-9693
def test_bindc_function(self):
out = self.module.coddity.wat(1, 20)
exp_out = 8
assert out == exp_out