Code Monkey home page Code Monkey logo

sphinx-fortran's Introduction

Sphinx-Fortran extensions

image

image

image

Purpose

This package provides two Sphinx (http://sphinx.pocoo.org/) extensions to the Fortran (90) language:

  • sphinxfortran.fortran_domain: Sphinx domain for fortran.
  • sphinxfortran.fortran_autodoc: Auto-documenting fortran code.

License

This package has the same license as VACUMM (http://www.ifremer.fr/vacumm) from which it originates: CeciLL-A (http://www.cecill.info/licences/Licence_CeCILL_V2.1-en.html), which is compatible with the GPL.

Prerequisites

The sphinx and numpy packages.

Installation

With pip:

pip install sphinx-fortran

With conda:

conda install -c vacumm -c conda-forge sphinx-fortran

From sources:

git clone https://github.com/VACUMM/sphinx-fortran.git
cd sphinx-fortran
python setup.py install

Quick start

  1. Add this extension to your sphinx conf.py.
  2. List you fortran source files in the variable fortran_src of your conf.py.
  3. Generate their documentation in rst files using directives like:

    .. f:automodule:: mymodule

Bugs and requests

Please go to this GitHub page: https://github.com/VACUMM/sphinx-fortran/issues

Authors

Stephane Raynaud (stephane.raynaud(at)gmail.com)

Thanks: Thomas Gastine and other pull request contributors.

Documentation

Website: http://sphinx-fortran.readthedocs.org

sphinx-fortran's People

Contributors

akohlmey avatar cfbastarz avatar dcaliste avatar dvuckovic avatar gastineau avatar hsorby avatar ianhbell avatar jdillard avatar jhogg41 avatar loicreynier avatar rhdtownsend avatar rogierfloors avatar sradanov avatar stefraynaud avatar warrickball avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sphinx-fortran's Issues

Type-bound procedures

How can I document a type-bound procedure with sphinx-fortran? Suppose I had the code

module mymod

type foo
real :: a
contains
subroutine do_stuff
end type foo

contains

subroutine do_stuff(self)
class(foo) :: self
print *,self%a
end subroutine do_stuff

end module mymod

...then what syntax do I need to use with sphinx-fortran to indicate that the do_stuff subroutine is bound to the foo type?

Fatal error when documenting multiple types in the same file

In case Fortran source has two or more types declared in the same file, like so:

module test
    implicit none

    type foo
        integer :: foo
    end type foo

    type bar
        integer :: bar
    end type bar
end module test

Python will throw a fatal error during generation of the documentation:

Exception occurred:
  File "/path/to/sphinxfortran/fortran_autodoc.py", line 1246, in format_quickaccess
    tlist = sorted(self.get_blocklist('types', module))
TypeError: '<' not supported between instances of 'dict' and 'dict'

The issue stems from trying to sort dictionaries using the sorted() function, which is apparently unsupported. This occurs in format_quickaccess method, so it's probably better to simply remove the call to sorted(), and leave this job to get_blocklist method, where sort parameter defaults to True anyway.

Fix will be provided in a PR shortly, for your consideration.

BTW, it would be very cool to be able to omit the autogenerated Quick access section from the output, possibly by introducing additional option to f:autosrcfile directive, for example :no_quick_access:. I can probably try to prepare this, but I wanted first to check if you accept these kind of enhancements via PRs and if the project is still alive?

Thanks for this great plugin, it's quite unique :)

fortran_domain doesn't handle arguments declared as "double precision" correctly.

An argument of a subroutine declared as
DOUBLE PRECISION,DIMENSION(:,:),INTENT(IN):: MYVAR
appears as

  • precision [double]
    in the documentation, instead of something like
  • myvar(,)[double precision, in]
    I suppose something is going wrong around this line:
    re_fieldname_match = re.compile( r'(?P<type>\b\w+\b(?P<kind>\s*\(.*\))?)?\s*(?P<name>\b\w+\b)\s*(?P<shape>\(.*\))?\s*(?P<sattrs>\[.+\])?').match
    since everything seems to be fine until the scan_fieldarg method of the FortranDocFieldTransformer class
    where
    print(fieldname)
    gives
    double precision myvar(,) [in]
    but the method returns
    precision None double None
    instead of
    myvar (,) double precision in

optional argument not detected as optional for autodoc

Two different things:

  • these 2 directives don't give the same result for the subroutine toto
    .. f:autosrcfile:: toto.f90
    .. f:autosubroutine:: toto
    The first one detects correctly the optional argument, the other not.

  • the .. f:autosrcfile:: command doesn't give an "optional" section in the result for optional argument
    test.pdf

fix warning about fortran_src raised at build

Hi,

I noticed the following warning at build:
WARNING: The config value fortran_src' has type list', defaults to `str'.

Please, change the line (setup function in fortran_autodoc module):
app.add_config_value('fortran_src', '.', False)
to:
app.add_config_value('fortran_src', ['.'], False)

.. note:: I cannot commit/push - sorry.

Thanks in advance.
Regards.

waning about a 4 column based index found

Hi,

I use the following statement for the fortran documentation:

 .. f:subroutine:: f90calceph_getversion_str (version) 

 .. f:subroutine:: calceph_getversion_str (version) BIND(C)

I receive the following warnings.

calceph.misc.rst:15: WARNING: 4 column based index found. It might be a bug of extensions you use: [('single', u'calceph_getversion_str() (fortran subroutine)', u'f//calceph_getversion_str', u'f//calceph_getversion_str')]
calceph.misc.rst:21: WARNING: 4 column based index found. It might be a bug of extensions you use: [('single', u'f90calceph_getversion_str() (fortran subroutine)', u'f//f90calceph_getversion_str', u'f//f90calceph_getversion_str')]

The documentation looks fine but I receive many similar warnings for my fortran documentation.

How can I remove these warnings ?

Best regards,

Error when parsing source with abstract interface

When I try to use fortran_autodoc on a source file that uses an abstract interface, sphinx crashes with

Extension error:
Handler <function fortran_parse at 0x112981d30> for event 'builder-inited' threw an exception (exception: crackline: groupcounter(=0) is nonpositive. Check the blocks.)
make: *** [html] Error 2

Example Fortran source file:

module test
  abstract interface
  end interface
end module test

autodoc feature mixes up descriptions

I'm currently working on some instructional material on using Sphinx for Fortran projects and I noticed
that the autodoc feature mixes up the descriptions of parameters.

E.g. when I have the following Fortran code:

subroutine calc_distance (np, nd, pos, i, j, rij, d, d2)
!
!  Calculate Distance vector, scalar distance and trucated distance
!  between atoms i and j.
!  The distance is truncated at pi/2
!
    implicit none
    integer(kind=4),intent(in) :: np                ! number of particles
    integer(kind=4),intent(in) :: nd                ! number of dimensions
    real(kind=8),intent(in),dimension(nd,np) :: pos ! positions
    integer(kind=4),intent(in) :: i                 ! index particle I
    integer(kind=4),intent(in) :: j                 ! index particle J
    real(kind=8),intent(out),dimension(nd) :: rij   ! distance vector
    real(kind=8),intent(out) :: d                   ! distance
    real(kind=8),intent(out) :: d2                  ! trucated distance

    real ( kind = 8 ), parameter :: PI2 = 3.141592653589793D+00 / 2.0D+00

    rij(1:nd) = pos(1:nd,i) - pos(1:nd,j)

    d = sqrt ( sum ( rij(1:nd)**2 ) )

    !  Truncate the distance:
    d2 = min ( d, PI2 )
end subroutine calc_distance

you can see here that the description of nd is just gone and the one of rij shows up next to j.
Code is at https://github.com/ostueker/Example_Fortran (file src/sub_calc_distance.f90).

Any idea if maybe I am doing something wrong?

DOC comments from `recursive subroutine`s are not read

I was just playing around with sphinx-python (version 1.0.1) and noticed that the header and inline comments are not extracted when the recursive keyword precedes a subroutine.

Example:

With this Fortran Code:

recursive SUBROUTINE add_tree_node(current, value)
! Add new tree_node into the tree.

    TYPE (tree_node), pointer :: current ! pointer to current tree
    REAL :: value                        ! value of new tree node

    IF (.NOT.associated(current)) THEN
        allocate(current)
        current%value = value
    ELSEIF (value < current%value) THEN
        CALL add_tree_node(current%left, value)
    ELSE
        CALL add_tree_node(current%right, value)
    END IF
END SUBROUTINE add_tree_node

and sphinx-fortran directive: .. f:autosrcfile:: tree_sort_module.f90

I get this after generating with make text:

subroutine  tree_sort_module/add_tree_node(current, value)

   Parameters:
      * **current*** [**tree_node**,**pointer**]*

      * **value*** [**real**]*

   Called from:
      "tree_sort"

Once I remove the recursive keyword, the comments get properly included in the docs:

subroutine  tree_sort_module/add_tree_node(current, value)

   Add new tree_node into the tree.

   Parameters:
      * **current*** [**tree_node**,**pointer**]* :: pointer to
        current tree

      * **value*** [**real**]* :: value of new tree node

   Called from:
      "add_tree_node()", "tree_sort"

   Call to:
      "add_tree_node()"

Error for autodoc on empty module

Running sphinx with fortran_autodoc on an empty module fails at

parsing fortran sources...{}

Exception occurred:
  File ".../sphinx-fortran/sphinxfortran/fortran_autodoc.py", line 347, in scan
    m = block['vardescsearch'](line)
KeyError: 'vardescsearch'

Quick fix: add a check if 'vardescsearch' in block.keys(): before line 347 in fortran_autodoc.py. A better solution would be to unify the initialization of block for all cases.

[Meta] Gathering interest in a "Framework :: Sphinx :: Domain" PyPi classifier

I'm trying to get a Framework :: Sphinx :: Domain PyPi classifier approved to help with the Sphinx docs as well as keep the ecosystem more organize and I need to demonstrate interest by having 10 or more project maintainers submit comments about their desire to use the new classifier.

If the maintainer of this project thinks a Framework :: Sphinx :: Domain would be useful for helping people find the domain as well as help the greater Sphinx ecosystem, please leave a comment on sphinx-doc/sphinx#11562 expressing interest in using the classifier with a link to the package that you maintain to help with the approval process.

Once it gets approved I can come back and submit a PR to add it to the package metadata.

Thanks!

In-line comments not working

Hi everyone,

I am trying to use sphinx-fortran to autodoc my fortran code. I am able to get it autodoc comments under programs, modules, functions, subroutines and types but I am unable to get the in-line comments for variables into the documentation. For eg.,

integer, parameter :: dp=kind(1.0d0) ! real*8 type

doesn't produce the comment "real*8 type" under the variable "dp" in the documentation. Am I doing something wrong? Or is this a bug with sphinx-fortran extension?

Thanks,
-Navaneeth

Generic procedures detection

Generic procedures are not detected as functions/subroutines, the same for operator overloading. Any chance it will be implemented? Or maybe I'm doing something wrong?

example:

    module class_instrumentalization
        ...
        private

        interface run
                module procedure run_list, run_obj 
        end interface
    
    public :: run
    ...
    .. automodule:: extensionmodule
       :members:
       :undoc-members:
       :show-inheritance:

current result:

image

Modules are found by autodoc only if written in lower case in the .rst, even if they are upper case in the code

Module names that are written in upper case in the fortran code are stored in lower case in self.modules of the F90toRst class.
This means that the module name has to be given in lower case to .. f:automodule:: in order to get found by the format_module method. Passing the module name as it occurs in the fortran code to . f:automodule:: makes the format_module method raise an F90toRstException('Unknown module'), which is quite counter intuitive.

Autodoc inconsistency

In a module i have

    ...
    INTEGER, PARAMETER :: ps = 6 !Number of digits of a single precision float
    INTEGER, PARAMETER :: rs = 37 !Exponent range of a single precision float
    INTEGER, PARAMETER :: pd = 12 !Number of digits of a double precision float
    INTEGER, PARAMETER :: rd = 307 !Exponent range of a doble precision float

    INTEGER, PARAMETER :: sp = selected_real_kind(ps, rs) !Single precision float kind
    INTEGER, PARAMETER :: dp = selected_real_kind(pd, rd) !Double precision float kind
    INTEGER, PARAMETER :: qp & !Quadruple precision float kind
    & = selected_real_kind(32)
    INTEGER, PARAMETER :: wp & !Working precision float kind: ``dp``
    & = dp
#ifdef __MIXED_PRECISION
    INTEGER, PARAMETER :: vp & !Mixed precision float kind: ``sp`` or ``dp`` (at compile time)
    & = sp !Single precision float kind
#else
    INTEGER, PARAMETER :: vp & !Mixed precision float kind: ``sp`` or ``dp`` (at compile time)
    & = dp !Double precision float kind
#endif

    INTEGER, PARAMETER :: pi1 = 2 !Number of digits of a 1-byte integer
    INTEGER, PARAMETER :: pi2 = 4 !Number of digits of a 2-byte integer
    INTEGER, PARAMETER :: pi4 = 9 !Number of digits of a 4-byte integer
    INTEGER, PARAMETER :: pi8 = 14 !Number of digits of a 8-byte integer

    INTEGER, PARAMETER :: i1 & !1-byte integer kind
    & = selected_int_kind(pi1)
    INTEGER, PARAMETER :: i2 & !2-byte integer kind
    & = selected_int_kind(pi2)
    INTEGER, PARAMETER :: i4 & !4-byte integer kind
    & = selected_int_kind(pi4)
    INTEGER, PARAMETER :: i8 & !8-byte integer kind
    & = selected_int_kind(pi8)

    INTEGER, PARAMETER :: wi & !Working integer kind: ``i4``
    & = i4 !4-byte integer kind

    PUBLIC :: sp, dp, wp, vp, i1, i2, i4, i8
    ...

where I needed to use the strategy of dividing all the declarations of parameters with line continuation so that the docstring for one parameter does not end up being the description of the parameter after the equal sign.

However, in the generated documentation the "default" values for vp, wi and wp result to be 4, 4 and 8, respectively. Why is that? Why not simply dp, i4 and dp.

I have solved an error "KeyError: 'vardescsearch'".

Dear developers,

I encountered a error when I was making a document:

File "~/.pyenv/versions/anaconda3-2019.10/lib/python3.7/site-packages/sphinxfortran/fortran_autodoc.py", line 348, in scan
m = block'vardescsearch'
KeyError: 'vardescsearch'

I have solved the error by changing the following lines in fortran_autodoc.py:

line 348
if line.strip().startswith('!'):
continue
m = block'vardescsearch'
if m:
block['vars'][m.group('varname').lower()]['desc'] = m.group('vardesc')

to
if line.strip().startswith('!'):
continue
if 'vardescsearch' in block:
m = block'vardescsearch'
if m:
block['vars'][m.group('varname').lower()]['desc'] = m.group('vardesc')

Also, in the user manual, I wonder

.. f:autovariable:: modname

instead,

.. f:automodule:: modname

Best regards.

cannot import extention

PC configuration:
OS ubuntu 16.04

I read some blogs about it includes:
google groups(https://groups.google.com/forum/#!topic/sphinx-users/gQfMxDsXQo0)
read the file(https://sphinx-fortran.readthedocs.io/en/latest/)
and related GitHub
I found it hasn't update for a while, is it still compatible with the new version's sphinx?
It is because I cannot import extensions like sphinxfortran.fortran_domain, sphinxfortran.fortran_autodoc in conf.py

the error message is:
Running Sphinx v2.1.2

Extension error:
Could not import extension sphinxfortran.fortran_autodoc (exception: cannot import name 'Directive' from 'sphinx.directives' (unknown location))

Running Sphinx v2.1.2

Extension error:
Could not import extension sphinxfortran.fortran_domain (exception: cannot import name 'Directive' from 'sphinx.util.compat' (/home/tianli/anaconda3/lib/python3.7/site-packages/sphinx/util/compat.py))

Mocking numpy out to build the doc on RTD

Hi,
I need to mock out numpy to prevent compilation of fortran code, when building my doc by sphinx on ReadTheDocs.

I'm afraid this becomes an issue when this sphinx extension is used, because the extension itself calls f2py (part of numpy).

I'd like to have a return from main developers, if possible.
Many thanks in advance for the kind support.

fortran_parse error in the fortran_autodoc module for a basic example

Hi,

I am trying to set a minimal working example for fortran_autodoc. make html works when no files are added to the project. If I add a simple file such as:

module constants  
implicit none 

   real, parameter :: pi = 3.1415926536  
   real, parameter :: e = 2.7182818285 
   
contains      
   subroutine show_consts()          
      print*, "Pi = ", pi          
      print*,  "e = ", e     
   end subroutine show_consts 
   
end module constants 

The file name is test.f90 and it is picked up by conf.py. I get the following error:
Handler <function fortran_parse at 0x00000166EC1CFCA8> for event 'builder-inited' threw an exception (exception: 'C')

I tried with the test files in the repository as well but I always get the same problem. This is independent to referring to them in index.rst. I imagine it is something to do with my setup, but I didn't find the traceback helpful at all. Perhaps somebody has come across it before?

Many thanks for your help.

Missing dependencies on 'six' and 'numpy'

sphinx_fortran uses the packages 'six' and 'numpy' but they are not automatically installed by pip when sphinx-fortran is installed. Attempting to use sphinx_fortran without first manually installing 'six' produces the following error:

Extension error:
Could not import extension sphinxfortran.fortran_domain (exception: No module named 'six')

Similarly, if numpy is missing:

Extension error:
Could not import extension sphinxfortran.fortran_autodoc (exception: No module named 'numpy')

TypeError in sort in "fortran_autodoc.py"

When trying to build documentation, the following line raises an Exception:

tlist = sorted(self.get_blocklist('types', module))

... due to trying to sort incompatible types (dictionaries in this case). I have attached the full "Read The Docs" build log, including Traceback:

More complete example of Fortran auto-documentation

Hi, great project!

Is it possible to have a more complete example on the type and format of the information that can be added to the source code, and that is used by Sphinx-Fortran to build the auto-documentation? i.e. something expanding the information contained in the "Optimize the process" section of this page?

Subroutine description when using continuation sign is not found

Hello sphinx-fortran team,
this is a great and very helpful project!
It seems to me that a subroutine description is not properly read when using autosubroutine in case of a continuation line. The documentation says the description comment is used "if they start immediately after the declaration line." If I break the declaration line and use "&" then the description is not used any more (probably because it is not directly following "subroutine").
for readability I would prefer to break the parameters over multiple lines.
Any chances to fix that easily?
best,
rochus

Autodocumentation of parameters

I have a section in a module of my Fortran code where

    ...
    INTEGER, PARAMETER :: ps = 6 !Number of digits of a single precision float
    INTEGER, PARAMETER :: rs = 37 !Exponent range of a single precision float
    INTEGER, PARAMETER :: pd = 12 !Number of digits of a double precision float
    INTEGER, PARAMETER :: rd = 307 !Exponent range of a doble precision float

    INTEGER, PARAMETER :: sp = selected_real_kind(ps, rs) !Single precision float kind
    INTEGER, PARAMETER :: dp = selected_real_kind(pd, rd) !Double precision float kind
    INTEGER, PARAMETER :: qp = selected_real_kind(32) !Quadruple precision float kind
    INTEGER, PARAMETER :: wp = dp !Working precision float kind
    ...

When the autodocumentation is generated for this module, the description for qp is missing and dp is described as "Working precision float kind" as if the comment for wp corresponded to dp. Is there a workaround other than writing

    ...
    INTEGER, PARAMETER :: ps = 6 !Number of digits of a single precision float
    INTEGER, PARAMETER :: rs = 37 !Exponent range of a single precision float
    INTEGER, PARAMETER :: pd = 12 !Number of digits of a double precision float
    INTEGER, PARAMETER :: rd = 307 !Exponent range of a doble precision float

    INTEGER, PARAMETER :: sp = selected_real_kind(ps, rs) !Single precision float kind
    INTEGER, PARAMETER :: dp = selected_real_kind(pd, rd) !Double precision float kind
    INTEGER, PARAMETER :: qp & !Quadruple precision float kind
    & = selected_real_kind(32)
    INTEGER, PARAMETER :: wp & !Working precision float kind: ``dp``
    & = dp
    ...

Fix FortranAutoSrcfileDirective

Hi,

please change the following lines of class FortranAutoSrcfileDirective(Directive), method run

if objtype:
    objtype = objtype.split(' ,')

with:

if objtype:
    objtype = objtype.split(',')
    objtype = [o.strip() for o in objtype]

There's a white trailing space in the version from the repo.
I cannot pull my changes, sorry.
Thanks in advance for your kind understanding.
Regards,

exception: 'fromsky' with abstract interface

Hi,

I encounter the following exception
Extension error: Handler <function fortran_parse at 0x7f35d1032170> for event 'builder-inited' threw an exception (exception: 'fromsky')
when I try to parse a module with:
.. f:automodule:: psfun_d_serial_mod
if the module contains an abstract interface:

abstract interface
        function func (x,k)
            use psb_base_mod
            implicit none
            real(psb_dpk_)                          :: func
            real(psb_dpk_), intent (in)             :: x   
            integer(psb_ipk_), intent(in), optional :: k 
        end function func
 end interface

If the previous code is commented, then the generation of the documentation works as intended.

I am using Sphinx version 3.2.1 and Sphinx_Fortran 1.1.1

Thank you in advance!

error processing files on windows NT system

Hello,

when using sphinx-fortran on windows systems, I noticed that the function get_src in module fortran_autodoc.py was wrongly processing filenames with full path stored in block['from']. On win system, a letter is generally used to identify the storage drive, having a column ':' after this letter. The column is used to get the parent block, as in numpy.f2py.crackfortran.py docstring:

B['from'] --- string showing the 'parents' of the current block

This prevents correct execution of sphinx-fortran on win10 for instance.

I suggest the following new version of the function that fixed the issue in my case :

    def get_src(self, block):
        """Get the source lines of the file including this block"""
        srcfile = block['from']
        if os.name != 'nt' or not os.path.isfile(block['from']):
            srcfile = block['from'].split(':')[0]
        return self.src[srcfile]

Thanks for your kind attention.
Regards,
P.I.: I cannot use a pull request.

Let the comment header as raw text or literal block

Hello,

Is it possible to leave the comment header of fortran blocks as raw text without interpreting it as ReST please ?
A possible fix is adding the following lines,

if len(block['desc']) and raw_desc > 0:
    block['desc'] = ["! .. code-block::\n"] + block['desc']

right after,

# Comment
 block['desc'] = self.get_comment(subsrc, aslist=True)

in the function scan_container of file fortran_autodoc.f90. The new variable raw_desc should be True if such option was selected when processing the fortran blocks.

Or perhaps, is there another way of achiving this behavior?

Thanks in advance for your kind attention.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.