aradi / fypp

Python powered Fortran preprocessor
http://fypp.readthedocs.io
BSD 2-Clause "Simplified" License
192 stars 30 forks source link

Logical test behaves different in a def'ed macro compares to outside of macro #26

Closed oyvindyr closed 1 year ago

oyvindyr commented 1 year ago

Hi,

Thanks for a great tool! I have met a strange behaviour of a defined macro in a fypp file. If you set correct_behaviour = True in the snippet below, it evaluates a logical flag and writes "elemental" or "impure elemental" depending on the logical test outside of a macro, and writes (correctly) "elemental". If you set correct_behaviour = False it evaluates the same logical test, but this time inside of a macro. The result differs!

Is this a bug or something I am missing?

#:def mac(is_pure, test_coverage)
    #:set pure_flag = is_pure and not test_coverage
    I am in the macro
    ${is_pure}$
    ${test_coverage}$
    ${pure_flag}$
    #:if pure_flag
        #:set elemental_purity = "elemental"
    #:else
        #:set elemental_purity = "impure elemental"
    #:endif
    ${elemental_purity}$

#:enddef

#:set correct_behaviour = True

#:set is_pure = True
#:set test_coverage = False

#:if correct_behaviour

    #:set pure_flag = is_pure and not test_coverage
    ${is_pure}$
    ${test_coverage}$
    ${pure_flag}$
    #:if pure_flag
        #:set elemental_purity = "elemental"
    #:else
        #:set elemental_purity = "impure elemental"
    #:endif
    ${elemental_purity}$

#:else

    @:mac(${is_pure}$, ${test_coverage}$)

#:endif

Best regards, Øyvind

aradi commented 1 year ago

I am happy to hear, that you find fypp useful!

The reason for the "discrepancy" lies in the fact, that the direct cal with the @: prefix turns all its arguments into a string (in order to prevent the need for quotation), so you check the bool-value of a string within the macro (which is always true, if the string has any content). If you change the call to $:mac(is_pure, test_coverage), which is evaluated directly in python, you will get the same results as outside.

oyvindyr commented 1 year ago

Thank you!