What would it take to be able to write an I/O library (JSON, TOML, etc.) for Fortran that was as easy for a user to use as the built-in namelists (which, frankly, people shouldn’t be using). Currently, users of the libraries for modern file formats have to write a lot of verbose code, since there’s not currently any way for the generic library to know anything about the variables in their custom types. An example:
type :: mytype integer, dimension(:),allocatable :: ints character(len=10) :: name real,dimension(3) :: x end type mytype
Now, how do we write a variable of
type(mytype) to a file? Well, we have to do stuff like this:
type(json_file) :: json type(mytype) :: t ... call json%add('t.ints', t%ints) call json%add('t.name', t%name) call json%add('t.x', t%x) call json%print('file.txt')
So, it’s up to the user to type out all the variables names, etc. This is error prone and very cumbersome for very large nested data structures.
What if we could do this:
type(json_file) :: json type(mytype) :: t call json%print(t, 'file.txt')
Where the dummy argument to
class(*), and the author of the JSON library had available in Fortran to do all the introspection necessary to resolve all the variables in the type. This would have to include variable names, kinds, size, rank, etc. And we’d need the ability to traverse user-defined types.
Wouldn’t this be a good addition to Fortran? I think it would be incredibly useful, would make life a lot easier, and encourage users to move to modern file formats. It seems like some or all of the machinery is already in the compilers, since that’s basically what it is doing with namelists. I just want to be able to use that machinery to read/write other file formats just as easily.