# Binding Generation

This documents how the C interface functions are generated.

## Rationale

We used to manually maintain individual source files for each mpi-level
function. For example, `src/mpi/pt2pt/send.c` for `MPI_Send`. Starting with
[PR #4846](https://github.com/pmodels/mpich/pull/4846),
we are now generating all the code with a python script and a set of
configuration files.

The interface is generated by `python maint/gen_binding_c.py`, executed
inside of `autogen.sh`. It loads the master configuration file, then loads, per
category, custom configuration files. One file is generated for each configured
function in the `src/binding/c` folder. Additionally it generates the
following three files:

- `src/binding/c/Makefile.mk`
- `src/binding/c/errnames.txt`
- `src/include/mpir_impl.h`

## Master API config file

The master configuration file, `maint/mpi_standards_api.txt` is a direct
transcription from the mpi-standard repository. It contains entries as
follows:

```
MPI_Send:
    buf: BUFFER, constant=True, [initial address of send buffer]
    count: POLYXFER_NUM_ELEM_NNI, [number of elements in send buffer]
    datatype: DATATYPE, [datatype of each send buffer element]
    dest: RANK, [rank of destination]
    tag: TAG, [message tag]
    comm: COMMUNICATOR
```

Each entry will have a function name and a list of parameters. Each parameter
starts with the variable name, followed by a "kind", then a set of optional 
attributes, and finally a description inside the square brackets.

## Language specific kind mapping

The mapping from parameter "kind" to language specific type is listed in
`maint/api_mapping.txt` with a simple format:

```
LIS_KIND_MAP:
    ACCESS_MODE: integer
    ...
BASE_C_KIND_MAP:
    ACCESS_MODE: int
    ...
SMALL_C_KIND_MAP:
    .base: BASE_C_KIND_MAP
    POLYDISPLACEMENT: int
    ...
BIG_C_KIND_MAP:
    .base: BASE_C_KIND_MAP
    POLYDISPLACEMENT: MPI_Aint
...
```

Each entry contains a map type heading followed by a set of `kind: type`
listings. `BASE_C_KIND_MAP` is only used to avoid duplication between `SMALL`
and `BIG` versions.

Typically we should use the exact mapping from the mpi standard, meaning
`maint/api_mapping.txt` should be kept in-sync with the upstream branch. But
sometimes, e.g. `MPIX` functions, we may need to define our own kind mappings.
We do that in `src/binding/custom_mapping.txt`.


## Custom API config files

For any function to be generated, it has to be listed in one of the custom
configuration files in the `src/binding/c` folder, such as
`src/binding/c/pt2pt_api.txt`. The filename has to fit the `dir_api.txt`
format. The root name designates the subfolder where the code files will be
generated in. For example, all functions listed in
`src/binding/c/pt2pt_api.txt` will get generated in `src/binding/c/pt2pt/`.

The custom configuration file follows the same format as the master
configuration file plus a few additions. Their formatting as follows:

```
MPI_Example:
    .desc: a short description
/*
    Notes:
    Here we can supply custom man page notes explaining the semantics of the
    function.
*/
/*
    Multiple such "comment" blocks are allowed. The first block adds notes to
    the top of the man page (after the generated parameter info). The rest of
    the blocks are concatenated a follows the generated notes.

    Typical functions will all include .ThreadSafe and .Fortran notes, unless
    one or both of them are excluded by .skip directives.

    .N ExampleNote
    Any text is allowed. Refer to the sowing package manual.
*/
{ -- error_check -- list_of, parameters, that, are, checked
    /* custom error checking code when automatically generated validation is
     * insufficient */
    if (list_of < 0) {
        mpi_errno = ...;
        goto fn_fail;
    }
}
{ -- early_return --
    if (!param1) {
        goto fn_exit;
    }
}
{
    /* without the -- mark, this is the "body of routine" */
    mpi_errno = my_custom_code(...);
    if (mpi_errno) {
        goto fn_fail;
    }
}
```

The above example customizes `MPI_Example` with the following:
- A short description
- Extra man page notes
- Custom error checking code
- `early_return` code
- Custom body of routine

The customizations are place holders to allow flexibility when dealing with
arbitrary complex code that is too complex to deal with within the python
script. However, for most functions, most of the custom parts can be omitted.
For example, the following:

```
MPI_Sendrecv:
    .desc: Sends and receives a message
```

is sufficient to generate `src/binding/c/pt2pt/sendrecv.c` with:
- A default man page
- Default validations
- Default body of routine which simply calls `MPIR_Sendrecv_impl`

When in doubt, double check the generated output and add customizations when
necessary.

For `MPIX` functions, we'll need to supply our own parameter information since
they will be missing from the standard master configuration file. Simply list
the parameters in the custom files. The parameters all start with 

```
param_name: ...
```

while the directives all start with a `.`,

```
.desc: ...
```

Supported directives include:
- `.desc` - A short description
- `.skip` - A list of items that should skip auto-generations:
    - `ThreadSafe, Fortran` - These are standard notes
    - `validate-INDEX` - The `INDEX` kind should be skipped
    - `validate-ANY` - Skip all validations
    - `initcheck` - The function should skip `MPIR_ERRTEST_INITIALIZED_ORDIE`
    - `global_cs` - The function should skip `MPID_THREAD_CS_ENTER/EXIT`

- `.extra` - A list extra items that should be generated:
    - `SignalSafe, NotThreadSafe, collops` - Extra notes 
- `.error` - A list extra error code that should listed in the document.
             The error codes associated with generated validation code are
             always documented automatically.

It is easy to extend with extra special directives. Simply specify it in the
configuration files with a `.name`, then implement it in
`maint/local_python/binding_c.py`. The difficult part is to keep it documented.
