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)
int add(int, int b);
def add(param_0: Int32, b: Int32) -> Int32:
pass
m.def("add",
add, py::arg("param_0"), py::arg("b"));
m.def("add",
add, nb::arg("param_0"), nb::arg("b"));
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)
int AnswerToTheUltimateQuestionOfLife_TheUniverse_AndEverything() { return 42; }
# Copyright(c) 2023 - Pascal Thomet
# Yes, I claim the copyright on this magnificent function.
# ...At least, I tried...
def answer_to_the_ultimate_question_of_life_the_universe_and_everything() -> int:
pass
// Copyright(c) 2023 - Pascal Thomet
// Yes, I claim the copyright on this magnificent function.
// ...At least, I tried...
m.def("answer_to_the_ultimate_question_of_life_the_universe_and_everything",
AnswerToTheUltimateQuestionOfLife_TheUniverse_AndEverything);
// Copyright(c) 2023 - Pascal Thomet
// Yes, I claim the copyright on this magnificent function.
// ...At least, I tried...
m.def("answer_to_the_ultimate_question_of_life_the_universe_and_everything",
AnswerToTheUltimateQuestionOfLife_TheUniverse_AndEverything);