Translating Python to Fortran with pyccel

pyccel, a github project that I installed under Windows Subsystem for Linux, can translate python code with type hints to Fortran code. For example, pyccel fib.py for the Python code

from pyccel.decorators import types
@types('int', results='int')
def fibonacci(n):
    if n<=0:
        print("Incorrect input")
    # First Fibonacci number is 0
    elif n==1:
        return 0
    # Second Fibonacci number is 1
    elif n==2:
        return 1
    else:
        return fibonacci(n-1)+fibonacci(n-2)

print(fibonacci(9))

generates Fortran source (modulo blank lines)

module fib
use ISO_C_BINDING
implicit none
contains
!........................................
recursive function fibonacci(n) result(Out_0001)
implicit none
integer(C_LONG_LONG) :: Out_0001
integer(C_LONG_LONG), value :: n
if (n <= 0_C_LONG_LONG) then
  print *, '' // 'Incorrect input'
  !First Fibonacci number is 0
else if (n == 1_C_LONG_LONG) then
  Out_0001 = 0_C_LONG_LONG
  return
  !Second Fibonacci number is 1
else if (n == 2_C_LONG_LONG) then
  Out_0001 = 1_C_LONG_LONG
  return
else
  Out_0001 = fibonacci(n - 1_C_LONG_LONG) + fibonacci(n - 2_C_LONG_LONG)
  return
end if
end function fibonacci
!........................................
end module fib
!........................................
function fibonacci(n) bind(c) result(Out_0001)
  use fib, only: mod_fibonacci => fibonacci
  use ISO_C_BINDING
  implicit none
  integer(C_LONG_LONG), value :: n
  integer(C_LONG_LONG) :: Out_0001
  Out_0001 = mod_fibonacci(n)
end function fibonacci
!........................................
program prog_prog_fib
use fib, only: fibonacci
use ISO_C_BINDING
implicit none
print *, fibonacci(9_C_LONG_LONG)
end program prog_prog_fib

One can reduce C_LONG_LONG clutter with

use ISO_C_BINDING, only: i64 => C_LONG_LONG

and making some textual substitutions.

5 Likes

Great idea, I went to GitHub to give it a star and noticed I already gave it a star. :slight_smile:

I had this in mind for some time. One approach that I was thinking is to leverage NumBa, that can do type inference, and then convert it to LFortran’s ASR, which can then be converted to formatted Fortran source code. I know that NumBa does a lot of work there (that I was hoping to leverage), also regarding NumPy arrays. I assume pyccel does something similar. I should get in touch with them and brainstorm these ideas more, I think there is a lot of opportunity here.