that block should be repeated. If the word in the repeat rule
needs a comma, leftarrow, or rightarrow, then prepend it with a
backslash ' \'. If a word in the repeat rule matches ' \\<index>' then
it will be replaced with the <index>-th word in the same repeat
specification. There are two forms for the repeat rule: named and
short.

Named repeat rule
^^^^^^^^^^^^^^^^^

A named repeat rule is useful when the same set of repeats must be
used several times in a block. It is specified using <rule1=item1,
item2, item3,..., itemN>, where N is the number of times the block
should be repeated. On each repeat of the block, the entire
expression, '<...>' will be replaced first with item1, and then with
item2, and so forth until N repeats are accomplished. Once a named
repeat specification has been introduced, the same repeat rule may be
used **in the current block** by referring only to the name
(i.e. <rule1>).


Short repeat rule
^^^^^^^^^^^^^^^^^

A short repeat rule looks like <item1, item2, item3, ..., itemN>. The
rule specifies that the entire expression, '<...>' should be replaced
first with item1, and then with item2, and so forth until N repeats
are accomplished.


Pre-defined names
^^^^^^^^^^^^^^^^^

The following predefined named repeat rules are available:

- <prefix=s,d,c,z>

- <_c=s,d,c,z>

- <_t=real, double precision, complex, double complex>

- <ftype=real, double precision, complex, double complex>

- <ctype=float, double, complex_float, complex_double>

- <ftypereal=float, double precision, \\0, \\1>

- <ctypereal=float, double, \\0, \\1>


Other files
------------

Non-Fortran files use a separate syntax for defining template blocks
that should be repeated using a variable expansion similar to the
named repeat rules of the Fortran-specific repeats.

NumPy Distutils preprocesses C source files (extension: :file:`.c.src`) written
in a custom templating language to generate C code. The ``@`` symbol is
used to wrap macro-style variables to empower a string substitution mechanism
that might describe (for instance) a set of data types.

The template language blocks are delimited by ``/**begin repeat``
and ``/**end repeat**/`` lines, which may also be nested using
consecutively numbered delimiting lines such as ``/**begin repeat1``
and ``/**end repeat1**/``:

1. ``/**begin repeat`` on a line by itself marks the beginning of
   a segment that should be repeated.

2. Named variable expansions are defined using ``#name=item1, item2, item3,
   ..., itemN#`` and placed on successive lines. These variables are
   replaced in each repeat block with corresponding word. All named
   variables in the same repeat block must define the same number of
   words.

3. In specifying the repeat rule for a named variable, ``item*N`` is short-
   hand for ``item, item, ..., item`` repeated N times. In addition,
   parenthesis in combination with ``*N`` can be used for grouping several
   items that should be repeated. Thus, ``#name=(item1, item2)*4#`` is
   equivalent to ``#name=item1, item2, item1, item2, item1, item2, item1,
   item2#``.

4. ``*/`` on a line by itself marks the end of the variable expansion
   naming. The next line is the first line that will be repeated using
   the named rules.

5. Inside the block to be repeated, the variables that should be expanded
   are specified as ``@name@``.

6. ``/**end repeat**/`` on a line by itself marks the previous line
   as the last line of the block to be repeated.

7. A loop in the NumPy C source code may have a ``@TYPE@`` variable, targeted
   for string substitution, which is preprocessed to a number of otherwise
   identical loops with several strings such as ``INT``, ``LONG``, ``UINT``,
   ``ULONG``. The ``@TYPE@`` style syntax thus reduces code duplication and
   maintenance burden by mimicking languages that have generic type support.

The above rules may be clearer in the following template source example:

.. code-block:: NumPyC
   :linenos:
   :emphasize-lines: 3, 13, 29, 31

    /* TIMEDELTA to non-float types */

    /**begin repeat
     *
     * #TOTYPE = BYTE, UBYTE, SHORT, USHORT, INT, UINT, LONG, ULONG,
     *           LONGLONG, ULONGLONG, DATETIME,
     *           TIMEDELTA#
     * #totype = npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint,
     *           npy_long, npy_ulong, npy_longlong, npy_ulonglong,
     *           npy_datetime, npy_timedelta#
     */

    /**begin repeat1
     *
     * #FROMTYPE = TIMEDELTA#
     * #fromtype = npy_timedelta#
     */
    static void
    @FROMTYPE@_to_@TOTYPE@(void *input, void *output, npy_intp n,
            void *NPY_UNUSED(aip), void *NPY_UNUSED(aop))
    {
        const @fromtype@ *ip = input;
        @totype@ *op = output;

        while (n--) {
            *op++ = (@totype@)*ip++;
        }
    }
    /**end repeat1**/

    /**end repeat**/

The preprocessing of generically-typed C source files (whether in NumPy
proper or in any third party package using NumPy Distutils) is performed
by `conv_template.py`_.
The type-specific C files generated (extension: ``.c``)
by these modules during the build process are ready to be compiled. This
form of generic typing is also supported for C header files (preprocessed
to produce ``.h`` files).

.. _conv_template.py: https://github.com/numpy/numpy/blob/main/numpy/distutils/conv_template.py

Useful functions in ``numpy.distutils.misc_util``
-------------------------------------------------

+ ``get_numpy_include_dirs()`` --- return a list of NumPy base
  include directories. NumPy base include directories contain
  header files such as ``numpy/arrayobject.h``, ``numpy/funcobject.h``
  etc. For installed NumPy the returned list has length 1
  but when building NumPy the list may contain more directories,
  for example, a path to ``config.h`` file that
  ``numpy/base/setup.py`` file generates and is used by ``numpy``
  header files.

+ ``append_path(prefix,path)`` --- smart append ``path`` to ``prefix``.

+ ``gpaths(paths, local_path='')`` --- apply glob to paths and prepend
  ``local_path`` if needed.

+ ``njoin(*path)`` --- join pathname components + convert ``/``-separated path
  to ``os.sep``-separated path and resolve ``..``, ``.`` from paths.
  Ex. ``njoin('a',['b','./c'],'..','g') -> os.path.join('a','b','g')``.

+ ``minrelpath(path)`` --- resolves dots in ``path``.

+ ``rel_path(path, parent_path)`` --- return ``path`` relative to ``parent_path``.

+ ``def get_cmd(cmdname,_cache={})`` --- returns ``numpy.distutils``
  command instance.

+ ``all_strings(lst)``

+ ``has_f_sources(sources)``

+ ``has_cxx_sources(sources)``

+ ``filter_sources(sources)`` --- return ``c_sources, cxx_sources,
  f_sources, fmodule_sources``

+ ``get_dependencies(sources)``

+ ``is_local_src_dir(directory)``

+ ``get_ext_source_files(ext)``

+ ``get_script_files(scripts)``

+ ``get_lib_source_files(lib)``

+ ``get_data_files(data)``

+ ``dot_join(*args)`` --- join non-zero arguments with a dot.

+ ``get_frame(level=0)`` --- return frame object from call stack with given level.

+ ``cyg2win32(path)``

+ ``mingw32()`` --- return ``True`` when using mingw32 environment.

+ ``terminal_has_colors()``, ``red_text(s)``, ``green_text(s)``,
  ``yellow_text(s)``, ``blue_text(s)``, ``cyan_text(s)``

+ ``get_path(mod_name,parent_path=None)`` --- return path of a module
  relative to parent_path when given. Handles also ``__main__`` and
  ``__builtin__`` modules.

+ ``allpath(name)`` --- replaces ``/`` with ``os.sep`` in ``name``.

+ ``cxx_ext_match``, ``fortran_ext_match``, ``f90_ext_match``,
  ``f90_module_name_match``

``numpy.distutils.system_info`` module
--------------------------------------

+ ``get_info(name,notfound_action=0)``
+ ``combine_paths(*args,**kws)``
+ ``show_all()``

``numpy.distutils.cpuinfo`` module
----------------------------------

+ ``cpuinfo``

``numpy.distutils.log`` module
------------------------------

+ ``set_verbosity(v)``


``numpy.distutils.exec_command`` module
---------------------------------------

+ ``get_pythonexe()``
+ ``find_executable(exe, path=None)``
+ ``exec_command( command, execute_in='', use_shell=None, use_tee=None, **env )``

The ``__init__.py`` file
''''''''''''''''''''''''

The header of a typical SciPy ``__init__.py`` is::

  """
  Package docstring, typically with a brief description and function listing.
  """

  # import functions into module namespace
  from .subpackage import *
  ...

  __all__ = [s for s in dir() if not s.startswith('_')]

  from numpy.testing import Tester
  test = Tester().test
  bench = Tester().bench

Extra features in NumPy Distutils
'''''''''''''''''''''''''''''''''

Specifying config_fc options for libraries in setup.py script
-------------------------------------------------------------

It is possible to specify config_fc options in setup.py scripts.
For example, using

  config.add_library('library',
                     sources=[...],
                     config_fc={'noopt':(__file__,1)})

will compile the ``library`` sources without optimization flags.

It's recommended to specify only those config_fc options in such a way
that are compiler independent.

Getting extra Fortran 77 compiler options from source
-----------------------------------------------------

Some old Fortran codes need special compiler options in order to
work correctly. In order to specify compiler options per source
file, ``numpy.distutils`` Fortran compiler looks for the following
pattern::

  CF77FLAGS(<fcompiler type>) = <fcompiler f77flags>

in the first 20 lines of the source and use the ``f77flags`` for
specified type of the fcompiler (the first character ``C`` is optional).

TODO: This feature can be easily extended for Fortran 90 codes as
well. Let us know if you would need such a feature.
