Developer Tutorial

This is a tutorial for anybody who wants to either develop LFortran or build tools on top.

Introduction

LFortran is structured around two independent modules, AST and ASR, both of which are standalone (completely independent of the rest of LFortran) and users are encouraged to use them independently for other applications and build tools on top:

  • Abstract Syntax Tree (AST): Represents any Fortran source code, strictly based on syntax, no semantic is included. The AST module can convert itself to Fortran source code.

  • Abstract Semantic Representation (ASR): Represents a valid Fortran source code, all semantic is included. Invalid Fortran code is not allowed (an error will be given). The ASR module can convert itself to an AST.

Abstract Syntax Tree (AST)

Fortran source code can be parsed into an AST using the src_to_ast() function:

integer function f(a, b) result(r)
integer, intent(in) :: a, b
r = a + b
end function

We can pretty print it using the %%showast magic:

%%showast
integer function f(a, b) result(r)
integer, intent(in) :: a, b
r = a + b
end function
(TranslationUnit [(Function f [(a) (b)] [(AttrType TypeInteger [] () None)] r () [] [] [] [(Declaration (AttrType TypeInteger [] () None) [(AttrIntent In)] [(a [] [] () None ()) (b [] [] () None ())])] [(= 0 r (+ a b))] [])])

We can convert AST to Fortran source code using %%showfmt:

%%showfmt
integer function f(a, b) result(r)
integer, intent(in) :: a, b
r = a + b
end function
integer function f(a, b) result(r)
integer, intent(in) :: a, b
r = (a) + (b)
end function f

All AST nodes and their arguments are described in AST.asdl.

Abstract Semantic Representation (ASR)

We can pretty print using the %%showasr magic:

%%showasr
integer function f(a, b) result(r)
integer, intent(in) :: a, b
r = a + b
end function
(TranslationUnit (SymbolTable 1 {f: (Function (SymbolTable 3 {a: (Variable 3 a In () () Default (Integer 4 []) Source Public Required), b: (Variable 3 b In () () Default (Integer 4 []) Source Public Required), r: (Variable 3 r ReturnVar () () Default (Integer 4 []) Source Public Required)}) f [(Var 3 a) (Var 3 b)] [(= (Var 3 r) (BinOp (Var 3 a) Add (Var 3 b) (Integer 4 []) ()))] (Var 3 r) Source Public Implementation)}) [])

All ASR nodes and their arguments are described in ASR.asdl.