Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Postprocessing and preprocessing

Header preprocessing

If you need to preprocess header code before the generation, you can create a function that transforms the source code, and store it inside options.srcmlcpp_options.code_preprocess_function

For example:

def preprocess_change_int(code: str) -> str:
    return code.replace("int", "Int32")  # This is a *very* dumb preprocessor


cpp_code = """
int add(int, int b);
"""

import litgen
from litgen.demo import litgen_demo

options = litgen.LitgenOptions()
options.srcmlcpp_options.code_preprocess_function = preprocess_change_int
litgen_demo.demo(options, cpp_code)
Loading...

Post-processing of the stub and pydef files

You can also post-process the stub and pydef files, i.e. apply a function that will be called after the code is generated. Below is a very dumb example:

cpp_code = """
int AnswerToTheUltimateQuestionOfLife_TheUniverse_AndEverything() { return 42; }
"""


from codemanip import code_utils


def postprocess_stub(code: str) -> str:
    return (
        code_utils.unindent_code(
            """
        # Copyright(c) 2023 - Pascal Thomet
        #    Yes, I claim the copyright on this magnificent function.
        #    ...At least, I tried...
        """
        )
        + code
    )


def postprocess_pydef(code: str) -> str:
    return (
        code_utils.unindent_code(
            """
        // Copyright(c) 2023 - Pascal Thomet
        //    Yes, I claim the copyright on this magnificent function.
        //    ...At least, I tried...
        """
        )
        + code
    )


options = litgen.LitgenOptions()
options.postprocess_stub_function = postprocess_stub
options.postprocess_pydef_function = postprocess_pydef
litgen_demo.demo(options, cpp_code, show_pydef=True)
Loading...