0
# Type System
1
2
Comprehensive type system analysis and utility functions for handling Fortran type conversions, kind mapping, array processing, and interoperability between Fortran and Python type systems.
3
4
## Capabilities
5
6
### Type Analysis Functions
7
8
Functions for analyzing and categorizing Fortran types.
9
10
```python { .api }
11
def is_derived_type(typename):
12
"""
13
Check if a type name represents a Fortran derived type.
14
15
Parameters:
16
- typename: str, Fortran type name to check
17
18
Returns:
19
bool, True if typename is a derived type
20
"""
21
22
def derived_typename(typename):
23
"""
24
Extract the base derived type name from a full type specification.
25
26
Parameters:
27
- typename: str, full Fortran type specification
28
29
Returns:
30
str, base derived type name
31
"""
32
33
def strip_type(t):
34
"""
35
Clean and normalize a Fortran type string.
36
37
Parameters:
38
- t: str, Fortran type string to clean
39
40
Returns:
41
str, cleaned type string
42
"""
43
44
def split_type_kind(typename):
45
"""
46
Split a Fortran type into base type and kind specification.
47
48
Parameters:
49
- typename: str, Fortran type with possible kind
50
51
Returns:
52
tuple, (base_type, kind) where kind may be None
53
"""
54
```
55
56
### Type Conversion Functions
57
58
Functions for converting between Fortran, C, and Python type representations.
59
60
```python { .api }
61
def f2c_type(typename, kind_map):
62
"""
63
Convert Fortran type to equivalent C type.
64
65
Parameters:
66
- typename: str, Fortran type name
67
- kind_map: dict, mapping of Fortran kinds to C types
68
69
Returns:
70
str, equivalent C type specification
71
"""
72
73
def f2py_type(type, attributes=None):
74
"""
75
Get f2py-compatible type specification.
76
77
Parameters:
78
- type: str, Fortran type name
79
- attributes: list, optional type attributes
80
81
Returns:
82
str, f2py type specification
83
"""
84
85
def normalise_type(typename, kind_map):
86
"""
87
Normalize Fortran type name using kind mappings.
88
89
Parameters:
90
- typename: str, Fortran type name to normalize
91
- kind_map: dict, kind to type mappings
92
93
Returns:
94
str, normalized type name
95
"""
96
97
def fortran_array_type(typename, kind_map):
98
"""
99
Get Fortran array type specification for a given base type.
100
101
Parameters:
102
- typename: str, base Fortran type
103
- kind_map: dict, kind mappings for type resolution
104
105
Returns:
106
str, Fortran array type specification
107
"""
108
```
109
110
## Built-in Type Mappings
111
112
### Standard Fortran Types
113
114
f90wrap recognizes and handles these standard Fortran intrinsic types:
115
116
**Integer Types:**
117
- `integer` - Default integer type
118
- `integer(kind=int8)` - 8-bit signed integer
119
- `integer(kind=int16)` - 16-bit signed integer
120
- `integer(kind=int32)` - 32-bit signed integer
121
- `integer(kind=int64)` - 64-bit signed integer
122
123
**Real Types:**
124
- `real` - Default real type (usually single precision)
125
- `real(kind=real32)` - 32-bit floating point
126
- `real(kind=real64)` - 64-bit floating point (double precision)
127
- `real(kind=real128)` - 128-bit floating point (quad precision)
128
129
**Complex Types:**
130
- `complex` - Default complex type
131
- `complex(kind=real32)` - Single precision complex
132
- `complex(kind=real64)` - Double precision complex
133
134
**Character Types:**
135
- `character` - Default character type
136
- `character(len=*)` - Deferred length character
137
- `character(len=n)` - Fixed length character
138
139
**Logical Types:**
140
- `logical` - Default logical type
141
- `logical(kind=int8)` - 8-bit logical
142
143
### C Interoperability Types
144
145
Types from the `iso_c_binding` module for C interoperability:
146
147
```python { .api }
148
# C integer types
149
c_int, c_short, c_long, c_long_long
150
c_signed_char, c_size_t, c_int8_t, c_int16_t, c_int32_t, c_int64_t
151
152
# C floating point types
153
c_float, c_double, c_long_double
154
155
# C character types
156
c_char
157
158
# C logical type
159
c_bool
160
161
# C pointer types
162
c_ptr, c_funptr
163
```
164
165
## Usage Examples
166
167
### Basic Type Analysis
168
169
```python
170
from f90wrap.fortran import is_derived_type, derived_typename, split_type_kind
171
172
# Check if type is derived
173
is_derived = is_derived_type('type(my_type)') # True
174
is_intrinsic = is_derived_type('integer') # False
175
176
# Extract derived type name
177
base_name = derived_typename('type(my_type)') # 'my_type'
178
179
# Split type and kind
180
base, kind = split_type_kind('real(kind=real64)') # ('real', 'real64')
181
base, kind = split_type_kind('integer') # ('integer', None)
182
```
183
184
### Type Conversion
185
186
```python
187
from f90wrap.fortran import f2c_type, f2py_type, normalise_type
188
189
# Define kind mappings
190
kind_map = {
191
'real64': 'double',
192
'int32': 'int',
193
'int64': 'long long'
194
}
195
196
# Convert to C type
197
c_type = f2c_type('real(kind=real64)', kind_map) # 'double'
198
c_int = f2c_type('integer(kind=int32)', kind_map) # 'int'
199
200
# Get f2py type
201
f2py_spec = f2py_type('real', ['intent(in)']) # 'real, intent(in)'
202
203
# Normalize type
204
norm_type = normalise_type('real(kind=real64)', kind_map) # 'double'
205
```
206
207
### Array Type Handling
208
209
```python
210
from f90wrap.fortran import fortran_array_type
211
212
# Get array type specification
213
array_type = fortran_array_type('real(kind=real64)', kind_map)
214
# Returns appropriate array type for the base type
215
```
216
217
### Working with Kind Maps
218
219
```python
220
# Example kind map for gfortran
221
gfortran_kinds = {
222
'real32': 'float',
223
'real64': 'double',
224
'int8': 'signed char',
225
'int16': 'short',
226
'int32': 'int',
227
'int64': 'long long'
228
}
229
230
# Example kind map for Intel Fortran
231
intel_kinds = {
232
'real32': 'float',
233
'real64': 'double',
234
'int8': 'char',
235
'int16': 'short',
236
'int32': 'int',
237
'int64': '__int64' # Intel-specific
238
}
239
240
# Use compiler-specific mappings
241
def get_kind_map(compiler):
242
if compiler == 'gfortran':
243
return gfortran_kinds
244
elif compiler == 'ifort':
245
return intel_kinds
246
else:
247
return {} # Default mappings
248
```
249
250
## Advanced Type Features
251
252
### Parameterized Derived Types
253
254
Support for Fortran 2003 parameterized derived types:
255
256
```fortran
257
type :: matrix(k, rows, cols)
258
integer, kind :: k = real64
259
integer, len :: rows, cols
260
real(k) :: data(rows, cols)
261
end type
262
```
263
264
f90wrap handles these by:
265
- Extracting type parameters during parsing
266
- Generating specialized wrappers for each parameter combination
267
- Providing Python interfaces that handle parameter validation
268
269
### Abstract Types and Type-Bound Procedures
270
271
Support for object-oriented Fortran features:
272
273
```fortran
274
type, abstract :: shape
275
contains
276
procedure(area_interface), deferred :: area
277
procedure :: perimeter
278
end type
279
280
type, extends(shape) :: circle
281
real :: radius
282
contains
283
procedure :: area => circle_area
284
end type
285
```
286
287
f90wrap provides:
288
- Python class hierarchies matching Fortran type inheritance
289
- Method dispatch for type-bound procedures
290
- Abstract base class support where appropriate
291
292
### Generic Interfaces
293
294
Handling of Fortran generic interfaces:
295
296
```fortran
297
interface operator(+)
298
module procedure add_reals, add_integers
299
end interface
300
```
301
302
f90wrap creates:
303
- Python methods with appropriate overloading
304
- Type-based dispatch to correct implementation
305
- Documentation of all supported type combinations
306
307
## Type Validation and Error Handling
308
309
### Validation Functions
310
311
The type system includes validation to catch common errors:
312
313
- **Kind Validation**: Verify kind parameters are supported
314
- **Size Validation**: Check array dimensions and type sizes
315
- **Compatibility Validation**: Ensure types can be wrapped properly
316
- **Circular Reference Detection**: Detect circular type dependencies
317
318
### Error Reporting
319
320
Comprehensive error reporting for type issues:
321
322
```python
323
# Example error messages
324
TypeError: "Unsupported Fortran type: 'type(unsupported_type)'"
325
ValueError: "Invalid kind specification: 'real(kind=invalid_kind)'"
326
RuntimeError: "Circular dependency detected in type hierarchy"
327
```
328
329
## Compiler-Specific Considerations
330
331
### gfortran Support
332
333
- Full support for gfortran 4.6+ type system
334
- Standard kind mappings for all intrinsic types
335
- Proper handling of gfortran-specific extensions
336
337
### Intel Fortran Support
338
339
- Support for ifort 12+ type system
340
- Intel-specific kind mappings
341
- Handling of Intel Fortran extensions
342
343
### NAG Fortran Support
344
345
- Basic support for NAG compiler
346
- Standard-compliant type handling
347
- Limited support for NAG-specific features
348
349
## Performance Optimization
350
351
### Type-Specific Optimizations
352
353
- **Scalar Types**: Direct value passing for simple scalars
354
- **Array Types**: Efficient memory layouts for arrays
355
- **Derived Types**: Optimized handle-based access
356
- **String Types**: Minimal copying for string operations
357
358
### Memory Layout Considerations
359
360
- **Fortran Ordering**: Proper handling of column-major arrays
361
- **Padding**: Account for compiler-specific padding in derived types
362
- **Alignment**: Ensure proper memory alignment for performance
363
- **Interoperability**: Optimize for C-Fortran data exchange