Debian Codegraph @

contrib/fypp-3.2-b8dd58b-20230822/docs/fypp.rst

raw
1 .. highlight:: none
2
3 ************
4 Introduction
5 ************
6
7 Fypp is a Python powered preprocessor. It can be used for any programming
8 languages but its primary aim is to offer a Fortran preprocessor, which helps to
9 extend Fortran with condititional compiling and template metaprogramming
10 capabilities. Instead of introducing its own expression syntax, it uses Python
11 expressions in its preprocessor directives, offering the consistency and
12 versatility of Python when formulating metaprogramming tasks. It puts strong
13 emphasis on robustness and on neat integration into developing toolchains.
14
15 Fypp was inspired by the `pyratemp
16 <http://www.simple-is-better.org/template/pyratemp.html>`_ templating engine
17 [1]_. Although it shares many concepts with pyratemp, it was written from
18 scratch focusing on the special needs when preprocessing source code. Fypp
19 natively supports the output of line numbering markers, which are used by
20 many compilers to generate compiler messages with correct line numbers. Unlike
21 most cpp/fpp-like preprocessors or the coco preprocessor, Fypp also supports
22 iterations, multiline macros, continuation lines in preprocessor directives and
23 automatic line folding. It generally tries to extend the modern Fortran language
24 with metaprogramming capabilities without tempting you to use it for tasks which
25 could/should be done in Fortran itself.
26
27 The project is `hosted on github <https://github.com/aradi/fypp>`_ with
28 documentation available on `readthedocs.org
29 <http://fypp.readthedocs.org>`_. Fypp is released under the *BSD 2-clause
30 license*.
31
32 This document describes Fypp Version 3.2.
33
34
35 Features
36 ========
37
38 Below you find a summary over Fypps main features. Each of them is described
39 more in detail in the individual sections further down.
40
41 * Definition, evaluation and removal of variables::
42
43 #:if DEBUG > 0
44 print *, "Some debug information"
45 #:endif
46
47 #:set LOGLEVEL = 2
48 print *, "LOGLEVEL: ${LOGLEVEL}$"
49
50 #:del LOGLEVEL
51
52 * Macro definitions and macro calls::
53
54 #:def ASSERT(cond)
55 #:if DEBUG > 0
56 if (.not. ${cond}$) then
57 print *, "Assert failed in file ${_FILE_}$, line ${_LINE_}$"
58 error stop
59 end if
60 #:endif
61 #:enddef ASSERT
62
63 ! Invoked via direct call (argument needs no quotation)
64 @:ASSERT(size(myArray) > 0)
65
66 ! Invoked as Python expression (argument needs quotation)
67 $:ASSERT('size(myArray) > 0')
68
69 * Conditional output::
70
71 program test
72 #:if defined('WITH_MPI')
73 use mpi
74 #:elif defined('WITH_OPENMP')
75 use openmp
76 #:else
77 use serial
78 #:endif
79
80 * Iterated output (e.g. for generating Fortran templates)::
81
82 interface myfunc
83 #:for dtype in ['real', 'dreal', 'complex', 'dcomplex']
84 module procedure myfunc_${dtype}$
85 #:endfor
86 end interface myfunc
87
88 * Inline directives::
89
90 logical, parameter :: hasMpi = #{if defined('MPI')}# .true. #{else}# .false. #{endif}#
91
92 * Insertion of arbitrary Python expressions::
93
94 character(*), parameter :: comp_date = "${time.strftime('%Y-%m-%d')}$"
95
96 * Inclusion of files during preprocessing::
97
98 #:include "macrodefs.fypp"
99
100 * Using Fortran-style continutation lines in preprocessor directives::
101
102 #:if var1 > var2 &
103 & or var2 > var4
104 print *, "Doing something here"
105 #:endif
106
107 * Passing (unquoted) multiline string arguments to callables::
108
109 #! Callable needs only string argument
110 #:def DEBUG_CODE(code)
111 #:if DEBUG > 0
112 $:code
113 #:endif
114 #:enddef DEBUG_CODE
115
116 #! Pass code block as first positional argument
117 #:block DEBUG_CODE
118 if (size(array) > 100) then
119 print *, "DEBUG: spuriously large array"
120 end if
121 #:endblock DEBUG_CODE
122
123 #! Callable needs also non-string argument types
124 #:def REPEAT_CODE(code, repeat)
125 #:for ind in range(repeat)
126 $:code
127 #:endfor
128 #:enddef REPEAT_CODE
129
130 #! Pass code block as positional argument and 3 as keyword argument "repeat"
131 #:block REPEAT_CODE(repeat=3)
132 this will be repeated 3 times
133 #:endblock REPEAT_CODE
134
135
136 * Preprocessor comments::
137
138 #! This will not show up in the output
139 #! Also the newline characters at the end of the lines will be suppressed
140
141 * Suppressing the preprocessor output in selected regions::
142
143 #! Definitions are read, but no output (e.g. newlines) will be produced
144 #:mute
145 #:include "macrodefs.fypp"
146 #:endmute
147
148 * Explicit request for stopping the preprocessor::
149
150 #:if DEBUGLEVEL < 0
151 #:stop 'Negative debug level not allowed!'
152 #:endif
153
154 * Easy check for macro parameter sanity::
155
156 #:def mymacro(RANK)
157 #! Macro only works for RANK 1 and above
158 #:assert RANK > 0
159 :
160 #:enddef mymacro
161
162 * Line numbering markers in output::
163
164 program test
165 #:if defined('MPI')
166 use mpi
167 #:endif
168 :
169
170 transformed to ::
171
172 # 1 "test.fypp" 1
173 program test
174 # 3 "test.fypp"
175 use mpi
176 # 5 "test.fypp"
177 :
178
179 when variable ``MPI`` is defined and Fypp was instructed to generate line
180 markers.
181
182 * Automatic folding of generated lines exceeding line length limit
183
184
185 ***************
186 Getting started
187 ***************
188
189 Installing
190 ==========
191
192 Fypp needs a working Python 3 interpreter (Python 3.5 or above).
193
194 When you install Fypp, you obtain the command line tool ``fypp`` and the Python
195 module ``fypp.py``. Latter you can import if you want to access the
196 functionality of Fypp directly from within your Python scripts.
197
198
199 Installing via conda
200 --------------------
201
202 The last stable release of Fypp can be easily installed as conda package by
203 issuing ::
204
205 conda install -c conda-forge fypp
206
207
208 Installing via pip
209 ------------------
210
211 You can also use Pythons command line installer ``pip`` in order to download the
212 stable release from the `Fypp page on PyPI <http://pypi.python.org/pypi/fypp>`_
213 and install it on your system.
214
215 If you want to install Fypp into the module system of the active Python 3
216 interpreter (typically the case when you are using a Python virtual
217 environment), issue ::
218
219 pip3 install fypp
220
221 Alternatively, you can install Fypp into the user space (under `~/.local`) with
222 ::
223
224 pip3 install --user fypp
225
226
227 Manual install
228 --------------
229
230 For a manual install, you can download the source code of the latest **stable**
231 release from the `Fypp project website
232 <https://github.com/aradi/fypp/releases>`_.
233
234 If you wish to obtain the latest **development** version, clone the projects
235 repository::
236
237 git clone https://github.com/aradi/fypp.git
238
239 and check out the `master` branch.
240
241 The command line tool is a single stand-alone script. You can run it directly
242 from the source folder ::
243
244 FYPP_SOURCE_FOLDER/bin/fypp
245
246 or after copying it from the `bin` folder to any location listed in your `PATH`
247 environment variable, by just issuing ::
248
249 fypp
250
251 The python module ``fypp.py`` can be found in ``FYP_SOURCE_FOLDER/src``.
252
253
254 Testing
255 =======
256
257 Simple manual testing can be done by issuing the command ::
258
259 ./test/runtests.sh
260
261 from the root of the Fypp source tree. This executes the unit tests shipped with
262 Fypp with the default Python interpreter in your path. If you wish to use a
263 specific interpreter, you can pass it as argument to the script::
264
265 ./test/runtests.sh python3
266
267 You can also pass multiple interpreters as separate arguments. In that case
268 the testing will be carried out for each of them.
269
270
271 Testing for developers
272 ----------------------
273
274 If you wish to contribute to Fypp, you should have `tox` installed on your
275 system, so that you can test the packaged project in isolated environments
276 before issuing a pull request.
277
278 In order to execute the unit tests with `tox`, run ::
279
280 tox
281
282 from the root folder of the source tree. This tries to test Fypp with various
283 different python interpreters. If you want to limit testing to selected
284 interpeters only, select the environment with the appropriate command line
285 switch, e.g. ::
286
287 tox -e py34
288
289
290
291 Running
292 =======
293
294 The Fypp command line tool reads a file, preprocesses it and writes it to
295 another file, so you would typically invoke it like::
296
297 fypp source.fpp source.f90
298
299 which would process `source.fpp` and write the result to `source.f90`. If
300 input and output files are not specified, information is read from stdin and
301 written to stdout.
302
303 The behavior of Fypp can be influenced with various command line options. A
304 summary of all command line options can be obtained by::
305
306 fypp -h
307
308
309 *********************
310 Preprocessor language
311 *********************
312
313
314 General syntax
315 ==============
316
317 Fypp has three types of preprocessor directives, all of them having a line and
318 an inline form:
319
320 * Control directives
321
322 * Line form, starting with ``#:`` (hashmark colon)::
323
324 #:if 1 > 2
325 Some code
326 #:endif
327
328 * Inline form, enclosed between ``#{`` and ``}#``::
329
330 #{if 1 > 2}#Some code#{endif}#
331
332 * Eval directives
333
334 * Line form, starting with ``$:`` (dollar colon)::
335
336 $:time.strftime('%Y-%m-%d')
337
338 * Inline form, enclosed between ``${`` and ``}$``::
339
340 print *, "Compilation date: ${time.strftime('%Y-%m-%d')}$"
341
342 * Direct call directive
343
344 * Line form, starting with ``@:`` (at colon)::
345
346 @:mymacro(a < b)
347
348 * Inline form, enclosed between ``@{`` and ``}@``::
349
350 print *, @{mymacro(a < b)}@
351
352 The line form must always start at the beginning of a line (preceded by optional
353 whitespace characters only) and it ends at the end of the line. The inline form
354 can appear anywhere, but if the construct consists of several directives
355 (e.g. ``#{if ...}#`` and ``#{endif}#``), all of them must appear on the same
356 line. While both forms can be used at the same time, they must be consistent for
357 a particular construct, e.g. a directive opened as line directive can not be
358 closed by an inline directive and vica versa.
359
360 Whitespaces in preprocessor commands are ignored if they appear after the
361 opening colon or curly brace or before the closing curly brace. So the following
362 examples are pairwise equivalent::
363
364 #:if 1 > 2
365 #: if 1 > 2
366
367 #{if 1 > 2}#
368 #{ if 1 > 2 }#
369
370 $:time.strftime('%Y-%m-%d')
371 $: time.strftime('%Y-%m-%d')
372
373 ${time.strftime('%Y-%m-%d')}$
374 ${ time.strftime('%Y-%m-%d') }$
375
376 Starting whitespaces before line directives are ignored, enabling you to choose
377 any indentation strategy you like for the directives::
378
379 program test
380 :
381 do ii = 1, nn
382 print *, ii
383 #:if DEBUG > 0
384 print *, "Some debug info about iteration ${ii}$"
385 #:endif
386 print *, "Normal code"
387 end do
388 :
389 end program test
390
391 Preprocessor directives can be arbitrarily nested::
392
393 #:if DEBUG > 0
394 #:if DO_LOGGING
395 ...
396 #:endif
397 #:endif
398
399 Every open directive must be closed before the end of the file is reached.
400
401 In all control directives, the whitespace separating the name of the directive
402 from the following parameter is obligatory. Therefore, the following example is
403 syntactically incorrect::
404
405 #! Incorrect due to missing whitespace after 'if'
406 #:if(1 > 2)
407
408
409 Expression evaluation
410 =====================
411
412 Python expressions can occur either as part of control directives, like ::
413
414 #:if DEBUG > 0
415 #:for dtype in ['real(dp)', 'integer', 'logical']
416
417 or directly inserted into the code using eval directives. ::
418
419 $:time.strftime('%Y-%m-%d')
420 print *, "${time.strftime('%Y-%m-%d')}$"
421
422 Expressions are always evaluated by using Pythons ``eval()`` builtin and must
423 be, therefore, syntactically and semantically correct Python
424 expressions. Although, this may require some additional quotations as compared
425 to other preprocessor languages ::
426
427 #:if defined('DEBUG') #! The Python function defined() expects a string argument
428 #:for dtype in ['real(dp)', 'integer', 'logical'] #! dtype runs over strings
429
430 it enables consistent expressions with (hopefully) least surprises (once you
431 know, how to formulate the expression in Python, you exactly know, how to write
432 it for Fypp). Also, note, that variable names, macros etc. are for Python (and
433 therefore also for Fypp) case sensitive.
434
435 When you access a variable in an expression, it must have been already defined
436 before, either via command line options or via preprocessor directives. For
437 example the directive ::
438
439 #:if DEBUG > 0
440
441 can only be evaluated, if the variable `DEBUG` had been already defined before.
442
443
444 Python sandbox
445 ==============
446
447 Python expressions are evaluated in an isolated Python environment, which
448 contains a restricted set of Python built-in functions and a few predefined
449 variables and functions (see below). There are no modules loaded by default, and
450 for safety reasons, no modules can be loaded once the preprocessing has
451 started, but can be loaded at startup if needed.
452
453 Predefined variables
454 --------------------
455
456 The isolated Python environment for the expression evaluation contains following
457 predefined global variables:
458
459 * ``_THIS_LINE_``: number of current line
460
461 * ``_THIS_FILE_``: name of current file
462
463 * ``_LINE_``: number of current line in the processed input file
464
465 * ``_FILE_``: name of processed input file ::
466
467 print *, "This is line nr. ${_LINE_}$ in file '${_FILE_}$'"
468
469 * ``_DATE_``: current date in ISO format
470
471 * ``_TIME_``: current time::
472
473 print *, "Rendering started ${_DATE_}$ ${_TIME_}$"
474
475 * ``_SYSTEM_``: Name of the system Fypp runs on, as returned by Pythons
476 ``platform.system()`` function (e.g. ``Linux``, ``Windows``, ``Darwin``, etc.)
477
478 * ``_MACHINE_``: Name of the current machine Fypp runs on, as returned by
479 Pythons ``platform.machine()`` function (e.g. ``x86_64``)
480
481 The predefined variables ``_FILE_`` and ``_LINE_`` differ from their
482 counterparts ``_THIS_FILE_`` and ``_THIS_LINE_`` only within macros. When a
483 macro is executed, the variables ``_THIS_FILE_`` and ``_THIS_LINE_`` specify the
484 position, where the expression containing these variables is located, while the
485 variables ``_FILE_`` and ``_LINE_`` refer to the position in the processed file,
486 from where the macro was called (and where the result of the evaluation will be
487 inserted later). For example, the input ::
488
489 #:def macro()
490 IN MACRO: _THIS_LINE_=${_THIS_LINE_}$, _LINE_=${_LINE_}$
491 #:enddef macro
492
493 GLOBAL: _THIS_LINE_=${_THIS_LINE_}$, _LINE_=${_LINE_}$ | ${macro()}$
494
495 yields after being processed by Fypp::
496
497 GLOBAL: _THIS_LINE_=5, _LINE_=5 | IN MACRO: _THIS_LINE_=2, _LINE_=5
498
499 If from within a macro an other macro is called, the variables ``_FILE_`` and
500 ``_LINE_`` will keep their original values, while ``_THIS_FILE_`` and
501 ``_THIS_LINE_`` will be continuously updated within the nested macro as well.
502
503
504 Predefined functions
505 --------------------
506
507 Following predefined functions are available:
508
509 * ``defined(VARNAME)``: Returns ``True`` if a variable with a given name has
510 been already defined. The variable name must be provided as string::
511
512 #:if defined('WITH_MPI')
513
514 * ``getvar(VARNAME, DEFAULTVALUE)``: Returns the value of a variable or a
515 default value if the variable is not defined. The variable name must be
516 provided as string::
517
518 #:if getvar('DEBUG', 0)
519
520 * ``setvar(VARNAME, VALUE)``: Sets a variable to given value. It is identical to
521 the `set directive`_. The variable name expression has the same format as in
522 the ``#:set`` directive, but must be quoted::
523
524 $:setvar('i', 12)
525 print *, "VAR I: ${i}$"
526
527 Multiple assignments may be specified as subsequent argument pairs::
528
529 $:setvar('i', 1, 'j', 2)
530 print *, "VAR I: ${i}$, VAR J: ${j}$"
531
532 * ``delvar(VARNAME)``: Removes a variable or a macro definition from the local
533 scope. It is identical to the `del directive`_. The variable name
534 expression must be provided as in the ``#:del`` directive, but must be quoted::
535
536 $:delvar('i')
537
538 Additional variable name expressions may be specified as subsequent arguments::
539
540 $:delvar('i', 'j')
541
542
543 * ``globalvar(VARNAME)``: Adds a given variable as global variable to the
544 current scope. It is identical to the `global directive`_. The variable name
545 expression must be provided as in the ``#:global`` directive, but must be
546 quoted::
547
548 $:globalvar('i')
549
550 Multiple variable name expressions may be specified as subsequent arguments.
551
552
553 Initializing variables
554 ----------------------
555
556 Initial values for preprocessor variables can be set via the command line option
557 (``-D``) at startup::
558
559 fypp -DDEBUG=0 -DWITH_MPI
560
561 The assigned value for a given variable is evaluated in Python. If no value is
562 provided, `None` is assigned.
563
564
565 Importing modules at startup
566 ----------------------------
567
568 .. warning:: Modules imported at startup have access to the full
569 **unrestricted** Python environment and can execute any Python code. Import
570 only trustworthy modules!
571
572 If a Python module is required for the preprocessing, it can be imported before
573 the preprocessing starts via the command line option (``-m``)::
574
575 fypp -m time
576
577 The example above would allow to process the line::
578
579 character(*), parameter :: comp_date = "${time.strftime('%Y-%m-%d')}$"
580
581 If more than one module is needed, each of them can imported with an individual
582 ``-m`` option::
583
584 fypp -m time -m math
585
586 When importing modules with the ``-m`` option, the module search path consists
587 of the current directory, the directories in the `PYTHONPATH` environment
588 variable and the standard Python module paths. Further lookup paths can be
589 specified using the option ``-M``::
590
591 fypp -M mymoddir1 -M mymoddir2 -m mymodule -m mymodule2
592
593 The module directories are looked up in the order they are specified *before*
594 searching at the default locations. Modules are imported also in the order of
595 their specification at the command line.
596
597 Each module imported at startup has its own name space. Entities in the imported
598 modules can be accessed during the preprocessing in the usual pythonic
599 way. After importing the module ``mymodule`` as in the example above, entities
600 in the module could be accessed as::
601
602 ${mymodule.SOME_CONSTANT}$
603
604 $:mymodule.SOME_CONSTANT
605
606 $:mymodule.some_function()
607
608 @:mymodule.some_function()
609
610 #:call mymodule.some_function
611 #:endcall mymodule.some_function
612
613 #:block mymodule.some_function
614 #:endblock mymodule.some_function
615
616
617
618 Eval directive
619 ==============
620
621 A result of a Python expression can be inserted into the code by using eval
622 directives ``$:`` (line form) or ``${`` and ``}$`` (inline form). The expression
623 is evaluated using Python's built-in function `eval()`. If it evaluates to
624 `None`, no output is produced. Otherwise the result is converted to a string and
625 written to the output. The eval directive has both, a line and an inline
626 variant::
627
628 $:somePythonFunction()
629 print *, "DEBUG LEVEL: ${DEBUG}$"
630
631 .. warning:: Lines containing eval directive(s) will be folded using
632 Fortran continuation lines when getting longer than a specified maximum. They
633 must, therefore, not contain anything which could lead to invalid source
634 code, when being folded at an arbitrary position (e.g. Fortran comments).
635
636
637 `set` directive
638 ==================
639
640 The value of a variable can be set during the preprocessing via the `set`
641 directive. (Otherwise, variables can be also declared and defined via command
642 line options.) The first argument is the name of the variable (unquoted),
643 followed by an optional Python expression. If the Python expression is present,
644 it must be separated by an equal sign from the variable name. If the Python
645 expression and the equal sign are not present, the variable is set to `None`::
646
647 #:set DEBUG
648 #:set LOG = 1
649 #:set LOGLEVEL = LOGLEVEL + 1
650
651 Note, that in the last example the variable `LOGLEVEL` must have been already
652 defined in advance.
653
654 The `set` directive also accepts assignments to variable tuples, provided the
655 right hand side of the assignment is compatible with the variable tuple::
656
657 #:set VAR1, VAR2 = 1, 2
658 #:set (VAR1, VAR2) = 1, 2
659
660 The parantheses around the variable list (second example) are optional.
661
662 The `set` directive can be also used in the inline form::
663
664 #{set X = 2}#print *, ${X}$
665
666 Similar to the line form, the separating equal sign is optional here as well.
667
668
669 `del` directive
670 ===============
671
672 A variable (or macro) definition can be removed from the current scope by the
673 `del` directive::
674
675 #:set X = 12
676 #! X available, with value 12
677 :
678 #:del X
679 #! X not available any more
680
681 The variable name expression syntax is identical to the one used for the `set`
682 directive, so that also variable tuples can be deleted::
683
684 #! Removes the variables X and Y from local scope
685 #:del X, Y
686
687 The variable passed to the ``del`` directive must exist and be erasable. So the
688 example above would trigger an error, if the variables ``X`` and ``Y`` were not
689 defined before.
690
691 The `del` directive can also be used to delete macro definitions::
692
693 #:def echo(TXT)
694 ${TXT}$
695 #:enddef
696 @:echo(HELLO)
697 #:del echo
698 #! Following line throws an error as macro echo is not available any more
699 @:echo(HELLO)
700
701 The `del` directive can be also used in the inline form::
702
703 #{del X}#
704
705
706 `if` directive
707 ==============
708
709 Conditional output can be generated using the `if` directive. The condition must
710 be a Python expression, which can be converted to a `bool`. If the condition
711 evaluates to `True`, the enclosed code is written to the output, otherwise it is
712 ignored.
713
714 ::
715
716 print *, "Before"
717 #:if DEBUG > 0
718 print *, "Debug code"
719 #:endif
720 print *, "After"
721
722 would result in
723
724 ::
725
726 print *, "Before"
727 print *, "Debug code"
728 print *, "After"
729
730 if the Python expression ``DEBUG > 0`` evaluates to `True`, otherwise in
731
732 ::
733
734 print *, "Before"
735 print *, "After"
736
737 For more complex scenarios ``elif`` and ``else`` branches can be
738 used as well::
739
740 #:if DEBUG >= 2
741 print *, "Very detailed debug info"
742 #:elif DEBUG >= 1
743 print *, "Less detailed debug info"
744 #:else
745 print *, "No debug info"
746 #:endif
747
748 The `if` directive is also available as inline directive::
749
750 print *, "COMPILATION MODE: #{if DEBUG > 0}#DEBUG#{else}#PRODUCTION#{endif}#"
751
752
753 `for` directive
754 ===============
755
756 Fortran templates can be easily created by using the `for` directive. The
757 following example creates a function for calculating the sine square for both
758 single and double precision reals::
759
760 #:set real_kinds = ['sp', 'dp']
761
762 interface sin2
763 #:for rkind in real_kinds
764 module procedure sin2_${rkind}$
765 #:endfor
766 end interface sin2
767
768 #:for rkind in real_kinds
769 function sin2_${rkind}$(xx) result(res)
770 real(${rkind}$), intent(in) :: xx
771 real(${rkind}$) :: res
772
773 res = sin(xx) * sin(xx)
774
775 end function sin2_${rkind}$
776 #:endfor
777
778 The `for` directive expects a loop variable expression and an iterable
779 separated by the ``in`` keyword. The code within the `for` directive is outputed
780 for every iteration with the current value of the loop variable, which can be
781 inserted using eval directives. The loop variable expression must be either a
782 name or a list of names joined by comma (``,``). In the latter case, the
783 iterable must consist of iterable items (e.g. tuples), which will be then
784 unpacked into the loop variables. (The number of the loop variables and the
785 number of the components of each iterated item must be identical.)::
786
787 #:set kinds = ['sp', 'dp']
788 #:set names = ['real', 'dreal']
789 #! create kinds_names as [('sp', 'real'), ('dp', 'dreal')]
790 #:set kinds_names = list(zip(kinds, names))
791
792 #! Access by indexing
793 interface sin2
794 #:for kind_name in kinds_names
795 module procedure sin2_${kind_name[1]}$
796 #:endfor
797 end interface sin2
798
799 #! Unpacking in the loop header
800 #:for kind, name in kinds_names
801 function sin2_${name}$(xx) result(res)
802 real(${kind}$), intent(in) :: xx
803 real(${kind}$) :: res
804
805 res = sin(xx) * sin(xx)
806
807 end function sin2_${name}$
808 #:endfor
809
810
811 The `for` directive can be used also in its inline form::
812
813 print *, "Numbers: #{for i in range(5)}#${i}$#{endfor}#"
814
815
816
817 `def` directive
818 ===============
819
820 Parametrized macros can be defined with the `def` directive. This defines a
821 regular callable in Python, which returns the rendered content of the macro body
822 when called. The macro arguments are converted to local variables containing the
823 actual arguments as values. The macro can be called from within an
824 eval-directive, via the `call` and `block` control directives and via their
825 abreviated form, the direct call.
826
827 Given the macro definition ::
828
829 #:def ASSERT(cond)
830 #:if DEBUG > 0
831 if (.not. (${cond}$)) then
832 print *, "Assert failed!"
833 error stop
834 end if
835 #:endif
836 #:enddef
837
838 the following three calls ::
839
840 #! call macro by evaluating a Python expression
841 $:ASSERT('x > y')
842
843 #! call macro by using the call directive (see below)
844 #:call ASSERT
845 x > y
846 #:endcall ASSERT
847
848 #! call macro by using the block directive (see below)
849 #:block ASSERT
850 x > y
851 #:endblock ASSERT
852
853 #! call macro by using the direct call directive (see below)
854 @:ASSERT(x > y)
855
856 would all yield ::
857
858 if (.not. (x > y)) then
859 print *, "Assert failed!"
860 error stop
861 end if
862
863 if the variable `DEBUG` had a value greater than zero or an empty string
864 otherwise.
865
866 It is possible to declare default values for the positional arguments of a
867 macro. If for a given positional argument such a value is provided, then default
868 values must be provided for all following arguments as well. When the macro is
869 called, missing positional arguments will be replaced by their default value::
870
871 #:def macro(X, Y=2, Z=3)
872 X=${X}$, Y=${Y}$, Z=${Z}$
873 #:enddef macro
874
875 $:macro(1) #! Returns "X=1, Y=2, Z=3"
876
877 Similar to Python, it is also possible to define macros with a variable number
878 of positional or keyword arguments (variadic macros) using the ``*`` and ``**``
879 argument prefixes. The corresponding arguments will contain the unprocessed
880 positional and keywords arguments as a list and a dictionary, respectively::
881
882 #:def macro(X, *VARPOS, **VARKW)
883 pos: ${X}$
884 varpos: #{for ARG in VARPOS}#${ARG}$, #{endfor}#
885 varkw: #{for KEYWORD in VARKW}#${KEYWORD}$->${VARKW[KEYWORD]}$, #{endfor}#
886 #:enddef macro
887
888 Calling the example macro above with ::
889
890 $:macro(1, 2, 3, kw1=4, kw2=5)
891
892 yields::
893
894 pos: 1
895 varpos: 2, 3,
896 varkw: kw1->4, kw2->5,
897
898 Macros can be invoked recursively. Together with the variadic arguments, this
899 enables the realization of variadic templates (similar to C++) [2]_::
900
901 #:def horner(x, a, b, *args)
902 #:set res = "({} * {} + ({}))".format(a, x, b)
903 #:if len(args) > 0
904 #:set res = horner(x, res, args[0], *args[1:])
905 #:endif
906 $:res
907 #:enddef
908
909 Calling the ``horner`` macro with ::
910
911 poly = @{horner(x, 2, -3, 4, -5, 6)}@
912
913 would result in the Horner scheme with the specified coefficients::
914
915 poly = ((((2 * x + (-3)) * x + (4)) * x + (-5)) * x + (6))
916
917
918 Scopes
919 ------
920
921 Scopes in general follow the Python convention: Within the macro, all variables
922 from the encompassing scope are available (as `DEBUG` in the example above), and
923 additionally those which were passed as arguments. If a variable is defined
924 within the macro, it will be only accessible within the macro. If a variable
925 with the same name already exists in the encompassing scope, it will be shadowed
926 by it for the time of the macro substitution. For example preprocessing the code
927 snippet ::
928
929 #:def macro(x)
930 print *, "Local XY: ${x}$ ${y}$"
931 #:set y = -2
932 print *, "Local XY: ${x}$ ${y}$"
933 #:enddef
934
935 #:set x = 1
936 #:set y = 2
937 print *, "Global XY: ${x}$ ${y}$"
938 $:macro(-1)
939 print *, "Global XY: ${x}$ ${y}$"
940
941 would result in ::
942
943 print *, "Global XY: 1 2"
944 print *, "Local XY: -1 2"
945 print *, "Local XY: -1 -2"
946 print *, "Global XY: 1 2"
947
948
949 For better readability, you can repeat the name of the macro (but not its
950 argument list) at the corresponding enddef directive::
951
952 #:def ASSERT(cond)
953 #:if DEBUG > 0
954 if (.not. (${cond}$)) then
955 print *, "Assert failed!"
956 error stop
957 end if
958 #:endif
959 #:enddef ASSERT
960
961
962 The `def` directive has no inline form.
963
964 .. warning:: The content of macros is usually inserted via an eval directive and
965 is accordingly subject to eventual line folding. Macros should,
966 therefore, not contain any inline Fortran comments. (Comments
967 starting at the beginning of the line preceded by optional
968 whitespaces only are OK, though). Use preprocessor comments
969 (``#!``) instead.
970
971
972 `block` and `call` directives
973 =============================
974
975 When a Python callable (regular Python function, macro etc.) needs a string
976 argument of larger size (e.g. source code), it can be called using the `call` or
977 the `block` directives to avoid extra quoting of the text argument and to enable
978 passing of multiline arguments in a comfortable way::
979
980 #:def DEBUG_CODE(code)
981 #:if DEBUG > 0
982 $:code
983 #:endif
984 #:enddef DEBUG_CODE
985
986 #:block DEBUG_CODE
987 if (a < b) then
988 print *, "DEBUG: a is less than b"
989 end if
990 #:endblock DEBUG_CODE
991
992 #:call DEBUG_CODE
993 if (a < b) then
994 print *, "DEBUG: a is less than b"
995 end if
996 #:endcall DEBUG_CODE
997
998 The `block` and the `call` directives are equivalent. The two alternative forms
999 exists in order to allow for more readable meta-code depending on the context.
1000
1001 The `block` and `call` directives take the name of the callable as argument. The
1002 lines between the opening and closing directives will be rendered and then
1003 passed as positional *string* arguments to the callable. The name of the
1004 callable can be repeated in the `endblock` and `endcall` directives for enhanced
1005 readability::
1006
1007 #! This form is probably somewhat more natural to read
1008 #:block DEBUG_CODE
1009 if (a < b) then
1010 print *, "DEBUG: a (${a}$) is less than b (${b}$)"
1011 end if
1012 #:endblock DEBUG_CODE
1013
1014 #:call DEBUG_CODE
1015 if (a < b) then
1016 print *, "DEBUG: a (${a}$) is less than b (${b}$)"
1017 end if
1018 #:endcall DEBUG_CODE
1019
1020 If the callable needs more than one string arguments, the `contains` directive
1021 (for `block`) or the `nextarg` directive (for `call`) can be used to separate
1022 the arguments from each other::
1023
1024 #:def CHOOSE_CODE(debug_code, nondebug_code)
1025 #:if DEBUG > 0
1026 $:debug_code
1027 #:else
1028 $:nondebug_code
1029 #:endif
1030 #:enddef CHOOSE_CODE
1031
1032 #:block CHOOSE_CODE
1033 if (a < b) then
1034 print *, "DEBUG: a is less than b"
1035 end if
1036 #:contains
1037 print *, "No debugging"
1038 #:endcall CHOOSE_CODE
1039
1040 #! This form is probably somewhat more natural to read
1041 #:call CHOOSE_CODE
1042 if (a < b) then
1043 print *, "DEBUG: a is less than b"
1044 end if
1045 #:nextarg
1046 print *, "No debugging"
1047 #:endcall CHOOSE_CODE
1048
1049 The lines in the body of the `block` and `call` directives may contain
1050 directives themselves. However, any variable defined within the body of the
1051 `block` and `call` directives will be a local variable existing only during the
1052 evaluation of that branch of the directive (and not being available when the
1053 callable is called with the evaluated string as argument).
1054
1055 The `contains` and `nextarg` directives may be followed by an optional argument
1056 name. In that case the text following will be passed as keyword argument to the
1057 callable. If the first argument should be also passed as keyword argument, it
1058 should be also preceded by a named `contains` or `nextarg` directive declared
1059 in the line immediately following the `block` or `call` directive. If an
1060 argument is passed as a keyword argument, all following arguments must be passed
1061 as keyword arguments as well::
1062
1063 #:block CHOOSE_CODE
1064 #:contains nondebug_code
1065 print *, "No debugging"
1066 #:contains debug_code
1067 if (a < b) then
1068 print *, "DEBUG: a is less than b"
1069 end if
1070 #:endblock CHOOSE_CODE
1071
1072 #:call CHOOSE_CODE
1073 #:nextarg nondebug_code
1074 print *, "No debugging"
1075 #:nextarg debug_code
1076 if (a < b) then
1077 print *, "DEBUG: a is less than b"
1078 end if
1079 #:endcall CHOOSE_CODE
1080
1081 Additional to passing the content of the `block` or `call` directives body as
1082 string argument, further arguments of arbitrary type can be passed by specifying
1083 them directly in the header of the directive. Among others, this can be very
1084 comfortable when the callable needs also non-string type of arguments::
1085
1086 #! Argument 'repeat' should be an integer, not string
1087 #:def REPEAT_CODE(code, repeat)
1088 #:for ind in range(repeat)
1089 $:code
1090 #:endfor
1091 #:enddef REPEAT_CODE
1092
1093 #! Code block as positional argument and 3 as keyword argument "repeat"
1094 #:block REPEAT_CODE(repeat=3)
1095 this will be repeated 3 times
1096 #:block REPEAT_CODE
1097
1098 #! Code block as positional argument and 3 as keyword argument "repeat"
1099 #:call REPEAT_CODE(repeat=3)
1100 this will be repeated 3 times
1101 #:endcall REPEAT_CODE
1102
1103 The arguments must be specified between parantheses and are evaluated as Python
1104 expressions. The arguments specified in the directive (both, in the header and
1105 in the body) are passed to the callable in the following order:
1106
1107 #. positional arguments in the header
1108
1109 #. positional arguments in the body
1110
1111 #. keyword arguments in the header
1112
1113 #. keyword arguments in the body
1114
1115 Callables without arguments can also be called with the `block` and `call`
1116 directives, provided the `endblock` and `endcall` directives immediately follows
1117 the opening directive. If there are empty lines between the opening and the
1118 closing directives, they will be interpreted as a positional argument::
1119
1120 #:def macro_noarg()
1121 NOARGS
1122 #:enddef macro_noarg
1123
1124 #:def macro_arg1(arg1)
1125 ARG1:${arg1}$
1126 #:enddef macro_arg1
1127
1128 #! Calling macro without arguments
1129 #:block macro_noarg
1130 #:endblock macro_noarg
1131
1132 #! Calling macro without arguments
1133 #:call macro_noarg
1134 #:endcall macro_noarg
1135
1136 #! Calling macro with one positional (empty) argument
1137 #! Note the empty line between block and endblock
1138 #:block macro_arg1
1139
1140 #:endblock macro_arg1
1141
1142 #! Calling macro with one positional (empty) argument
1143 #! Note the empty line between call and endcall
1144 #:call macro_arg1
1145
1146 #:endcall macro_arg1
1147
1148 The `block` and `call` directives can also be used in their inline form. As this
1149 easily leads to code being hard to read, it should be usually avoided::
1150
1151 ! Rather ugly
1152 print *, #{block CHOOSE_CODE}# a(:) #{contains}# size(a) #{endblock}#
1153
1154 ! Rather ugly as well
1155 print *, #{call CHOOSE_CODE}# a(:) #{nextarg}# size(a) #{endcall}#
1156
1157 ! This form is more readable
1158 print *, ${CHOOSE_CODE('a(:)', 'size(a)')}$
1159
1160 ! Alternatively, you may use a direct call (see next section)
1161 print *, @{CHOOSE_CODE(a(:), size(a))}@
1162
1163 If the callable only requires short text arguments, the more compact direct call
1164 directive should be used as an alternative (see next section).
1165
1166
1167 Direct call directive
1168 =====================
1169
1170 In order to enable compact (single line) calls while still maintaining code
1171 readability, the `block` and `call` directives have an alternative form, the
1172 direct call directive::
1173
1174 #:def ASSERT(cond)
1175 #:if DEBUG > 0
1176 if (.not. (${cond}$)) then
1177 print *, "Assert failed!"
1178 error stop
1179 end if
1180 #:endif
1181 #:enddef ASSERT
1182
1183 @:ASSERT(size(aa) >= size(bb))
1184
1185 The direct call directive starts with ``@:`` followed by the name of a Python
1186 callable and an opening parenthesis (``(``). Everything after that up to the
1187 closing parenthesis (``)``) is passed as *string argument* to the callable. The
1188 closing parenthesis may only be followed by whitespace characters.
1189
1190 When the callable needs more than one argument, the arguments must be separated
1191 by a comma (``,``)::
1192
1193 #:def ASSERT_EQUAL(received, expected)
1194 if (${received}$ /= ${expected}$) then
1195 print *, "ASSERT_EQUAL failed (${received}$ /= ${expected}$)!"
1196 error stop
1197 end if
1198 #:enddef ASSERT_EQUAL
1199
1200 @:ASSERT_EQUAL(size(coords, dim=2), size(atomtypes))
1201
1202 .. note:: In order to be able to split the argument string of a direct call
1203 correctly, Fypp assumes that all provided arguments represent valid
1204 Fortran expressions with balanced quotes (``'`` or ``"``) and balanced
1205 brackets (``()``, ``[]`` and ``{}``) outside of quoted regions. The
1206 argument string is only split around commas which are outside of any
1207 quoted or bracketed regions.
1208
1209 Arguments can be optionally enclosed within curly braces in order to avoid
1210 argument splitting at unwanted places or to improve readability. The outermost
1211 curly braces will be removed from the arguments before they are passed to the
1212 callable::
1213
1214 #! Passes "a**2 + b**2" and "c**2" as string arguments to ASSERT_EQUAL
1215 @:ASSERT_EQUAL({a**2 + b**2}, c**2)
1216
1217 Keywords arguments can be passed by prefixing them with the keyword name
1218 and an equal sign::
1219
1220 @:ASSERT_EQUAL(expected=size(atomtypes), received=size(coords, dim=2))
1221 @:ASSERT_EQUAL(expected=c**2, received={a**2 + b**2})
1222
1223 If the equal sign is followed immediately by an other equal sign, the argument
1224 will be recognized as positional and not as keyword argument. This exception
1225 allows for passing valid Fortran code containing the comparison operator
1226 (``==``) without the need for special bracketing. In other cases, however,
1227 bracketing may be needed to avoid recognition as keyword argument::
1228
1229 #! Passes string "a == b" as first positional argument
1230 @:ASSERT(a == b)
1231
1232 #! Passes string "=b" as keyword argument "a"
1233 @:ASSERT(a={=b})
1234
1235 #! Passes string "b" as keyword argument "a"
1236 @:someMacro(a = b)
1237
1238 #! Passes "a = b" as positional argument
1239 @:someMacro({a = b})
1240
1241 The direct call directive may contain continuation lines::
1242
1243 @:ASSERT_EQUAL(size(coords, dim=2), &
1244 & size(atomtypes))
1245
1246 The arguments are parsed for further inline eval directives (but not for any
1247 inline control or direct call directives), making variable substitutions in the
1248 arguments possible::
1249
1250 #:set MYSIZE = 2
1251 @:ASSERT_EQUAL(size(coords, dim=2), ${MYSIZE}$)
1252
1253 Whitespaces around the arguments of the direct call are stripped, but not the
1254 whitespaces within the optional curly braces around the argument::
1255
1256 #! Calls a macro without arguments
1257 @:macro_without_args()
1258
1259 #! Calls a macro with no arguments (whitespace between () is stripped):
1260 @:macro_without_args( )
1261
1262 #! Calls a macro with empty string as argument
1263 @:macro_with_one_arg({})
1264
1265 #! Calls a macro with one space as argument
1266 @:macro_with_one_arg({ })
1267
1268 The direct call directive can also be used in its inline form::
1269
1270 #! Using CHOOSE_CODE() macro defined in previous section
1271 print *, @{CHOOSE_CODE(a(:), size(a))}@
1272
1273
1274 `global` directive
1275 ==================
1276
1277 Global variables are by default read-only in local scopes (e.g. within
1278 macros). This can be changed for selected variables by using the `global`
1279 directive::
1280
1281 #:def set_debug(value)
1282 #:global DEBUG
1283 #:set DEBUG = value
1284 #:enddef set_debug
1285
1286 #:set DEBUG = 1
1287 $:DEBUG
1288 $:set_debug(2)
1289 $:DEBUG
1290
1291 In the example above, without the `global` directive, the `set` directive would
1292 have created a local variable within the macro, which had shadowed the global
1293 variable and was destroyed at the end of the macro execution. With the `global`
1294 directive the `set` refers to the variable in the global scope. The
1295 variable in the global scope does not need to exist yet, when the `global`
1296 directive is executed. It will be then created at the first `set` directive, or
1297 remain non-existing if no assignment is made in the current scope.
1298
1299 A variable can only made global, if it was not created in the local scope
1300 yet. Therefore, the following code would throw an exception::
1301
1302 #:def set_debug(value)
1303 #! DEBUG variable created in local scope
1304 #:set DEBUG = value
1305
1306 #! Invalid: variable DEBUG already exists in local scope
1307 #:global DEBUG
1308 #:enddef set_debug
1309
1310 # Throws exception
1311 $:set_debug(2)
1312
1313
1314 `include` directive
1315 ===================
1316
1317 The `include` directive allows you to collect your preprocessor macros and
1318 variable definitions in separate files and include them whenever needed. The
1319 include directive expects a quoted string with a file name::
1320
1321 #:include 'mydefs.fypp'
1322
1323 If the file name is relative, it is interpreted relative to the folder where the
1324 processed file is located (or to the current folder, if Fypp reads from
1325 stdin). Further lookup paths can be added with the ``-I`` command line option.
1326
1327 The `include` directive does not have an inline form.
1328
1329
1330 `mute` directive
1331 ================
1332
1333 Empty lines between Fypp definitions makes the code easier to read. However,
1334 being outside of Fypp-directives, those empty lines will be written unaltered to
1335 the output. This can be especially disturbing if various macro definition
1336 files are included, as the resulting output would eventually contain a lot of
1337 empty lines. With the `mute` directive, the output can be suspended. While
1338 everything is still processed as normal, no output is written for the code
1339 within the `mute` directive::
1340
1341 #:mute
1342
1343 #:include "mydefs1.fypp"
1344 #:include "mydefs2.fypp"
1345
1346 #:def test(x)
1347 print *, "TEST: ${x}$"
1348 #:enddef test
1349
1350 #:endmute
1351 $:test('me')
1352
1353 The example above would only produce ::
1354
1355 print *, "TEST: me"
1356
1357 as output without any newlines.
1358
1359 The `mute` directive does not have an inline form.
1360
1361
1362 `stop` directive
1363 ================
1364
1365 The `stop` directive can be used to report an error and stop the preprocessor
1366 before all input has been consumed. This can be useful in cases, where some
1367 external conditions (e.g. user defined variables) do not meet certain
1368 criteria. The directive expects a Python expression, which will be converted to
1369 string and written to standard error. After writing the error message Fypp exits
1370 immediately with a non-zero exit code (see `Exit Codes`_)::
1371
1372 #! Stop the code if DEBUGLEVEL is not positive
1373 #:if DEBUGLEVEL < 0
1374 #:stop 'Wrong debug level {}!'.format(DEBUGLEVEL)
1375 #:endif
1376
1377 There is no inline form of the `stop` directive.
1378
1379
1380 `assert` directive
1381 ==================
1382
1383 The `assert` directive is a short form for the combination of an `if` and a
1384 `stop` directive. It evaluates a given expression and stops the code if the
1385 boolean value of the result is `False`. This can be very convenient, if you want
1386 to write robust macros containing sanity checks for their arguments::
1387
1388 #:def mymacro(RANK)
1389 #! Macro only works for RANK 1 and above
1390 #:assert RANK > 0
1391 :
1392 #:enddef mymacro
1393
1394 Given the macro definition above, the macro call ::
1395
1396 $:mymacro(1)
1397
1398 would pass the `assert` directive in the third line, while the call ::
1399
1400 $:mymacro(0)
1401
1402 would cause Fypp to stop at it.
1403
1404 When the expression in an `assert` directive evaluates to `False`, Fypp reports
1405 the failed assertion (the condition, the file name and the line number) on
1406 standard error and terminates immediately with a non-zero exit code (see `Exit
1407 Codes`_).
1408
1409 There is no inline form of the `assert` directive.
1410
1411
1412 Comment directive
1413 =================
1414
1415 Comment lines can be added by using the ``#!`` preprocessor directive. The
1416 comment line (including the newlines at their end) will be ignored by the
1417 prepropessor and will not appear in the output::
1418
1419 #! This will not show up in the output
1420
1421 There is no inline form of the comment directive.
1422
1423
1424 ****************
1425 Various features
1426 ****************
1427
1428
1429 Multiline directives
1430 ====================
1431
1432 The line form of the control and eval directives can span arbitrary number of
1433 lines, if Fortran-style continuation characters are used::
1434
1435 #:if a > b &
1436 & or b > c &
1437 & or c > d
1438 $:somePythonFunction(param1, &
1439 &param2)
1440
1441 The line break at the first line must be in the expression, not in the opening
1442 delimiter characters or in the directive name. Similar to Fortran, the
1443 continuation character at the beginning of each continuation line may be left
1444 away, but then all whitespaces at the beginning of the respective continuation
1445 line will be part of the expression.
1446
1447 Inline directives must not contain any continuation lines.
1448
1449
1450 Line folding
1451 ============
1452
1453 The Fortran standard only allows source lines up to 132 characters. In order to
1454 emit standard conforming code, Fypp folds all lines in the output which it had
1455 manipulated before (all lines containing eval directives). Lines which were
1456 just copied to the output are left unaltered. The maximal line length can be
1457 chosen by the ``-l`` command line option. The indentation of the continuation
1458 lines can be tuned with the ``--indentation`` option, and the folding strategy
1459 can be selected by the ``-f`` option with following possibilities:
1460
1461 * ``brute``: Continuation lines are indented relative to the beginning of
1462 the line, and each line is folded at the maximal line position.
1463
1464 * ``simple``: Like ``brute``, but continuation lines are indented with respect
1465 of the indentation of the original line.
1466
1467 * ``smart``: Like ``simple``, but Fypp tries to fold the line at a whitespace
1468 character in order to prevent split tokens. To prevent continuation lines
1469 becoming too short, it defaults to ``simple`` if no whitespace occurs in the
1470 last third of the line.
1471
1472 The ``-F`` option can be used to turn off line folding.
1473
1474
1475 .. warning:: Fypp is not aware of the Fortran semantics of the lines it folds.
1476
1477 Fypp applies the line folding mechanically (only considering the position of the
1478 whitespace characters). Lines containing eval directives and lines within macro
1479 definitions should, therefore, not contain any Fortran style comments (started
1480 by ``!``) *within* the line, as folding within the comment would result in
1481 invalid Fortran code. For comments within such lines, Fypps comment directive
1482 (``#!``) can be used instead::
1483
1484 #:def macro()
1485 print *, "DO NOT DO THIS!" ! Warning: Line may be folded within the comment
1486 print *, "This is OK." #! Preprocessor comment is safe as it will be stripped
1487
1488 For comments starting at the beginning of the line (preceded by optional
1489 whitespace characters only) the folding is suppressed, though. This enables you
1490 to define macros with non-negligible comment lines (e.g. with source code
1491 documentation or OpenMP directives)::
1492
1493 #:def macro(DTYPE)
1494 !> This functions calculates something (version ${DTYPE}$)
1495 !! \param xx Ingoing value
1496 !! \return Some calculated value.
1497 ${DTYPE}$ function calcSomething(xx)
1498 :
1499 end function calcSomething
1500 #:enddef macro
1501
1502
1503 Escaping
1504 ========
1505
1506 If you want to prevent Fypp to interpret something as a directive, put a
1507 backslash (``\``) between the first and second delimiter character. In case of
1508 inline directives, do it for both, the opening and the closing delimiter::
1509
1510 $\: 1 + 2
1511 #\{if 1 > 2}\#
1512 @\:myMacro arg1
1513
1514 Fypp will not recognize the escaped strings as directives, but will remove the
1515 backslash between the delimiter characters in the output. If you put more than
1516 one backslash between the delimiters, only one will be removed.
1517
1518
1519 Line numbering markers
1520 ======================
1521
1522 In order to support compilers in emitting messages with correct line numbers
1523 with respect to the original source file, Fypp can put line number directives
1524 (a.k.a. line markers) in its output. This can be enabled by using the command
1525 line option ``-n``. Given a file ``test.fpp`` with the content ::
1526
1527 program test
1528 #:if defined('MPI')
1529 use mpi
1530 #:else
1531 use openmpi
1532 #:endif
1533 :
1534 end program test
1535
1536 the command ::
1537
1538 fypp -n -DMPI test.fpp
1539
1540 produces the output ::
1541
1542 # 1 "test.fpp" 1
1543 program test
1544 # 3 "test.fpp"
1545 use mpi
1546 # 7 "test.fpp"
1547 :
1548 end program test
1549
1550 If during compilation of this output an error occurred in the line ``use mpi``
1551 (e.g. the mpi module can not be found), the compiler would know that this line
1552 corresponds to line number 3 in the original file ``test.fpp`` and could emit an
1553 according error message.
1554
1555 The line numbering directives can be fine tuned with the ``-N`` option, which
1556 accepts following mode arguments:
1557
1558 * ``full``: Line numbering directives are emitted whenever lines are
1559 removed from the original source file or extra lines are added to it.
1560
1561 * ``nocontlines``: Same as full, but line numbering directives are omitted
1562 before continuation lines. (Some compilers, like the NAG Fortran compiler,
1563 have difficulties with line numbering directives before continuation lines).
1564
1565 Note: Due to a bug introduced in GFortran 5 (being also present in major
1566 versions 6), a workaround is needed for obtaining correct error messages when
1567 compiling preprocessed files with those compilers. Please use the command line
1568 option ``--line-marker-format 'gfortran5'`` in those cases.
1569
1570
1571 Scopes
1572 ======
1573
1574 Fypp uses a scope concept very similar to Pythons one. There is one global scope
1575 (like in Python modules), and temporary local scopes may be created in special
1576 cases (e.g. during macro calls).
1577
1578 The global scope is the one, which Fypp normaly uses for defining objects. All
1579 imports specified on the command line are carried out in this scope And all
1580 definitions made by the `set` and `def` directives in the processed source file
1581 defines entities in that scope, unless they appear within a `block`, a `call` or
1582 a `def` directive.
1583
1584 Addtional temporary local scopes are opened, whenever
1585
1586 * a macro defined by the `def` directive is called, or
1587
1588 * the body of the `block` or `call` directive is evaluated in order to render
1589 the text, which will be passed to the callable as argument.
1590
1591 Any entity defined in a local scope is only visible within that scope and is
1592 unaccessible once the scope has been closed. For example the code snippet::
1593
1594 #:set toupper = lambda s: s.upper()
1595 #:call toupper
1596 #:set NUMBER = 9
1597 here is the number ${NUMBER}$
1598 #:endcall toupper
1599 $:defined('NUMBER')
1600
1601 results after preprocessing in ::
1602
1603 HERE IS THE NUMBER 9
1604 False
1605
1606 as the variable ``NUMBER`` defined in the local scope is destroyed, when the
1607 scope is closed (the `endcall` directive has been reached).
1608
1609
1610 Lookup rules
1611 ------------
1612
1613 When Fypp tries to resolve a name, the lookup rules depend on the scope, in
1614 which the query appears:
1615
1616 * global scope (outside of any `def` or `call` directives): only the global
1617 scope is searched.
1618
1619 * local scope (within the body of a `call` or `def` directive): first, the
1620 active local scope is searched. Then the scope embedding it (the scope which
1621 contains the directive) is searched. Then further embedding scopes are
1622 searched until finally also the global scope has been checked. The search is
1623 immediately terminated, if the name has been found in a scope.
1624
1625 Note, that all variables outside of the active scope are read-only. If a
1626 variable with the same name is created in the active scope, it will shadow the
1627 original definition. Once the scope is closed, the variable regains it original
1628 value. For example::
1629
1630 #:set toupper = lambda s: s.upper()
1631 #:set X = 1
1632 #:call toupper
1633 #:set X = 2
1634 value ${X}$
1635 #:endcall toupper
1636 value ${X}$
1637
1638 results in ::
1639
1640 VALUE 2
1641 value 1
1642
1643 Also note, that if a name can not be resolved in the active scope during a macro
1644 evaluation, the relevant embedding scope for the next lookup is the scope, where
1645 the macro has been defined (where the `def` directive occurs), and *not* the
1646 scope, from which the macro is being called. The following snippet demonstrates
1647 this::
1648
1649 #! GLOBAL SCOPE
1650 #:set toupper = lambda s: s.upper()
1651 #:call toupper
1652 #! LOCAL SCOPE 1
1653
1654 #:def macro1()
1655 #! LOCAL SCOPE 2A
1656 value of x: ${X}$
1657 #:enddef macro1
1658
1659 #! LOCAL SCOPE 1
1660
1661 #:def macro2()
1662 #! LOCAL SCOPE 2B
1663 #:set X = 2
1664 $:macro1()
1665 #:enddef macro2
1666
1667 #! LOCAL SCOPE 1
1668 #:set X = 1
1669 $:macro2()
1670 #:endcall
1671
1672 #! GLOBAL SCOPE
1673
1674 After processing the code above one obtains ``VALUE OF X: 1``. Although in the
1675 local scope 2B, from where the macro ``macro1()`` is called, the value of X is
1676 defined to be ``2``, the relevant scopes for the lookup of X during the macro
1677 evaluation are the local scope 2A of ``macro1()`` (where the eval-directive for
1678 X is located), the local scope 1 (where the `def` directive for ``macro1()``
1679 occurs) and the global scope (which embeds local scope 1). Therefore, at the
1680 macro evaluation the value ``1`` will be substituted as this is the value of X
1681 in scope 1, and scope 1 is the first scope in the lookup order, which provides a
1682 value for X.
1683
1684
1685 Rendering file names as relative paths
1686 ======================================
1687
1688 When the input file is specified as an absolute path (e.g. during an
1689 out-of-source build), the variables ``_FILE_`` and ``_THIS_FILE_`` will also
1690 contain absolute paths. This might result in file names, which are unnecessary
1691 long and might reveal unwanted information about the directory structure on the
1692 building host.
1693
1694 The ``--file-var-root`` option converts the paths in ``_FILE_`` and
1695 ``_THIS_FILE_`` to relative paths with respect to a specified root folder.
1696 Given the file `source.fpp`::
1697
1698 [...]
1699 call fatal_error("Error in ${_FILE_}$:${_LINE_}$")
1700
1701 invoking with Fypp with ::
1702
1703 fypp /home/user/projectdir/src/source.fpp
1704
1705 results in ::
1706
1707 [...]
1708 call fatal_error("Error in /home/user/projectdir/src/source.fpp:2")
1709
1710 while using the ``--file-var-root`` option ::
1711
1712 fypp --file-var-root=/home/user/projectdir /home/user/projectdir/src/source.fpp
1713
1714 yields ::
1715
1716 [...]
1717 call fatal_error("Error in src/source.fpp:2")
1718
1719
1720 Exit codes
1721 ==========
1722
1723 When run as a standalone application, Fypp returns one of the following exit
1724 codes to the calling environment:
1725
1726 * 0: Preprocessing finished successfully.
1727
1728 * 1: Stopped due to an unexpected error.
1729
1730 * 2: Explicitely requested stop encountered (`stop directive`_ or `assert
1731 directive`_).
1732
1733
1734
1735 ********
1736 Examples
1737 ********
1738
1739 Asserts and debug code
1740 ======================
1741
1742 In this example a simple "assert"-mechanism (as can be found in many programming
1743 languages) should be implemented, where run-time checks can be included or
1744 excluded depending on preprocessor variable definitions. Apart of single
1745 assert-like queries, we also want to include larger debug code pieces, which can
1746 be removed in the production code.
1747
1748 First, we create an include file (``checks.fypp``) with the appropriate macros::
1749
1750 #:mute
1751
1752 #! Enable debug feature if the preprocessor variable DEBUG has been defined
1753 #:set DEBUG = defined('DEBUG')
1754
1755
1756 #! Stops the code, if the condition passed to it is not fulfilled
1757 #! Only included in debug mode.
1758 #:def ASSERT(cond, msg=None)
1759 #:if DEBUG
1760 if (.not. (${cond}$)) then
1761 write(*,*) 'Run-time check failed'
1762 write(*,*) 'Condition: ${cond.replace("'", "''")}$'
1763 #:if msg is not None
1764 write(*,*) 'Message: ', ${msg}$
1765 #:endif
1766 write(*,*) 'File: ${_FILE_}$'
1767 write(*,*) 'Line: ', ${_LINE_}$
1768 stop
1769 end if
1770 #:endif
1771 #:enddef ASSERT
1772
1773
1774 #! Includes code if in debug mode.
1775 #:def DEBUG_CODE(code)
1776 #:if DEBUG
1777 $:code
1778 #:endif
1779 #:enddef DEBUG_CODE
1780
1781 #:endmute
1782
1783 Remarks:
1784
1785 * All macro definitions are within a ``#:mute`` -- ``#:endmute`` pair in order to
1786 prevent the appearance of disturbing empty lines (the lines between the macro
1787 definitions) in the file which includes ``checks.fypp``.
1788
1789 * The preprocessor variable ``DEBUG`` will determine, whether the checks
1790 and the debug code is left in the preprocessed code or not.
1791
1792 * The content of both macros, ``ASSERT`` and ``DEBUG_CODE``, are only included
1793 if the variable ``DEBUG`` has been defined.
1794
1795 * We also want to print out the failed condition for more verbose output. As the
1796 condition may contains apostrophes, we use Python's string replacement method
1797 to escape them.
1798
1799 With the definitions above, we can use the functionality in any Fortran source
1800 after including ``checks.fypp``::
1801
1802 #:include 'checks.fypp'
1803
1804 module testmod
1805 implicit none
1806
1807 contains
1808
1809 subroutine someFunction(ind, uplo)
1810 integer, intent(in) :: ind
1811 character, intent(in) :: uplo
1812
1813 @:ASSERT(ind > 0, msg="Index must be positive")
1814 @:ASSERT(uplo == 'U' .or. uplo == 'L')
1815
1816 ! Do something useful here
1817 ! :
1818
1819 #:block DEBUG_CODE
1820 print *, 'We are in debug mode'
1821 print *, 'The value of ind is', ind
1822 #:endblock DEBUG_CODE
1823
1824 end subroutine someFunction
1825
1826 end module testmod
1827
1828 Now, the file ``testmod.fpp`` can be preprocessed with Fypp. When the variable
1829 ``DEBUG`` is not set::
1830
1831 fypp testmod.fpp testmod.f90
1832
1833 the resulting routine will not contain the conditional code::
1834
1835 subroutine someFunction(ind, uplo)
1836 integer, intent(in) :: ind
1837 character, intent(in) :: uplo
1838
1839
1840
1841
1842 ! Do something useful here
1843 ! :
1844
1845
1846
1847 end subroutine someFunction
1848
1849 On the other hand, if the ``DEBUG`` variable is set::
1850
1851 fypp -DDEBUG testmod.fpp testmod.f90
1852
1853 the run-time checks and the debug code will be there::
1854
1855 subroutine someFunction(ind, uplo)
1856 integer, intent(in) :: ind
1857 character, intent(in) :: uplo
1858
1859 if (.not. (ind > 0)) then
1860 write(*,*) 'Run-time check failed'
1861 write(*,*) 'Condition: ind > 0'
1862 write(*,*) 'Message: ', "Index must be positive"
1863 write(*,*) 'File: testmod.fpp'
1864 write(*,*) 'Line: ', 12
1865 stop
1866 end if
1867 if (.not. (uplo == 'U' .or. uplo == 'L')) then
1868 write(*,*) 'Run-time check failed'
1869 write(*,*) 'Condition: uplo == ''U'' .or. uplo == ''L'''
1870 write(*,*) 'File: testmod.fpp'
1871 write(*,*) 'Line: ', 13
1872 stop
1873 end if
1874
1875 ! Do something useful here
1876 ! :
1877
1878 print *, 'We are in debug mode'
1879 print *, 'The value of ind is', ind
1880
1881 end subroutine someFunction
1882
1883
1884 Generic programming
1885 ===================
1886
1887 The example below shows how to create a generic function ``maxRelError()``,
1888 which gives the maximal elementwise relative error for any pair of arrays with
1889 ranks from 0 (scalar) to 7 in single or double precision. The Fortran module
1890 (file ``errorcalc.fpp``) contains the interface ``maxRelError`` which maps to
1891 all the realizations with the different array ranks and precisions::
1892
1893 #:def ranksuffix(RANK)
1894 $:'' if RANK == 0 else '(' + ':' + ',:' * (RANK - 1) + ')'
1895 #:enddef ranksuffix
1896
1897 #:set PRECISIONS = ['sp', 'dp']
1898 #:set RANKS = range(0, 8)
1899
1900 module errorcalc
1901 implicit none
1902
1903 integer, parameter :: sp = kind(1.0)
1904 integer, parameter :: dp = kind(1.0d0)
1905
1906 interface maxRelError
1907 #:for PREC in PRECISIONS
1908 #:for RANK in RANKS
1909 module procedure maxRelError_${RANK}$_${PREC}$
1910 #:endfor
1911 #:endfor
1912 end interface maxRelError
1913
1914 contains
1915
1916 #:for PREC in PRECISIONS
1917 #:for RANK in RANKS
1918
1919 function maxRelError_${RANK}$_${PREC}$(obtained, reference) result(res)
1920 real(${PREC}$), intent(in) :: obtained${ranksuffix(RANK)}$
1921 real(${PREC}$), intent(in) :: reference${ranksuffix(RANK)}$
1922 real(${PREC}$) :: res
1923
1924 #:if RANK == 0
1925 res = abs((obtained - reference) / reference)
1926 #:else
1927 res = maxval(abs((obtained - reference) / reference))
1928 #:endif
1929
1930 end function maxRelError_${RANK}$_${PREC}$
1931
1932 #:endfor
1933 #:endfor
1934
1935 end module errorcalc
1936
1937 The macro ``ranksuffix()`` defined at the beginning receives a rank as argument
1938 and returns a string, which is either the empty string (rank 0) or the
1939 appropriate number of dimension placeholder separated by commas and within
1940 parantheses (e.g. ``(:,:)`` for rank 2). The string expression is calculated as
1941 a Python expression, so that we can make use of the powerful string manipulation
1942 routines in Python and write it as a one-line routine.
1943
1944 If we preprocess the Fortran source file ``errorcalc.fpp`` with Fypp::
1945
1946 fypp errorcalc.fpp errorcalc.f90
1947
1948 the resulting file ``errorcalc.f90`` will contain a module with the generic
1949 interface ``maxRelError()``::
1950
1951 interface maxRelError
1952 module procedure maxRelError_0_sp
1953 module procedure maxRelError_1_sp
1954 module procedure maxRelError_2_sp
1955 module procedure maxRelError_3_sp
1956 module procedure maxRelError_4_sp
1957 module procedure maxRelError_5_sp
1958 module procedure maxRelError_6_sp
1959 module procedure maxRelError_7_sp
1960 module procedure maxRelError_0_dp
1961 module procedure maxRelError_1_dp
1962 module procedure maxRelError_2_dp
1963 module procedure maxRelError_3_dp
1964 module procedure maxRelError_4_dp
1965 module procedure maxRelError_5_dp
1966 module procedure maxRelError_6_dp
1967 module procedure maxRelError_7_dp
1968 end interface maxRelError
1969
1970 The interface maps to the appropriate functions::
1971
1972 function maxRelError_0_sp(obtained, reference) result(res)
1973 real(sp), intent(in) :: obtained
1974 real(sp), intent(in) :: reference
1975 real(sp) :: res
1976
1977 res = abs((obtained - reference) / reference)
1978
1979 end function maxRelError_0_sp
1980
1981
1982 function maxRelError_1_sp(obtained, reference) result(res)
1983 real(sp), intent(in) :: obtained(:)
1984 real(sp), intent(in) :: reference(:)
1985 real(sp) :: res
1986
1987 res = maxval(abs((obtained - reference) / reference))
1988
1989 end function maxRelError_1_sp
1990
1991
1992 function maxRelError_2_sp(obtained, reference) result(res)
1993 real(sp), intent(in) :: obtained(:,:)
1994 real(sp), intent(in) :: reference(:,:)
1995 real(sp) :: res
1996
1997 res = maxval(abs((obtained - reference) / reference))
1998
1999 end function maxRelError_2_sp
2000
2001 :
2002
2003 The function ``maxRelError()`` can be, therefore, invoked with a pair of arrays
2004 with various ranks or with a pair of scalars, both in single and in double
2005 precision, as required.
2006
2007 If you prefer not to have preprocessor loops around long code blocks, the
2008 example above can be also written by defining a macro first and then calling
2009 the macro within the loop. The function definition would then look as follows::
2010
2011 contains
2012
2013 #:def maxRelError_template(RANK, PREC)
2014 function maxRelError_${RANK}$_${PREC}$(obtained, reference) result(res)
2015 real(${PREC}$), intent(in) :: obtained${ranksuffix(RANK)}$
2016 real(${PREC}$), intent(in) :: reference${ranksuffix(RANK)}$
2017 real(${PREC}$) :: res
2018
2019 #:if RANK == 0
2020 res = abs((obtained - reference) / reference)
2021 #:else
2022 res = maxval(abs((obtained - reference) / reference))
2023 #:endif
2024
2025 end function maxRelError_${RANK}$_${PREC}$
2026 #:enddef maxRelError_template
2027
2028 #:for PREC in PRECISIONS
2029 #:for RANK in RANKS
2030 $:maxRelError_template(RANK, PREC)
2031 #:endfor
2032 #:endfor
2033
2034 end module errorcalc
2035
2036
2037 ***********************************
2038 Integration into build environments
2039 ***********************************
2040
2041 Fypp can be integrated into build environments like any other preprocessor. If
2042 your build environment is Python-based, you may consider to access its
2043 functionality directly via its API instead of calling it as an external script
2044 (see the `API documentation`_).
2045
2046 Make
2047 ====
2048
2049 In traditional make based system you can define an appropriate preprocessor
2050 rule in your ``Makefile``::
2051
2052 .fpp.f90:
2053 fypp $(FYPPFLAGS) $< $@
2054
2055 or for GNU make::
2056
2057 %.f90: %.fpp
2058 fypp $(FYPPFLAGS) $< $@
2059
2060
2061 Waf
2062 ===
2063
2064 For the `waf` build system the Fypp source tree contains extension modules in
2065 the folder ``tools/waf``. They use Fypps Python API, therefore, the ``fypp``
2066 module must be accessible from Python. Using those waf modules, you can
2067 formulate a Fypp preprocessed Fortran build like the example below::
2068
2069 def options(opt):
2070 opt.load('compiler_fc')
2071 opt.load('fortran_fypp')
2072
2073 def configure(conf):
2074 conf.load('compiler_fc')
2075 conf.load('fortran_fypp')
2076
2077 def build(bld):
2078 sources = bld.path.ant_glob('*.fpp')
2079 bld(
2080 features='fypp fc fcprogram',
2081 source=sources,
2082 target='myprog'
2083 )
2084
2085 Check the documentation in the corresponding waf modules for further details.
2086
2087
2088 CMake
2089 =====
2090
2091 One possible way of invoking the Fypp preprocessor within the CMake build
2092 framework is demonstrated below (thanks to Jacopo Chevallard for providing the
2093 very first version of this example)::
2094
2095 ### Pre-process: .fpp -> .f90 via Fypp
2096
2097 # Create a list of the files to be preprocessed
2098 set(fppFiles file1.fpp file2.fpp file3.fpp)
2099
2100 # Pre-process
2101 foreach(infileName IN LISTS fppFiles)
2102
2103 # Generate output file name
2104 string(REGEX REPLACE ".fpp\$" ".f90" outfileName "${infileName}")
2105
2106 # Create the full path for the new file
2107 set(outfile "${CMAKE_CURRENT_BINARY_DIR}/${outfileName}")
2108
2109 # Generate input file name
2110 set(infile "${CMAKE_CURRENT_SOURCE_DIR}/${infileName}")
2111
2112 # Custom command to do the processing
2113 add_custom-command(
2114 OUTPUT "${outfile}"
2115 COMMAND fypp "${infile}" "${outfile}"
2116 MAIN_DEPENDENCY "${infile}"
2117 VERBATIM)
2118
2119 # Finally add output file to a list
2120 set(outFiles ${outFiles} "${outfile}")
2121
2122 endforeach(infileName)
2123
2124
2125 *****************
2126 API documentation
2127 *****************
2128
2129 Additional to its usage as a command line tool, Fypp can also be operated
2130 directly from Python. This can be especially practical, when Fypp is used in a
2131 Python driven build environment (e.g. waf, Scons). Below you find the detailed
2132 documentation of the API Fypp offers.
2133
2134
2135 fypp module
2136 ===========
2137
2138 .. automodule:: fypp
2139
2140
2141 Fypp
2142 ====
2143
2144 .. autoclass:: Fypp
2145 :members:
2146
2147
2148 FyppOptions
2149 ===========
2150
2151 .. autoclass:: FyppOptions
2152 :members:
2153
2154
2155 get_option_parser()
2156 ===================
2157
2158 .. autofunction:: get_option_parser()
2159
2160
2161 FyppError
2162 =========
2163
2164 .. autoclass:: FyppError
2165 :members:
2166
2167
2168 *****
2169 Notes
2170 *****
2171
2172 .. [1] I am indebted to pyratemps author Roland Koebler for some helpful
2173 discussions.
2174
2175 .. [2] Many thanks to Ivan Pribec for pointing out the similarity to C++
2176 variadic templates and bringing up the Horner scheme as example.