Documentation
¶
Index ¶
- func ABS[T signed | float](x T) T
- func ACOS[T float](x T) T
- func AIMAG(z complex64) float32
- func AINT[T float](x T) T
- func ALL(a *Array[bool]) bool
- func ANINT[T float](x T) T
- func ANY(a *Array[bool]) bool
- func ASIN[T float](x T) T
- func ATAN[T float](x T) T
- func ATAN2[T float](y, x T) T
- func ArraySetAdd[T numeric](dst, a, b *Array[T])
- func ArraySetDiv[T numeric](dst, a, b *Array[T])
- func ArraySetMul[T numeric](dst, a, b *Array[T])
- func ArraySetNeg[T numeric](dst, src *Array[T])
- func ArraySetSub[T numeric](dst, a, b *Array[T])
- func CABS(z complex64) float32
- func CDABS(z complex128) float64
- func CEILING[T float](x T) T
- func CHAR(i int32) string
- func CMPLX[T float | signed](x T) complex64
- func CMPLX2[T float | signed](x, y T) complex64
- func COS[T float](x T) T
- func COSH[T float](x T) T
- func CPOW[T complexNum](a, exponent T) T
- func CSQRT(z complex64) complex64
- func CharacterArrayJoin(arr *Array[CharacterArray]) string
- func DCMPLX[T float | signed](x T) complex128
- func DCMPLX2[T float | signed](x, y T) complex128
- func DIM[T numeric](a, b T) T
- func DIMAG(z complex128) float64
- func DOT_PRODUCT[T numeric](a, b *Array[T]) T
- func DPROD(x, y float32) float64
- func DREALPART(z complex128) float64
- func DeclareCommon(set PointerSetter, cb *CommonBlock)
- func EXP[T float](x T) T
- func Equivalence(toEquiv ...PointerSetter)
- func FLOOR[T float](x T) T
- func IABS[T signed](x T) T
- func ICHAR(ch CharacterArray) int32
- func LOG[T float](x T) T
- func LOG10[T float](x T) T
- func MAX[T numeric](first T, rest ...T) T
- func MAXLOC[T arrNumeric](a *Array[T]) int32
- func MAXVAL[T arrNumeric](a *Array[T]) T
- func MIN[T numeric](first T, rest ...T) T
- func MINLOC[T arrNumeric](a *Array[T]) int32
- func MINVAL[T arrNumeric](a *Array[T]) T
- func MOD[T integer](a, p T) T
- func MODREAL[T float](a, p T) T
- func MaxFloat32(vals ...float32) float32
- func MaxInt32(vals ...int32) int32
- func MinFloat32(vals ...float32) float32
- func MinInt32(vals ...int32) int32
- func NINT[T float](x T) int32
- func NORM2[T arrNumeric](a *Array[T]) T
- func POW[T float](a, exponent T) T
- func PRODUCT[T arrNumeric](a *Array[T]) T
- func REALPART(z complex64) float32
- func SIGN[T signed | float](a, b T) T
- func SIN[T float](x T) T
- func SINH[T float](x T) T
- func SQRT[T float](x T) T
- func SUM[T arrNumeric](a *Array[T]) T
- func ScalarRef[T any](v T) *T
- func Stop(code int)
- func TAN[T float](x T) T
- func TANH[T float](x T) T
- func UnsafePointerData[I integer, T any](p PointerTo[T]) I
- type Array
- func ArrayAbs[T numeric](a *Array[T]) *Array[T]
- func ArrayAdd[T numeric](a, b *Array[T]) *Array[T]
- func ArrayAddScalar[T numeric](a *Array[T], s T) *Array[T]
- func ArrayDiv[T numeric](a, b *Array[T]) *Array[T]
- func ArrayDivScalar[T numeric](a *Array[T], s T) *Array[T]
- func ArrayMul[T numeric](a, b *Array[T]) *Array[T]
- func ArrayMulScalar[T numeric](a *Array[T], s T) *Array[T]
- func ArrayNeg[T numeric](a *Array[T]) *Array[T]
- func ArrayPow[T numeric](a *Array[T], s T) *Array[T]
- func ArraySetEqual[T comparable](dst *Array[bool], a, b *Array[T]) *Array[bool]
- func ArraySub[T numeric](a, b *Array[T]) *Array[T]
- func ArraySubScalar[T numeric](a *Array[T], s T) *Array[T]
- func MATMUL[T numeric](a, b *Array[T]) *Array[T]
- func NewArray[T any](data []T, dims ...int) *Array[T]
- func NewArrayWithBounds[T any](data []T, shape, lower, upper []int) *Array[T]
- func NewCharacterArrayArray(charlen int, dims ...int) *Array[CharacterArray]
- func NewCharacterArrayFromStrings(charlen int, values []string, dims ...int) *Array[CharacterArray]
- func ScalarSubArray[T numeric](s T, a *Array[T]) *Array[T]
- func UnallocatedArray[T any](dims ...int) *Array[T]
- func (a *Array[T]) Allocate(dims ...int)
- func (a *Array[T]) Allocated() bool
- func (a *Array[T]) At(indices ...int) T
- func (a *Array[T]) AtOffset(indices ...int) int
- func (a *Array[T]) AtPtr(indices ...int) *T
- func (a *Array[T]) DataUnsafe() unsafe.Pointer
- func (a *Array[T]) Deallocate()
- func (a *Array[T]) Len() int
- func (a *Array[T]) LenBuffer() int
- func (a *Array[T]) Lower() []int
- func (a *Array[T]) LowerDim(dim int) int
- func (from *Array[T]) MoveAlloc(to *Array[T])
- func (a *Array[T]) Pointer() PointerTo[T]
- func (a *Array[T]) Set(value T, indices ...int)
- func (a *Array[T]) SetAll(value T)
- func (a *Array[T]) SetDataUnsafe(v unsafe.Pointer)deprecated
- func (dst *Array[T]) SetFrom(src *Array[T])
- func (a *Array[T]) SetLenBufferUnsafe(length int)
- func (a *Array[T]) Shape() []int
- func (a *Array[T]) Size() int
- func (a *Array[T]) SizeDim(dim int) int
- func (a *Array[T]) SizeElement() int
- func (a *Array[T]) Upper() []int
- func (a *Array[T]) UpperDim(dim int) int
- func (a *Array[T]) View(ranges ...Range) *Array[T]
- type CharacterArray
- func (ch CharacterArray) AdjustL() CharacterArray
- func (ch CharacterArray) AdjustR() CharacterArray
- func (ch *CharacterArray) Allocate(length int)
- func (ch CharacterArray) At(i int) byte
- func (ch CharacterArray) DataUnsafe() unsafe.Pointer
- func (ch CharacterArray) Index(substring string) int
- func (ch CharacterArray) Len() int
- func (ch CharacterArray) LenBuffer() int
- func (ch CharacterArray) LenTrim() int
- func (ch CharacterArray) Set(v byte, i int)
- func (ch *CharacterArray) SetConcat(toJoin ...CharacterArray)
- func (ch *CharacterArray) SetConcatString(toJoin ...string)
- func (ch *CharacterArray) SetDataUnsafe(v unsafe.Pointer)deprecated
- func (ch *CharacterArray) SetFromString(data string)
- func (ch *CharacterArray) SetLenBufferUnsafe(length int)
- func (ch *CharacterArray) SetSubstring(start, end int, data string)
- func (ch CharacterArray) SizeElement() int
- func (ch CharacterArray) String() string
- func (ch CharacterArray) StringLen() string
- func (ch CharacterArray) Substring(start, end int) string
- func (ch CharacterArray) Trim() CharacterArray
- func (ch CharacterArray) View(start, end int) CharacterArray
- type CommonBlock
- type Pointer
- type PointerSetter
- type PointerTo
- func (p PointerTo[T]) Array(shape ...int) *Array[T]
- func (p PointerTo[T]) At(idx int) T
- func (p PointerTo[T]) AtPtr(idx int) *T
- func (p PointerTo[T]) Data() *T
- func (p PointerTo[T]) DataAt(idx int) *T
- func (p PointerTo[T]) DataUnsafe() unsafe.Pointer
- func (p PointerTo[T]) LenBuffer() int
- func (p PointerTo[T]) Set(v T, idx int)
- func (p *PointerTo[T]) SetDataUnsafe(v unsafe.Pointer)deprecated
- func (p *PointerTo[T]) SetLenBufferUnsafe(length int)
- func (p PointerTo[T]) Size() int
- func (p PointerTo[T]) SizeElement() int
- func (p PointerTo[T]) Slice() []T
- func (p PointerTo[T]) View(startOff, endOff int) PointerTo[T]
- type Range
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ABS ¶
func ABS[T signed | float](x T) T
ABS returns the absolute value of x Fortran: ABS(x) - works with INTEGER, REAL, COMPLEX For complex numbers, returns magnitude
func AINT ¶
func AINT[T float](x T) T
AINT truncates x to a whole number (rounds toward zero) Fortran: AINT(x) - returns REAL type
func ALL ¶
ALL returns true if all elements of a logical array are true. Corresponds to Fortran ALL(MASK) intrinsic.
func ANINT ¶
func ANINT[T float](x T) T
ANINT returns the nearest whole number to x Fortran: ANINT(x) - like NINT but returns REAL type
func ANY ¶
ANY returns true if any element of the logical array is true. Corresponds to Fortran ANY(mask).
func ATAN2 ¶
func ATAN2[T float](y, x T) T
ATAN2 returns the arctangent of y/x in radians, using signs to determine quadrant Fortran: ATAN2(y, x)
func ArraySetAdd ¶
func ArraySetAdd[T numeric](dst, a, b *Array[T])
ArraySetAdd performs element-wise addition: dst = a + b All arrays must have the same shape. Corresponds to Fortran: dst = a + b (array expressions)
func ArraySetDiv ¶
func ArraySetDiv[T numeric](dst, a, b *Array[T])
ArraySetDiv performs element-wise division: dst = a / b All arrays must have the same shape. Corresponds to Fortran: dst = a / b (array expressions)
func ArraySetMul ¶
func ArraySetMul[T numeric](dst, a, b *Array[T])
ArraySetMul performs element-wise multiplication: dst = a * b All arrays must have the same shape. Corresponds to Fortran: dst = a * b (array expressions)
func ArraySetNeg ¶
func ArraySetNeg[T numeric](dst, src *Array[T])
ArraySetNeg performs in-place element-wise negation: dst = -src Corresponds to Fortran: dst = -src (array expression, in-place)
func ArraySetSub ¶
func ArraySetSub[T numeric](dst, a, b *Array[T])
ArraySetSub performs element-wise subtraction: dst = a - b All arrays must have the same shape. Corresponds to Fortran: dst = a - b (array expressions)
func CABS ¶
CABS returns the absolute value (magnitude) of a complex number Fortran: CABS(z) - returns REAL
func CDABS ¶
func CDABS(z complex128) float64
CDABS returns the absolute value (magnitude) of a double complex number Fortran: CDABS(z) - returns DOUBLE PRECISION
func CEILING ¶
func CEILING[T float](x T) T
CEILING returns the least integer greater than or equal to x Fortran: CEILING(x)
func CMPLX ¶
func CMPLX[T float | signed](x T) complex64
CMPLX converts a real or integer to complex with zero imaginary part. Fortran: CMPLX(x) - returns COMPLEX
func CMPLX2 ¶
func CMPLX2[T float | signed](x, y T) complex64
CMPLX2 creates a complex number from real and imaginary parts. Fortran: CMPLX(x, y) - returns COMPLEX
func CPOW ¶
func CPOW[T complexNum](a, exponent T) T
POW returns a to the power of exponent. In fortran represented as a**exponent.
func CharacterArrayJoin ¶
func CharacterArrayJoin(arr *Array[CharacterArray]) string
CharacterArrayJoin concatenates all elements of a CHARACTER array into a single Go string. Used when a CHARACTER array is passed as a format specifier to WRITE/READ.
func DCMPLX ¶
func DCMPLX[T float | signed](x T) complex128
DCMPLX converts to double complex with zero imaginary part. Fortran: DCMPLX(x) - returns DOUBLE COMPLEX
func DCMPLX2 ¶
func DCMPLX2[T float | signed](x, y T) complex128
DCMPLX2 creates a double complex number from real and imaginary parts. Fortran: DCMPLX(x, y) - returns DOUBLE COMPLEX
func DIM ¶
func DIM[T numeric](a, b T) T
DIM returns the positive difference (a - b if a > b, else 0) Fortran: DIM(a, b)
func DIMAG ¶
func DIMAG(z complex128) float64
DIMAG returns the imaginary part of a double complex number. Fortran: DIMAG(z) - returns DOUBLE PRECISION
func DOT_PRODUCT ¶
func DOT_PRODUCT[T numeric](a, b *Array[T]) T
DOT_PRODUCT computes the dot product of two 1D arrays. Corresponds to Fortran DOT_PRODUCT(VECTOR_A, VECTOR_B) intrinsic. For numeric arrays: result = sum(a(i) * b(i))
func DPROD ¶
DPROD returns the double-precision product of two REAL arguments Fortran: DPROD(x, y) - returns DOUBLE PRECISION
func DREALPART ¶
func DREALPART(z complex128) float64
DREALPART returns the real part of a double complex number. Fortran: DREAL(z) - returns DOUBLE PRECISION
func DeclareCommon ¶
func DeclareCommon(set PointerSetter, cb *CommonBlock)
DeclareCommon wires a variable to share memory with a COMMON block. Per Fortran standard, COMMON blocks are packed without padding (no alignment requirements).
func Equivalence ¶
func Equivalence(toEquiv ...PointerSetter)
Equivalence implements Fortran's EQUIVALENCE statement by making multiple pointers share the same underlying memory allocation.
Fortran EQUIVALENCE ¶
The EQUIVALENCE statement forces multiple variables to share the same memory location:
DOUBLE PRECISION :: dval(100) INTEGER :: ival(200) EQUIVALENCE (dval, ival)
After equivalence, dval and ival refer to the same memory region.
How It Works ¶
Equivalence finds the largest allocation among the provided pointers and sets all pointers to share that base address. Each pointer retains its own type information for element access.
Usage ¶
All arguments must be pointers to PointerSetter types (use & operator):
var floatPtr PointerTo[float64] var intPtr PointerTo[int32] floatPtr = MALLOC[float64](100 * 8) // Allocate 100 float64s Equivalence(&floatPtr, &intPtr) // Now both point to same memory; intPtr sees 200 int32 elements
Notes ¶
For type-punning (viewing memory as a different type), prefer PointerFrom which returns a new typed view without modifying the original pointer.
func FLOOR ¶
func FLOOR[T float](x T) T
FLOOR returns the greatest integer less than or equal to x Fortran: FLOOR(x)
func IABS ¶
func IABS[T signed](x T) T
IABS returns the absolute value of an integer Fortran: IABS(i) - works with INTEGER
func ICHAR ¶
func ICHAR(ch CharacterArray) int32
ICHAR returns the ASCII value of the first character (Fortran ICHAR intrinsic).
func LOG ¶
func LOG[T float](x T) T
LOG returns the natural logarithm of x Fortran: LOG(x) or ALOG(x)
func LOG10 ¶
func LOG10[T float](x T) T
LOG10 returns the base-10 logarithm of x Fortran: LOG10(x) or ALOG10(x)
func MAX ¶
func MAX[T numeric](first T, rest ...T) T
MAX returns the maximum value from a variadic list Fortran: MAX(a1, a2, ..., an)
func MAXLOC ¶
MAXLOC returns the 1-based index of the maximum element. Corresponds to Fortran MAXLOC(array).
func MAXVAL ¶
func MAXVAL[T arrNumeric](a *Array[T]) T
MAXVAL returns the maximum element. Corresponds to Fortran MAXVAL(array).
func MIN ¶
func MIN[T numeric](first T, rest ...T) T
MIN returns the minimum value from a variadic list Fortran: MIN(a1, a2, ..., an)
func MINLOC ¶
MINLOC returns the 1-based index of the minimum element. Corresponds to Fortran MINLOC(array).
func MINVAL ¶
func MINVAL[T arrNumeric](a *Array[T]) T
MINVAL returns the minimum element. Corresponds to Fortran MINVAL(array).
func MOD ¶
func MOD[T integer](a, p T) T
MOD returns the remainder of a divided by p (same sign as a) Fortran: MOD(a, p) - works with INTEGER and REAL For integers: a - INT(a/p) * p For reals: a - AINT(a/p) * p
func MODREAL ¶
func MODREAL[T float](a, p T) T
MODREAL returns the floating-point remainder Fortran: MOD(a, p) for REAL arguments
func MaxFloat32 ¶
MaxFloat32 is a convenience wrapper for MAX with float32
func MinFloat32 ¶
MinFloat32 is a convenience wrapper for MIN with float32
func NINT ¶
func NINT[T float](x T) int32
NINT returns the nearest integer to x Fortran: NINT(x) - rounds to nearest integer (0.5 rounds away from zero)
func NORM2 ¶
func NORM2[T arrNumeric](a *Array[T]) T
NORM2 returns the Euclidean norm of all elements. Corresponds to Fortran NORM2(array).
func POW ¶
func POW[T float](a, exponent T) T
POW returns a to the power of exponent. In fortran represented as a**exponent.
func PRODUCT ¶
func PRODUCT[T arrNumeric](a *Array[T]) T
PRODUCT returns the product of all elements. Corresponds to Fortran PRODUCT(array).
func REALPART ¶
REALPART returns the real part of a complex number. Fortran: REAL(z) when z is complex - returns REAL
func SIGN ¶
func SIGN[T signed | float](a, b T) T
SIGN transfers the sign of b to the magnitude of a Fortran: SIGN(a, b) returns |a| if b >= 0, -|a| if b < 0
func SQRT ¶
func SQRT[T float](x T) T
SQRT returns the square root of x Fortran: SQRT(x) - works with REAL, COMPLEX
func SUM ¶
func SUM[T arrNumeric](a *Array[T]) T
SUM returns the sum of all array elements. Corresponds to Fortran SUM(array).
func ScalarRef ¶
func ScalarRef[T any](v T) *T
ScalarRef returns a pointer to a copy of v. Used at Fortran call sites where a non-addressable expression (literal, arithmetic result) is passed to a by-reference scalar parameter with no INTENT(IN) declaration.
func UnsafePointerData ¶
UnsafePointerData converts a Pointer to an integer address, matching Fortran's treatment of Cray-style POINTER variables as INTEGER addresses.
This enables Fortran patterns like:
INTEGER :: ptr1, ptr2 DOUBLE PRECISION :: arr1(1), arr2(1) POINTER (ptr1, arr1(1)), (ptr2, arr2(1)) ptr1 = MALLOC(100 * 8) ptr2 = ptr1 ! Share the same memory
Transpiles to:
var ptr1, ptr2 intrinsic.Pointer[float64] ptr1 = intrinsic.MALLOC[float64](100 * 8) ptr2 = ptr1 // Go pointers share directly, no conversion needed
The integer conversion is mainly needed for interop with legacy code that stores addresses in INTEGER variables or performs pointer arithmetic.
Types ¶
type Array ¶
type Array[T any] struct { // contains filtered or unexported fields }
Array represents a multi-dimensional Fortran array with column-major layout. It uses a single contiguous memory allocation (slab allocation) for efficiency.
Design rationale based on Fortran standards:
FORTRAN 77 (ANSI X3J3/90.4): - Section 5.1.1: Arrays have 1-7 dimensions (line 2075-2076) - Section 5.1.1.1: Dimension declarator format is [lower:]upper - Section 5.1.1.2: If lower bound omitted, defaults to 1 (line 2123-2124) - Section 5.1.1.2: Bounds can be negative, zero, or positive (line 2120-2121) - Section 5.2.4-5.2.5: Array element ordering and storage sequence (line 2264-2302) - Table 1 (line 2425-2463): Subscript value formula defines column-major layout
- 1D: subscript_value = 1 + (s1 - j1)
- 2D: subscript_value = 1 + (s1 - j1) + (s2 - j2)*d1
- 3D: subscript_value = 1 + (s1 - j1) + (s2 - j2)*d1 + (s3 - j3)*d2*d1
- Where di = ki - ji + 1 (size of dimension i)
Fortran 95 (ISO/IEC 1539:1991): - Section 6.2.2.3: Array element order (line 7246-7250) - Table 6.1 (line 7269-7348): Same subscript order formula as F77 - Note 1 (line 7350): di = max(ki - ji + 1, 0) - Added ALLOCATABLE arrays (line 5188-5193) - Added assumed-shape arrays (line 5631-5643)
Column-major layout means the FIRST index varies fastest in memory. For a 2D array A(3,4), memory order is: A(1,1), A(2,1), A(3,1), A(1,2), A(2,2), ...
Example (ColumnMajor) ¶
Example demonstrating column-major memory layout In Fortran, the first index varies fastest
package main
import (
"fmt"
"github.com/soypat/go-fortran/intrinsic"
)
func main() {
// Create a 2x3 matrix
matrix := intrinsic.NewArray[int32](nil, 2, 3)
// Fill with unique values
matrix.Set(11, 1, 1)
matrix.Set(21, 2, 1)
matrix.Set(12, 1, 2)
matrix.Set(22, 2, 2)
matrix.Set(13, 1, 3)
matrix.Set(23, 2, 3)
// Memory order is column-major: (1,1), (2,1), (1,2), (2,2), (1,3), (2,3)
// This matches Fortran's array storage sequence
fmt.Println("Accessing by row:")
for i := 1; i <= 2; i++ {
for j := 1; j <= 3; j++ {
if j > 1 {
fmt.Print(" ")
}
fmt.Printf("%d", matrix.At(i, j))
}
fmt.Println()
}
}
Output: Accessing by row: 11 12 13 21 22 23
Example (Intrinsics) ¶
Example of intrinsic function equivalents
package main
import (
"fmt"
"github.com/soypat/go-fortran/intrinsic"
)
func main() {
matrix := intrinsic.NewArray[int32](nil, 3, 4)
// SIZE(array, 1) - size of first dimension
fmt.Printf("SIZE = %d\n", matrix.Len())
// SHAPE(array) - shape of all dimensions
fmt.Printf("SHAPE = %v\n", matrix.Shape())
// LBOUND(array) - lower bounds
fmt.Printf("LBOUND = %v\n", matrix.Lower())
// UBOUND(array) - upper bounds
fmt.Printf("UBOUND = %v\n", matrix.Upper())
}
Output: SIZE = 3 SHAPE = [3 4] LBOUND = [1 1] UBOUND = [3 4]
func ArrayAbs ¶
ArrayAbs returns a new array with each element's absolute value: result = |a| Corresponds to Fortran: result = ABS(a) (array expression)
func ArrayAdd ¶
ArrayAdd returns a new array with element-wise addition: result = a + b Corresponds to Fortran: result = a + b (array expression)
func ArrayAddScalar ¶
ArrayAddScalar returns a new array with each element incremented by scalar s: result = a + s
func ArrayDiv ¶
ArrayDiv returns a new array with element-wise division: result = a / b Corresponds to Fortran: result = a / b (array expression)
func ArrayDivScalar ¶
ArrayDivScalar returns a new array with each element divided by scalar s: result = a / s
func ArrayMul ¶
ArrayMul returns a new array with element-wise multiplication: result = a * b Corresponds to Fortran: result = a * b (array expression)
func ArrayMulScalar ¶
ArrayMulScalar returns a new array with each element multiplied by scalar s: result = a * s
func ArrayNeg ¶
ArrayNeg returns a new array with each element negated: result = -a Corresponds to Fortran: result = -a (unary array expression)
func ArrayPow ¶
ArrayPow returns a new array with each element raised to scalar power s: result = a**s Corresponds to Fortran: result = a**s (array expression)
func ArraySetEqual ¶
ArraySetEqual performs element-wise equality comparison: dst[i] = (a[i] == b[i]) If dst is nil, a new array with the same shape as a is allocated. All arrays must have compatible shapes. Corresponds to Fortran: a == b (array expressions)
func ArraySub ¶
ArraySub returns a new array with element-wise subtraction: result = a - b Corresponds to Fortran: result = a - b (array expression)
func ArraySubScalar ¶
ArraySubScalar returns a new array with scalar s subtracted: result = a - s
func MATMUL ¶
MATMUL computes the matrix product of two arrays. Corresponds to Fortran MATMUL(MATRIX_A, MATRIX_B) intrinsic. Supports 2D×2D, 2D×1D, and 1D×2D cases using column-major layout.
func NewArray ¶
Example (OneDimensional) ¶
Example of 1D array with default bounds [1:size] Corresponds to Fortran: INTEGER :: arr(5)
package main
import (
"fmt"
"github.com/soypat/go-fortran/intrinsic"
)
func main() {
arr := intrinsic.NewArray[int32](nil, 5)
// Set elements using Fortran 1-based indexing
arr.Set(10, 1)
arr.Set(20, 2)
arr.Set(30, 3)
// Access elements
fmt.Println(arr.At(1))
fmt.Println(arr.At(2))
fmt.Println(arr.At(3))
}
Output: 10 20 30
Example (TwoDimensional) ¶
Example of 2D array with column-major layout Corresponds to Fortran: REAL :: matrix(3, 4)
package main
import (
"fmt"
"github.com/soypat/go-fortran/intrinsic"
)
func main() {
matrix := intrinsic.NewArray[float32](nil, 3, 4)
// Create identity-like matrix
matrix.Set(1.0, 1, 1)
matrix.Set(1.0, 2, 2)
matrix.Set(1.0, 3, 3)
// Access elements
fmt.Printf("matrix(1,1) = %.1f\n", matrix.At(1, 1))
fmt.Printf("matrix(2,2) = %.1f\n", matrix.At(2, 2))
fmt.Printf("matrix(3,3) = %.1f\n", matrix.At(3, 3))
}
Output: matrix(1,1) = 1.0 matrix(2,2) = 1.0 matrix(3,3) = 1.0
func NewArrayWithBounds ¶
NewArrayWithBounds creates an array with custom bounds for each dimension. Supports arbitrary lower bounds as per F77 Section 5.1.1.2 (line 2120-2121).
Example: DIMENSION(-5:5, 0:9) creates an array with:
- shape = [11, 10] (size of each dimension)
- lower = [-5, 0] (lower bounds)
- upper = [5, 9] (upper bounds)
The shape, lower, and upper slices must have the same length (number of dimensions). Column-major strides are computed as:
- stride[0] = 1
- stride[i] = stride[i-1] * shape[i-1]
Example ¶
Example of array with custom bounds Corresponds to Fortran: DIMENSION A(-5:5)
package main
import (
"fmt"
"github.com/soypat/go-fortran/intrinsic"
)
func main() {
// Array with bounds from -5 to 5 (11 elements)
arr := intrinsic.NewArrayWithBounds[int32](nil,
[]int{11}, // shape: 11 elements
[]int{-5}, // lower bound: -5
[]int{5}, // upper bound: 5
)
// Set elements using custom bounds
arr.Set(100, -5) // First element
arr.Set(0, 0) // Middle element
arr.Set(100, 5) // Last element
fmt.Printf("A(-5) = %d\n", arr.At(-5))
fmt.Printf("A(0) = %d\n", arr.At(0))
fmt.Printf("A(5) = %d\n", arr.At(5))
}
Output: A(-5) = 100 A(0) = 0 A(5) = 100
Example (TwoDimensional) ¶
Example of 2D array with custom bounds Corresponds to Fortran: DIMENSION matrix(0:2, 10:12)
package main
import (
"fmt"
"github.com/soypat/go-fortran/intrinsic"
)
func main() {
// 2D array with custom bounds: (0:2, 10:12)
matrix := intrinsic.NewArrayWithBounds[int32](nil,
[]int{3, 3}, // shape: 3x3
[]int{0, 10}, // lower bounds: 0, 10
[]int{2, 12}, // upper bounds: 2, 12
)
// Set corner elements
matrix.Set(1, 0, 10) // Bottom-left
matrix.Set(2, 2, 12) // Top-right
fmt.Printf("matrix(0,10) = %d\n", matrix.At(0, 10))
fmt.Printf("matrix(2,12) = %d\n", matrix.At(2, 12))
}
Output: matrix(0,10) = 1 matrix(2,12) = 2
func NewCharacterArrayArray ¶
func NewCharacterArrayArray(charlen int, dims ...int) *Array[CharacterArray]
NewCharacterArrayArray creates a multi-dimensional array of CHARACTER(LEN=charlen) strings. Each CharacterArray element is pre-allocated with the specified character length.
func NewCharacterArrayFromStrings ¶
func NewCharacterArrayFromStrings(charlen int, values []string, dims ...int) *Array[CharacterArray]
NewCharacterArrayFromStrings creates a 1D array of CHARACTER(LEN=charlen) strings from a slice of Go strings. Each string is padded/truncated to charlen.
func ScalarSubArray ¶
ScalarSubArray returns a new array: result = s - a
func UnallocatedArray ¶
func (*Array[T]) Allocate ¶
Allocate allocates the array with given dimensions (1-based bounds). Panics if already allocated (Fortran semantics without STAT=).
func (*Array[T]) At ¶
At returns the element at the given indices (using Fortran indexing with custom bounds) Implements the subscript value formula from F77 Table 1 / F95 Table 6.1.
Example for 2D array with bounds (1:3, 1:4):
arr.At(2, 3) accesses element at row 2, column 3 offset = (2 - 1)*1 + (3 - 1)*3 = 1 + 6 = 7
Example for array with custom bounds (-5:5, 0:9):
arr.At(0, 5) accesses element at indices (0, 5) offset = (0 - (-5))*1 + (5 - 0)*11 = 5 + 55 = 60
func (*Array[T]) DataUnsafe ¶
DataUnsafe implements Pointer interface.
func (*Array[T]) Deallocate ¶
func (a *Array[T]) Deallocate()
Deallocate frees the array's memory. Panics if not allocated (Fortran semantics without STAT=).
func (*Array[T]) Len ¶
Len returns the size of the first dimension Corresponds to Fortran SIZE(array, 1) intrinsic
func (*Array[T]) Lower ¶
Lower returns a copy of the lower bounds slice Corresponds to Fortran LBOUND(array) intrinsic (no dimension argument)
func (*Array[T]) LowerDim ¶
LowerDim returns the lower bound of a specific dimension (1-based dimension index) Corresponds to Fortran LBOUND(array, dim) intrinsic
func (*Array[T]) MoveAlloc ¶
MoveAlloc moves the allocation from the receiver (FROM) to to (TO). Implements Fortran MOVE_ALLOC(FROM, TO): TO gets FROM's allocation, FROM becomes unallocated.
func (*Array[T]) Set ¶
Set sets the element at the given indices (using Fortran indexing with custom bounds) Implements the subscript value formula from F77 Table 1 / F95 Table 6.1.
Example: arr.Set(value, 1, 2) sets the element at row 1, column 2
func (*Array[T]) SetAll ¶
func (a *Array[T]) SetAll(value T)
SetAll sets all elements of the array to the given value. Corresponds to Fortran array(:) = value or array = value syntax.
func (*Array[T]) SetDataUnsafe
deprecated
SetDataUnsafe implements PointerSetter interface.
Deprecated: Extremely unsafe.
func (*Array[T]) SetFrom ¶
SetFrom copies all elements from src to dst element-wise. Both arrays must have the same shape. Corresponds to Fortran: dst = src (array assignment)
func (*Array[T]) SetLenBufferUnsafe ¶
SetLenBufferUnsafe sets the number of elements in the backing data slice.
func (*Array[T]) Shape ¶
Shape returns a copy of the shape slice (size of each dimension) Corresponds to Fortran SHAPE(array) intrinsic
func (*Array[T]) Size ¶
Size returns the total number of elements in the array Corresponds to Fortran SIZE(array) intrinsic (no dimension argument)
func (*Array[T]) SizeDim ¶
SizeDim returns the size of a specific dimension (1-based dimension index) Corresponds to Fortran SIZE(array, dim) intrinsic
func (*Array[T]) SizeElement ¶
SizeElement implements Pointer interface.
func (*Array[T]) Upper ¶
Upper returns a copy of the upper bounds slice Corresponds to Fortran UBOUND(array) intrinsic (no dimension argument)
func (*Array[T]) UpperDim ¶
UpperDim returns the upper bound of a specific dimension (1-based dimension index) Corresponds to Fortran UBOUND(array, dim) intrinsic
func (*Array[T]) View ¶
View creates a view of the array with the given ranges applied to each dimension. The view shares the underlying data with the original array (no copy). Views can be nested: arr.View(...).View(...) works correctly.
Example:
arr := NewArray[int32](nil, 10, 5) view := arr.View(R(2, 4), R(1, 3)) // rows 2-4, cols 1-3 view.At(1, 1) // equivalent to arr.At(2, 1)
type CharacterArray ¶
type CharacterArray struct {
// contains filtered or unexported fields
}
CharacterArray represents a Fortran CHARACTER(LEN=n) variable with fixed length.
Design: Uses Go slice len/cap duality for metadata:
- cap(data): Fortran declared length (fixed, immutable)
- len(data): Actual data length (user extension, not part of Fortran semantics)
To match Fortran semantics, always use cap(data) for the effective length. Methods automatically handle space padding and truncation to cap(data).
Example:
// Fortran: CHARACTER(LEN=20) :: str
str := NewCharacterArray(20) // cap=20, len=0 initially
str.SetFromString("Hello") // Sets "Hello" + 15 spaces, len=5
s := str.String() // Returns full 20-char string with padding
func NewCharacterArray ¶
func NewCharacterArray(length int) (ch CharacterArray)
func NewCharacterArrayRef ¶
func NewCharacterArrayRef(length int) *CharacterArray
NewCharacterArrayRef allocates and returns a pointer to a CharacterArray. Used for initializing CHARACTER fields in derived type structs.
func (CharacterArray) AdjustL ¶
func (ch CharacterArray) AdjustL() CharacterArray
AdjustL returns a new CharacterArray with leading spaces moved to the end (ADJUSTL intrinsic) Corresponds to Fortran: ADJUSTL(str)
func (CharacterArray) AdjustR ¶
func (ch CharacterArray) AdjustR() CharacterArray
AdjustR returns a new CharacterArray with trailing spaces moved to the start (ADJUSTR intrinsic) Corresponds to Fortran: ADJUSTR(str)
func (*CharacterArray) Allocate ¶
func (ch *CharacterArray) Allocate(length int)
func (CharacterArray) At ¶
func (ch CharacterArray) At(i int) byte
func (CharacterArray) DataUnsafe ¶
func (ch CharacterArray) DataUnsafe() unsafe.Pointer
DataUnsafe implements Pointer interface.
func (CharacterArray) Index ¶
func (ch CharacterArray) Index(substring string) int
Index returns the 1-based starting position of substring in string (INDEX intrinsic) Returns 0 if not found Corresponds to Fortran: INDEX(str, substring)
func (CharacterArray) Len ¶
func (ch CharacterArray) Len() int
Len returns the declared length of the CHARACTER variable (LEN intrinsic) Corresponds to Fortran: LEN(str)
func (CharacterArray) LenBuffer ¶
func (ch CharacterArray) LenBuffer() int
LenBuffer returns length of flattened character buffer in characters (bytes). Implements [pointer] interface.
func (CharacterArray) LenTrim ¶
func (ch CharacterArray) LenTrim() int
LenTrim returns the length without trailing spaces (LEN_TRIM intrinsic) Corresponds to Fortran: LEN_TRIM(str)
func (CharacterArray) Set ¶
func (ch CharacterArray) Set(v byte, i int)
func (*CharacterArray) SetConcat ¶
func (ch *CharacterArray) SetConcat(toJoin ...CharacterArray)
func (*CharacterArray) SetConcatString ¶
func (ch *CharacterArray) SetConcatString(toJoin ...string)
func (*CharacterArray) SetDataUnsafe
deprecated
func (ch *CharacterArray) SetDataUnsafe(v unsafe.Pointer)
SetDataUnsafe implements Pointer interface.
Deprecated: Extremely unsafe.
func (*CharacterArray) SetFromString ¶
func (ch *CharacterArray) SetFromString(data string)
func (*CharacterArray) SetLenBufferUnsafe ¶
func (ch *CharacterArray) SetLenBufferUnsafe(length int)
SetLenBufferUnsafe sets the capacity of the character array.
func (*CharacterArray) SetSubstring ¶
func (ch *CharacterArray) SetSubstring(start, end int, data string)
SetSubstring sets a substring of the character array. Fortran: str(start:end) = 'value' Uses 1-based indexing.
func (CharacterArray) SizeElement ¶
func (ch CharacterArray) SizeElement() int
SizeElement returns the number of bytes per character. Always returns 1 in Go. Implements [pointer] interface.
func (CharacterArray) String ¶
func (ch CharacterArray) String() string
func (CharacterArray) StringLen ¶
func (ch CharacterArray) StringLen() string
func (CharacterArray) Substring ¶
func (ch CharacterArray) Substring(start, end int) string
Substring returns a copy of the string from start to end. Corresponds to Fortran: str(start:end)
func (CharacterArray) Trim ¶
func (ch CharacterArray) Trim() CharacterArray
Trim returns a new CharacterArray with trailing spaces removed (TRIM intrinsic) The result has the same declared length but different content Corresponds to Fortran: TRIM(str)
func (CharacterArray) View ¶
func (ch CharacterArray) View(start, end int) CharacterArray
View returns a view into the substring from start to end (1-based, inclusive)
type CommonBlock ¶
type CommonBlock struct {
// contains filtered or unexported fields
}
func NewCommonBlock ¶
func NewCommonBlock(name string, size int) CommonBlock
func (*CommonBlock) Reset ¶
func (cb *CommonBlock) Reset()
type Pointer ¶
type Pointer interface {
// DataUnsafe returns a pointer to the start of the backing buffer in memory.
DataUnsafe() unsafe.Pointer
// LenBuffer returns the length of the backing buffer in memory in elements.
// This is not in bytes. To obtain size of buffer in bytes do p.LenBuffer()*p.SizeElement().
LenBuffer() int
// SizeElement returns the size in bytes of the elements the pointer points to.
SizeElement() int
}
type PointerSetter ¶
type PointerSetter interface {
Pointer
// SetDataUnsafe is a super unsafe method that should be used extremely cautiously.
//
// Deprecated: Do not use this.
SetDataUnsafe(ptr unsafe.Pointer)
// SetLenBufferUnsafe sets the number of elements the pointer can access.
// Used by Equivalence to properly size destination pointers.
SetLenBufferUnsafe(length int)
}
func PointerOff ¶
func PointerOff(ptr PointerSetter, elemNum int) PointerSetter
PointerOff wraps a PointerSetter with an element offset for EQUIVALENCE. Used when equivalencing at a specific array element: EQUIVALENCE (A, B(5))
The elemNum parameter is a 1-based element number (Fortran indexing). Use Array.AtOffset(indices...) + 1 to convert multi-dimensional indices.
Example:
// EQUIVALENCE (A, MAT(2,3)) intrinsic.Equivalence(&a, intrinsic.PointerOff(mat, mat.AtOffset(2, 3) + 1))
type PointerTo ¶
type PointerTo[T any] struct { // contains filtered or unexported fields }
PointerTo represents a Fortran Cray-style pointer - a typed memory address.
Fortran POINTER Semantics ¶
In Fortran (particularly Cray Fortran and legacy code), POINTER statements declare integer variables that hold memory addresses:
POINTER (pointer_var, pointee)
The pointer_var is an INTEGER that stores an address (like a C pointer cast to intptr_t). The pointee is accessed through that address, similar to C dereferencing.
Type Safety ¶
Unlike Fortran's untyped integer addresses, Go's PointerTo[T] is type-safe:
- POINTER (iptr, iarr(1)) → PointerTo[int32] (for INTEGER arrays)
- POINTER (dptr, darr(1)) → PointerTo[float64] (for DOUBLE PRECISION arrays)
- POINTER (lptr, larr(1)) → PointerTo[bool] (for LOGICAL arrays)
Usage Patterns ¶
1. Dynamic allocation:
var ptr intrinsic.PointerTo[float64] ptr = intrinsic.MALLOC[float64](n * 8) x := ptr.At(i) // 1-based Fortran indexing
2. Subroutine parameters (arrays):
// Fortran: SUBROUTINE FOO(arr) // Go: func FOO(arr *intrinsic.Array[float64]) // Caller wraps: FOO(&myArray) or FOO(ptr.Array())
3. Shared memory (EQUIVALENCE-like):
var iview intrinsic.PointerTo[int32] var dview intrinsic.PointerTo[float64] // Both point to same memory for type punning
func MALLOC ¶
MALLOC allocates memory for Fortran MALLOC calls (typically a C library function). In transpiled code, actual memory allocation is handled by Go's garbage collector.
Example Fortran usage:
INTEGER :: ptr DOUBLE PRECISION :: arr(1) POINTER (ptr, arr(1)) ptr = MALLOC(1000 * 8) ! Allocate 1000 doubles
Transpiles to:
var ptr intrinsic.Pointer[float64] ptr = intrinsic.MALLOC[float64](1000 * 8) // Access via ptr.At(i) with Fortran 1-based indexing
func NewPointerFromSlice ¶
NewPointerFromSlice creates a Pointer from an existing Go slice. Used internally by MALLOC and for wrapping Go slices to pass to Fortran subroutines.
func PointerFrom ¶
PointerFrom creates a type-punned view of an existing Pointer, reinterpreting the same memory as a different element type. This is useful for Fortran EQUIVALENCE semantics where the same memory is accessed with different types.
Type Punning Rules ¶
When reinterpreting memory from source type S to destination type D:
- Total bytes remains constant: len(S) * sizeof(S) == len(D) * sizeof(D)
- If sizeof(S) > sizeof(D): destination has MORE elements (expansion) Example: float64[1] → int32[2] (8 bytes → 2×4 bytes)
- If sizeof(S) < sizeof(D): destination has FEWER elements (contraction) Example: int32[2] → float64[1] (2×4=8 bytes → 1×8 bytes)
- If sizeof(S) == sizeof(D): destination has SAME element count Example: int32[10] → float32[10] (both 4 bytes per element)
Alignment Requirements ¶
The function panics if the total byte size is not evenly divisible by the destination element size.
Example ¶
// View float64 memory as int32 elements floatPtr := MALLOC[float64](100 * 8) // 100 float64 elements intPtr := PointerFrom[int32](floatPtr) // 200 int32 elements (same memory) // Access the same 8 bytes as two different types floatPtr.Set(1, 3.14) lowBits := intPtr.At(1) // Low 32 bits of 3.14 highBits := intPtr.At(2) // High 32 bits of 3.14
Safety Warnings ¶
This function performs UNSAFE type punning:
- No guarantee that bit patterns are valid for the destination type
- Can violate Go's type safety and memory model
- Should only be used for Fortran interop where EQUIVALENCE is required
func Ptr ¶
Ptr creates a Pointer from a single element reference. Used for passing scalar variables by reference to OUT/INOUT parameters.
func UnallocatedPtr ¶
UnallocatedPtr declares a pointer with a length without assigning it a data portion. This is typical for ALLOCATABLE declarations.
func (PointerTo[T]) Array ¶
Array converts the Pointer to an Array for multi-dimensional operations. Creates a 1D array with Fortran indexing (lower bound 1, upper bound Len()).
Example:
ptr := intrinsic.MALLOC[float64](100 * 8) arr := ptr.Array(4,2,100) arr.At(3,1,89) // Access element at offset 3,1,89.
func (PointerTo[T]) At ¶
At accesses an element using Fortran 1-based indexing. This matches Fortran array semantics: arr(1) is the first element.
Example:
ptr := intrinsic.MALLOC[float64](10 * 8) ptr.At(1) // First element (Fortran: arr(1)) ptr.At(10) // Last element (Fortran: arr(10))
func (PointerTo[T]) AtPtr ¶
AtPtr returns a pointer to the idx'th element (1-indexed), matching Array's interface.
func (PointerTo[T]) Data ¶
func (p PointerTo[T]) Data() *T
Data returns the underlying Go pointer (*T) to the first element. Useful for passing to Go functions expecting native pointers.
func (PointerTo[T]) DataUnsafe ¶
func (PointerTo[T]) LenBuffer ¶
LenBuffer returns the number of elements the pointer can access. For MALLOC allocations, this is the allocated size divided by element size.
func (*PointerTo[T]) SetDataUnsafe
deprecated
func (*PointerTo[T]) SetLenBufferUnsafe ¶
SetLenBufferUnsafe sets the number of elements this pointer can access.
func (PointerTo[T]) SizeElement ¶
SizeElement returns size of individual elements the pointer corresponds to in bytes.
func (PointerTo[T]) Slice ¶
func (p PointerTo[T]) Slice() []T
Slice returns a Go slice view of the pointed-to memory. The slice uses 0-based indexing (Go convention). For Fortran 1-based indexing, use At() method instead.
func (PointerTo[T]) View ¶
View creates a sub-pointer viewing a range of the original allocation. Uses Fortran 1-based indexing: View(1, 10) returns elements 1-10 inclusive.
Example:
ptr := intrinsic.MALLOC[int32](100 * 4) sub := ptr.View(10, 20) // Elements 10-20 of original allocation sub.At(1) // First element of view (element 10 of original)