### Install litgen using pip Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/01_10_00_quickstart.html Installs the litgen package using pip. Supports installation from PyPI or directly from the development version on GitHub. ```bash pip install litgen ``` ```bash pip install "litgen@git+https://github.com/pthom/litgen" ``` -------------------------------- ### Install Development Requirements Source: https://github.com/pthom/litgen/blob/main/Build.md Installs the development dependencies listed in the 'requirements-dev.txt' file using pip. This ensures all necessary tools for development are available. ```bash pip install -r requirements-dev.txt ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/pthom/litgen/blob/main/Build.md Installs the pre-commit hooks for the repository. This automates code quality checks before each commit. ```bash pre-commit install ``` -------------------------------- ### Python Stub Code (.pyi) Example Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/01_10_00_quickstart.html Example of Python stub code (.pyi) generated by Litgen. This file contains type hints and function signatures for Python, aiding in static analysis and IDE support. It defines a function 'add' and a class 'Point'. ```python def add(a: int, b: int) -> int: pass class Point: x: int = 0 y: int = 0 def __init__(self, x: int = 0, y: int = 0) -> None: """Auto-generated default constructor with named params""" pass ``` -------------------------------- ### Install Integration Test Library in Editable Mode Source: https://github.com/pthom/litgen/blob/main/Build.md Navigates to the integration test directory, installs the library in editable mode, and then returns to the original directory. This makes the integration test library available for development. ```bash cd src/litgen/integration_tests pip install -v -e . cd - ``` -------------------------------- ### Profiling with Snakeviz Source: https://github.com/pthom/litgen/blob/main/Build.md Installs snakeviz, profiles a Python script using cProfile, and visualizes the results. This helps in identifying performance bottlenecks. ```bash pip install snakeviz python -m cProfile -o profile.prof your_test.py snakeviz profile.prof ``` -------------------------------- ### Build and Install srcML from Source Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/20_20_00_install_srcml.html Clones the srcML repository, creates a build directory, configures the build using CMake, compiles the project with parallel jobs, and installs it system-wide. ```bash git clone https://github.com/pthom/srcML.git \-b develop_fix_build mkdir \-p build && cd build cmake ../srcML && make \-j sudo make install ``` -------------------------------- ### Generated C++ binding code (.cpp) Source: https://github.com/pthom/litgen/blob/main/litgen-book/01_10_00_quickstart.md Example of generated C++ binding code for the 'mylib.h' header, intended for use with a Python binding library like pybind11. It defines the 'add' function and the 'Point' class. ```cpp m.def("add", add, py::arg("a"), py::arg("b")); auto pyClassPoint = py::class_ (m, "Point", "") .def(py::init<>([]( int x = 0, int y = 0) { auto r_ctor_ = std::make_unique(); r_ctor_->x = x; r_ctor_->y = y; return r_ctor_; }) , py::arg("x") = 0, py::arg("y") = 0 ) .def_readwrite("x", &Point::x, "") .def_readwrite("y", &Point::y, "") ; ``` -------------------------------- ### C++ Binding Code (.cpp) Example Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/01_10_00_quickstart.html Example of C++ binding code (.cpp) generated by Litgen for use with Python (e.g., Pybind11). This code defines how C++ functions and classes are exposed to Python. It includes binding for the 'add' function and the 'Point' class. ```cpp m.def("add", add, py::arg("a"), py::arg("b")); auto pyClassPoint = py::class_< Point >(m, "Point", "") .def(py::init<>()([](int x = 0, int y = 0) { auto r_ctor_ = std::make_unique(); r_ctor_->x = x; r_ctor_->y = y; return r_ctor_; }) , py::arg("x") = 0, py::arg("y") = 0 ) .def_readwrite("x", &Point::x, "") .def_readwrite("y", &Point::y, ""); ``` -------------------------------- ### Install srcML from Pre-compiled Binaries (Ubuntu) Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/_sources/20_20_00_install_srcml.md This snippet shows how to download and install a pre-compiled .deb package of srcML on Ubuntu 20.04. It utilizes `wget` to fetch the package and `dpkg` to install it. Ensure you have the correct URL for the desired version. ```bash wget http://131.123.42.38/lmcrs/v1.0.0/srcml_1.0.0-1_ubuntu20.04.deb sudo dpkg -i srcml_1.0.0-1_ubuntu20.04.deb ``` -------------------------------- ### Set up Development Environment Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/_sources/litgen_template/README.md Steps to set up a virtual environment and install development requirements for the project. This includes creating a virtual environment using venv and installing necessary packages like litgen, pybind11, nanobind, pytest, black, and mypy from a requirements file. ```bash python3 -m venv venv source venv/bin/activate ``` ```bash pip install -r requirements-dev.txt ``` -------------------------------- ### Install srcML from pre-compiled binaries (Ubuntu) Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/20_20_00_install_srcml.html This snippet shows how to download and install a pre-compiled .deb package of srcML on Ubuntu 20.04. It uses `wget` to download the package and `dpkg` to install it. Ensure you have the correct URL for the .deb file. ```bash wget http://131.123.42.38/lmcrs/v1.0.0/srcml_1.0.0-1_ubuntu20.04.deb sudo dpkg \-i srcml_1.0.0-1_ubuntu20.04.deb ``` -------------------------------- ### Install litgen Locally with Pip Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/01_05_00_install_or_online.html This command installs the litgen package from its GitHub repository using pip. It ensures you have the latest version integrated into your Python environment for local use. After installation, follow the quickstart guide for further setup. ```bash pip install "litgen@git+https://github.com/pthom/litgen" ``` -------------------------------- ### Run litgen to generate bindings Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/01_10_00_quickstart.html A Python script that initializes litgen and its options. This serves as the entry point for generating code from C++ headers. ```python # file: generate.py import litgen options = litgen.LitgenOptions() ``` -------------------------------- ### Install litgen in Editable Mode Source: https://github.com/pthom/litgen/blob/main/Build.md Installs the litgen package in editable mode using pip. This allows for development changes to be reflected immediately without reinstallation. ```bash pip install -v -e . ``` -------------------------------- ### Install and Install pre-commit Hooks Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/_sources/litgen_template/README.md Installs the pre-commit tool and activates its hooks for the current repository. Pre-commit helps automate code checks before committing. ```bash pip install pre-commit pre-commit install ``` -------------------------------- ### Install and Use Python Bindings Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/_sources/litgen_template/README.md Instructions for end-users to install the Python package from source and then import and use it in their Python scripts. This involves cloning the repository, installing the package using pip, and importing the generated module. ```bash git clone https://github.com/pthom/litgen_template.git && cd litgen_template pip install -v . ``` ```python import daft_lib daft_lib.add(1, 2) ``` -------------------------------- ### Install and Run Pytest: Python Test Framework Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/_sources/litgen_template/README.md Installs the Pytest framework for running Python tests. After installation, Pytest can be executed to discover and run tests in the project. Configuration is managed via pytest.ini. ```bash pip install pytest pytest ``` -------------------------------- ### Regex String Matching Examples Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/02_03_00_options.html Demonstrates the usage of regex strings for matching patterns in litgen options. It shows how to match specific strings, use alternatives with '|', and the behavior of an empty string. ```python # Matches everything mystring = ".*" # Multiple alternatives myalternatives = r"^YourFunctionName$|_private$" ``` -------------------------------- ### Install and Run Ruff: Python Linter and Formatter Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/_sources/litgen_template/README.md Installs the Ruff tool for linting and formatting Python code. It can then be executed to check the entire project directory. ```bash pip install ruff ruff . ``` -------------------------------- ### Python Pimpl Example File Generation Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/unused_20_10_00_pimpl_my_class.html This Python code snippet utilizes the 'srcmlcpp_tools' library to generate example C++ and header files for Pimpl implementation. It demonstrates how to create and display these generated files. ```python from srcmlcpp_tools import pimpl_my_class cpp_file, header_file = pimpl_my_class.create_pimpl_example_files() litgen_demo.show_cpp_file(cpp_file) litgen_demo.show_cpp_file(header_file) ``` -------------------------------- ### Cloning and Installing Package from Source (Shell) Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/litgen_template/README.html Instructions for end-users to clone the repository and install the Python package directly from the source directory using pip. ```shell git clone https://github.com/pthom/litgen_template.git && cd litgen_template pip install -v . ``` -------------------------------- ### Virtual Environment Setup (Shell) Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/litgen_template/README.html Commands to create and activate a Python virtual environment for development. This isolates project dependencies. ```shell python3 -m venv venv source venv/bin/activate ``` -------------------------------- ### Build srcML from Source (Linux/macOS) Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/_sources/20_20_00_install_srcml.md This snippet outlines the process to clone the srcML repository, configure the build using CMake, compile the source code, and install it. It uses a specific branch (`develop_fix_build`) known to have compilation fixes. The `make -j` command speeds up compilation by using multiple jobs. ```bash git clone https://github.com/pthom/srcML.git -b develop_fix_build mkdir -p build && cd build cmake ../srcML && make -j sudo make install ``` -------------------------------- ### Install lg-mylib Pip Package Source: https://github.com/pthom/litgen/blob/main/src/litgen/integration_tests/Readme.md Command to install the Python binding library 'lg-mylib' using pip. The '-e' flag allows for editable installs. ```bash pip install [-e] . ``` -------------------------------- ### Python Usage Example Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/litgen_template/README.html Demonstrates how end-users would import and use the generated Python module. This involves importing the module and calling a sample function. ```python import daft_lib daft_lib.add(1, 2) ``` -------------------------------- ### Run litgen demo with options in Python Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/02_05_00_headers.html This Python snippet demonstrates how to initialize LitgenOptions and run the litgen demo function. It requires the litgen library to be installed and assumes the `cpp_code` variable is defined elsewhere. ```python from litgen.demo import litgen_demo options = litgen.LitgenOptions() litgen_demo.demo(options, cpp_code) ``` -------------------------------- ### Install srcML Dependencies on Ubuntu Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/20_20_00_install_srcml.html Installs the required packages for building srcML on Ubuntu systems. These packages include development libraries for archive, ANTLR, XML, XSLT, and cURL. ```bash sudo apt-get install libarchive-dev antlr libxml2-dev libxslt-dev libcurl4-openssl-dev ``` -------------------------------- ### Install and Run Black: Python Code Formatter Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/_sources/litgen_template/README.md Installs the Black code formatter for Python. After installation, it can be run to automatically format Python code within the project directory. ```bash pip install black black . ``` -------------------------------- ### Python: Example Code for Documentation Generation Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/08_10_00_custom_bindings.html This is an example of Python code structure intended for documentation generation, possibly by a tool like litgen. It includes classes, methods, and functions with type hints and docstrings. It demonstrates how to define a submodule and global functions. ```python # class root_ns: # Proxy class that introduces typings for the *submodule* root_ns pass # (This corresponds to a C++ namespace. All methods are static!) class Foo: m_value: int = 0 def __init__(self, m_value: int = 0) -> None: """Auto-generated default constructor with named params""" pass def get_value(self) -> int: """Get the value""" ... def set_value(self, value: int) -> None: """Set the value""" ... @staticmethod # We **must** use @staticmethod here def foo_namespace_function() -> int: """A custom function in the submodule""" ... # def global_function() -> int: """A custom function in the main module""" ... ``` -------------------------------- ### Customize litgen options for code generation Source: https://github.com/pthom/litgen/blob/main/litgen-book/01_10_00_quickstart.md Demonstrates how to customize litgen's behavior using LitgenOptions. It shows how to exclude functions by name using regex and how to add custom methods to classes. ```python options.fn_exclude_by_name__regex = r"^_" ``` ```python options.custom_bindings.add_custom_bindings_to_class( "Point", stub_code="def norm(self) -> float: ...", pydef_code="LG_CLASS.def(\"norm\", [](const Point& p){ return sqrt(p.x*p.x + p.y*p.y); });" ) ``` -------------------------------- ### Create Python Virtual Environment Source: https://github.com/pthom/litgen/blob/main/Build.md Creates a Python virtual environment named 'venv' using Python 3.10 or higher and activates it. This isolates project dependencies. ```bash python3 -m venv venv # At least python 3.10 source venv/bin/activate ``` -------------------------------- ### pybind11 C++ Binding Code for Python Functions Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/02_00_00_first_steps.html Example pybind11 code to expose Python functions 'add' and 'sub' to C++. It defines arguments and docstrings for the exposed functions. ```cpp m.def("add", Add, py::arg("x"), py::arg("y") = 2, "Adds two integers"); m.def("sub", Sub, py::arg("x"), py::arg("y") = 2, "Substract two integers"); ``` -------------------------------- ### Build Project with CMake Source: https://github.com/pthom/litgen/blob/main/Build.md Compiles the C++ CMake project. This process regenerates and recompiles bindings for integration tests each time. ```bash mkdir build && cd build cmake .. make ``` -------------------------------- ### Final Module Setup Source: https://github.com/pthom/litgen/blob/main/src/litgen/integration_tests/CMakeLists.txt Calls the `litgen_setup_module` function to finalize the setup of the Python module. This function likely handles linking the native library, setting up packaging, and potentially generating stub files. ```cmake litgen_setup_module( ${bound_library} ${python_native_module_name} ${python_wrapper_module_name} ${CMAKE_CURRENT_LIST_DIR}/_stubs ) ``` -------------------------------- ### Run All Development Checks Source: https://github.com/pthom/litgen/blob/main/Build.md Executes a script that runs all development checks, including mypy, black, ruff, and pytest. This ensures code quality and correctness. ```bash ./ci_scripts/devel/run_all_checks.sh ``` -------------------------------- ### Define C++ header for litgen Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/01_10_00_quickstart.html Defines a simple C++ header file ('mylib.h') with an inline function and a struct. This header will be used as input for litgen to generate bindings. ```cpp // file: mylib.h #pragma once inline int add(int a, int b) { return a + b; } struct Point { int x = 0; int y = 0; }; ``` -------------------------------- ### Litgen Namespace Handling Example (Python & C++) Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/_sources/08_05_00_namespaces.ipynb This example showcases Litgen's namespace processing capabilities. It includes C++ code with various namespace scenarios (root, details, anonymous, nested, duplicate) and Python code to configure Litgen options like `namespaces_root` and `python_run_black_formatter`. The `litgen_demo.demo` function processes the C++ code based on the provided options. ```python cpp_code = """ void FooRoot(); // A function in the root namespace namespace details // This namespace should be excluded (see options.namespace_exclude__regex) { void FooDetails(); } namespace // This anonymous namespace should be excluded { void LocalFunction(); } // This namespace should not be outputted as a submodule, // since it is present in options.namespaces_root namespace Main { // this is an inner namespace (this comment should become the namespace doc) namespace Inner { void FooInner(); } // This is a second occurrence of the same inner namespace // The generated python module will merge these occurrences // (and this comment will be ignored, since the Inner namespace already has a doc) namespace Inner { void FooInner2(); } } """ import litgen from litgen.demo import litgen_demo options = litgen.LitgenOptions() options.namespaces_root = ["Main"] # options.namespace_exclude__regex = r"[Ii]nternal|[Dd]etail" # this is the default! options.python_run_black_formatter = True # options.python_convert_to_snake_case = False # uncomment this in order to keep the original namespaces and functions names litgen_demo.demo(options, cpp_code) ``` -------------------------------- ### C++ binding code (.cpp) generated by litgen Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/_sources/01_10_00_quickstart.md The generated C++ source file containing pybind11 bindings. This code links the C++ functions and classes to Python, enabling them to be called from Python scripts after compilation. ```cpp m.def("add", add, py::arg("a"), py::arg("b")); auto pyClassPoint = py::class_ (m, "Point", "") .def(py::init<>([]( int x = 0, int y = 0) { auto r_ctor_ = std::make_unique(); r_ctor_->x = x; r_ctor_->y = y; return r_ctor_; }) , py::arg("x") = 0, py::arg("y") = 0 ) .def_readwrite("x", &Point::x, "") .def_readwrite("y", &Point::y, "") ; ``` -------------------------------- ### Demonstrate Litgen Code Generation with Options (Python) Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/03_05_00_code_layout.html This Python snippet demonstrates how to use the Litgen library to generate code. It shows the initialization of LitgenOptions, setting various C++ and Python generation configurations, and then calling the demo function with these options and sample C++ code. The `litgen_demo.demo` function is the core of this example, taking options, C++ code, and a flag to show Python definitions. ```python import litgen from litgen.demo import litgen_demo options = litgen.LitgenOptions() cpp_code = """ int add(int a, int b); // Adds two numbers """ options.cpp_indent_with_tabs = True # The C++ code will be indented with options.cpp_indent_size = 1 # one tab options.python_indent_size = 2 # The python code will be indented with 2 spaces options.python_run_black_formatter = False # (if black is disabled) options.original_signature_flag_show = True # We will show the original C++ signatures in the python stubs litgen_demo.demo(options, cpp_code, show_pydef=True) ``` -------------------------------- ### JavaScript for Copying Code Snippet Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/02_00_00_first_steps.html This JavaScript function, `copy_code_1757527553388_106`, copies a predefined C++ code snippet to the user's clipboard. It utilizes the `navigator.clipboard.writeText` API. The snippet itself is a nanobind C++ binding example. ```javascript function copy_code_1757527553388_106() { let code = \`//////////////////// //////////////////// auto pyClassBoxedBool = nb::class\_ (m, \"BoxedBool\", \"\") .def\_rw(\"value\", &BoxedBool::value, \"\") .def(nb::init(), nb::arg(\"v\" ) = false) .def(\"\_\_repr\_\_", &BoxedBool::\_\_repr\_\_) ; //////////////////// //////////////////// m.def(\"switch\_bool\_value\", [](BoxedBool & v) { auto SwitchBoolValue_adapt_modifiable_immutable = [](BoxedBool & v) { bool & v_boxed_value = v.value; SwitchBoolValue(v_boxed_value); }; SwitchBoolValue_adapt_modifiable_immutable(v); }, nb::arg(\"v\" ), \" changes the value of the bool parameter (passed by modifiable reference)\ (This function will use a BoxedBool in the python code, so that its value can be modified)\"); \`; navigator.clipboard.writeText(code); } ``` -------------------------------- ### Configure Litgen Options - Add Custom Method Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/01_10_00_quickstart.html Example of adding a custom method to a generated class in Litgen. This involves defining both the Python stub code and the C++ implementation for the new method. The example shows adding a 'norm' method to the 'Point' class. ```python options.custom_bindings.add_custom_bindings_to_class( "Point", stub_code="def norm(self) -> float: ...", pydef_code="LG_CLASS.def(\"norm\", [](const Point& p){ return sqrt(p.x*p.x + p.y*p.y); });" ) ``` -------------------------------- ### Python stub code with custom method generated by litgen Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/_sources/01_10_00_quickstart.md The updated Python stub code for the 'Point' class, now including the custom 'norm' method. This reflects the modifications made using litgen's custom binding capabilities. ```python class Point: x: int = 0 y: int = 0 def __init__(self, x: int = 0, y: int = 0) -> None: """Auto-generated default constructor with named params""" pass def norm(self) -> float: ... ``` -------------------------------- ### List Available Justfile Commands Source: https://github.com/pthom/litgen/blob/main/src/litgen/integration_tests/Readme.md The justfile at the top of the repository provides a set of commands for building and running integration tests. Use 'just -l' to list all available recipes. ```bash just -l ``` -------------------------------- ### Python/C++: Pybind11 Binding Example Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/02_05_00_headers.html This snippet demonstrates a basic pybind11 binding for C++ code. It shows how to define a function 'foo' that can be called from Python. This requires the pybind11 library to be installed and configured for C++ compilation. ```c++ // #ifndef MY_HEADER_H m.def("foo", Foo); // #endif ``` -------------------------------- ### Configure Litgen Options - Exclude Functions Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/01_10_00_quickstart.html Example of configuring Litgen options in Python to exclude functions whose names match a regular expression. This allows for finer control over code generation by skipping specific functions. ```python options.fn_exclude_by_name__regex = r"^_" ``` -------------------------------- ### Configure Code Kernel and Editor Settings (JSON) Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/01_05_00_install_or_online.html This JSON configuration object sets up parameters for a code kernel and a code editor. It specifies whether a kernel is requested, binder options for repository integration, CodeMirror editor configuration (theme and mode), and kernel options including name and path. It also includes a flag for predefined output. ```json { "requestKernel": true, "binderOptions": { "repo": "binder-examples/jupyter-stacks-datascience", "ref": "master" }, "codeMirrorConfig": { "theme": "abcdef", "mode": "python" }, "kernelOptions": { "name": "python3", "path": "./." }, "predefinedOutput": true } ``` -------------------------------- ### Python: Jupyter Kernel Configuration Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/02_00_00_first_steps.html This Python code snippet configures a Jupyter kernel for use within a binder environment. It specifies the repository, branch, and specific configuration for CodeMirror and the kernel itself. This is useful for setting up reproducible computational environments. ```python { "requestKernel": true, "binderOptions": { "repo": "binder-examples/jupyter-stacks-datascience", "ref": "master", }, "codeMirrorConfig": { "theme": "abcdef", "mode": "python" }, "kernelOptions": { "name": "python3", "path": "./." }, "predefinedOutput": true } kernelName = 'python3' ``` -------------------------------- ### Configure litgen to exclude functions by regex Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/_sources/01_10_00_quickstart.md An example of modifying litgen options to exclude C++ functions from code generation if their names match a specified regular expression. This allows for finer control over which parts of the C++ code are exposed to Python. ```python options.fn_exclude_by_name__regex = r"^_" ``` -------------------------------- ### C++: Nanobind Example for Python Bindings Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/05_05_00_functions.html This C++ code snippet utilizes the nanobind library to create Python bindings for C++ functions. It defines two functions, 'priv_set_options' and 'set_options', making them accessible from Python. This requires the nanobind library to be installed and configured. ```cpp #include #include namespace nb = nanobind; using namespace nb::literals; struct PrivateOptions {}; void priv_SetOptions(int v) { // Implementation } void SetOptions(int options, const PrivateOptions& private_options = PrivateOptions()) { // Implementation } NB_MODULE(litgen, m) { m.def("priv_set_options", &priv_SetOptions, nb::arg("v")); m.def("set_options", &SetOptions, nb::arg("options"), nb::arg("private_options") = PrivateOptions()); } ``` -------------------------------- ### Python stub code (.pyi) generated by litgen Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/_sources/01_10_00_quickstart.md The generated Python stub file, which provides type hints and function signatures for the C++ code. This file aids in static analysis and autocompletion within Python development environments. ```python def add(a: int, b: int) -> int: pass class Point: x: int = 0 y: int = 0 def __init__(self, x: int = 0, y: int = 0) -> None: """Auto-generated default constructor with named params""" pass ``` -------------------------------- ### Install srcML Dependencies on macOS Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/20_20_00_install_srcml.html Installs the required packages for building srcML on macOS systems using Homebrew. It installs the ANTLR2 parser generator and the Boost C++ libraries. ```bash brew install antlr2 boost ``` -------------------------------- ### Python: Download and display litgen/options.py content Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/_sources/02_03_00_options.ipynb This Python snippet downloads the content of the litgen options file from a URL and displays it. It utilizes `code_utils.download_url_content` for fetching and `litgen_demo.show_python_code` for presentation. No specific inputs are taken, and the output is a displayed Python code block. ```python from codemanip import code_utils from litgen.demo import litgen_demo litgen_options_code = code_utils.download_url_content( "https://raw.githubusercontent.com/pthom/litgen/main/src/litgen/options.py" ) litgen_demo.show_python_code(litgen_options_code, title="litgen/options.py") ``` -------------------------------- ### Generate Python stub and C++ binding code with litgen Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/_sources/01_10_00_quickstart.md A Python script that utilizes the litgen library to process a C++ header file ('mylib.h') and generate both Python stub code (.pyi) and C++ binding code (.cpp). It then prints the generated code to the console. ```python # file: generate.py import litgen options = litgen.LitgenOptions() gen = litgen.generate_code_for_file(options, "mylib.h") print("===================================") print("=== Generated stub code (.pyi) ===") print("===================================") print(gen.stub_code) print() print("===================================") print("=== Generated pydef code (.cpp) ===") print("===================================") print(gen.pydef_code) ``` -------------------------------- ### Install and Run Mypy: Static Type Checker for Python Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/_sources/litgen_template/README.md Installs the Mypy static type checker for Python. After installation, it can be run to analyze Python code for type errors. Configuration is managed via mypy.ini. ```bash pip install mypy mypy ``` -------------------------------- ### Demonstrate Binding Generation with Options Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/_sources/02_00_00_first_steps.ipynb Demonstrates the generation of C++ bindings and Python stubs using litgen, with an option to show the C++ binding code (`show_pydef=True`). This function is useful for visualizing the generated code directly. ```python from litgen.demo import litgen_demo litgen_demo.demo(options, cpp_code, show_pydef=True) ``` -------------------------------- ### Generate C++ Bindings with litgen Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/02_00_00_first_steps.html This snippet shows how to use the litgen library to generate C++ binding code and Python declarations from C++ source code. It involves importing the library, creating an instance of `LitgenOptions`, defining the C++ code to be processed, and then calling `litgen.generate_code` to produce the bindings. The generated code is stored in the `generated_code` variable. ```python # Import litgen import litgen # Instantiate some options options = litgen.LitgenOptions() # Code for which we will emit bindings cpp_code = """ // Mathematic operations // Adds two integers int Add(int x, int y = 2); int Sub(int x, int y = 2); // Substract two integers """ # Run the generator generated_code = litgen.generate_code(options, cpp_code) ``` -------------------------------- ### Install Package in Editable Mode Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/litgen_template/README.html Installs the Python package in editable mode, allowing for quick iteration on C++ code changes without full reinstallation. This requires pip and a Python environment. ```bash pip install -e . ``` -------------------------------- ### Install and Run Pyright: Static Type Checker for Python Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/_sources/litgen_template/README.md Installs the Pyright static type checker for Python. It can then be executed to perform type checking on Python code. Configuration is handled by pyrightconfig.json. ```bash pip install pyright pyright ``` -------------------------------- ### Install Package in Editable Mode (Bash) Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/_sources/litgen_template/README.md Command to install the Python package in editable mode, allowing for direct reflection of C++ code changes without reinstallation. This is crucial for rapid development cycles. ```bash pip install -v -e . # -e stands for --editable, and -v stands for --verbose ``` -------------------------------- ### C++ Declarations for Function Exclusion Example Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/05_05_00_functions.html This snippet shows the original C++ code declarations used in the Litgen example. It includes functions and parameters that will be targeted by the exclusion rules in the Python snippet. ```cpp void priv_SetOptions(bool v); void SetOptions(const PublicOptions& options, const PrivateOptions& privateOptions = PrivateOptions()); ``` -------------------------------- ### pybind11 C++ Binding Code Example Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/05_05_00_functions.html Example of pybind11 C++ binding code that exposes Python functions to C++. This snippet demonstrates how to define Python-visible functions using pybind11's `m.def`. ```cpp m.def("generic_pybind", generic_pybind); m.def("generic_nanobind", generic_nanobind); ``` -------------------------------- ### C++ Pimpl Pattern Implementation Example Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/unused_20_10_00_pimpl_my_class.html An example of a C++ class (`MyStruct`) implementing the Pimpl pattern. It shows the private Pimpl class (`MyStructPImpl`) and the glue code that connects the public interface to the private implementation. ```cpp #include "my_class.h" struct MyStructPImpl { MyStructPImpl() { /* ...*/ } bool SomeMethod() { /* ... */ } private: bool SomePrivateMethod() { /* ... */ } int mSomePrivateMember; }; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! AUTOGENERATED CODE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // // Autogenerated code below! Do not edit! MyStruct::MyStruct() : mPImpl(std::make_unique()) { } bool MyStruct::SomeMethod() { return mPImpl->SomeMethod(); } MyStruct::~MyStruct() = default; // // Autogenerated code end // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! AUTOGENERATED CODE END !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ``` -------------------------------- ### Configure Litgen Options and Generate Bindings (Python) Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/_sources/01_05_05_online.ipynb This Python snippet configures the litgen options for code generation, including namespace handling, naming conventions, API markers, and preprocessor definitions. It then demonstrates the usage of the `litgen_demo` function to generate Python stubs and C++ bindings from C++ code. ```python import litgen from litgen.demo import litgen_demo options = litgen.LitgenOptions() # This namespace will not be outputted as a python module options.namespaces_root = ["MyNamespace"] # All functions, modules and namespaces names are converted to snake case options.python_convert_to_snake_case = True # This is an API marker in the C++ code (for shared libraries code) options.srcmlcpp_options.functions_api_prefixes = "^MY_API$" # Also create bindings for functions that do not have the API marker options.fn_exclude_non_api = False # Optional comment that can be added to non API functions options.fn_non_api_comment = "" # "Box" immutable functions parameter when they should be modifiable options.fn_params_replace_modifiable_immutable_by_boxed__regex = r".*" # Which numeric and string preprocessor do we want to export options.macro_define_include_by_name__regex = "^MY_" code = """ // This namespace is not outputed as a submodule, since it is marked as Root (see options.namespaces_root) namespace MyNamespace { // Multiplies a list of double by a given factor, returns updated list std::vector MultiplyDoubles(const std::vector& v, float k); // changes the value of the bool parameter (passed by modifiable reference) // (This function will use a BoxedBool in the python code, so that its value can be modified) void SwitchBoolValue(bool &v); // Standalone comment blocs are also exported // This function includes an API marker which will be ignored when generating the bindings MY_API int MySubstract(int a, int b); // eol doc is also included in bindings doc namespace MyMath // This namespace is not ignored and introduces a new python module { // div and mul: divide or multiply float numbers // (This comment concerns the two grouped // functions below, and will be exported as such) float Div(float a, float b); // Divide float Mul(float a, float b); // Multiply } // Stores Pixel coordinates struct Pixel { // Coordinates double x = 2., y = 3.; // Draw a pixel void Draw(Image& i); private: double _Norm(); // this will not be exported as it is private }; // This macro value be exported, as it matches the regex macro_define_include_by_name__regex #define MY_VALUE 123 } """ litgen_demo.demo( options, code, show_cpp=False, show_pydef=True, height=80 ) ``` -------------------------------- ### Python nanobind C++ Binding Example (with nb prefix) Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/05_05_00_functions.html This snippet shows a Python binding for C++ using nanobind, similar to the previous example but explicitly using the `nb` prefix for nanobind functions and arguments. ```python m.def("foo2", nb::overload_cast(foo2), nb::arg("x")); ``` -------------------------------- ### C++ Code Snippet for Type Replacement Example Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/04_05_00_names_translation.html An example C++ code declaration used to illustrate type replacement in litgen. It includes a custom template class `MyPair` and a standard type `std::vector`. ```cpp MyPair GetMinMax(std::vector& values); ``` -------------------------------- ### Python Class Initialization and Method for Options Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/02_03_00_options.html Demonstrates the initialization of a Python class for srcML C++ options and a method to retrieve API prefixes. It includes handling for various configuration flags and parsing string inputs. ```python class SrcmlcppOptions: ignored_warnings: list[WarningType] # List of ignored warnings, identified by a part of the warning message ignored_warning_parts: list[str] # Show python callstack when warnings are raised flag_show_python_callstack: bool = False # if true, display parsing progress during execution (on stdout) flag_show_progress: bool = False ################################################################################ # Workaround for https://github.com/srcML/srcML/issues/1833 ################################################################################ fix_brace_init_default_value = True ################################################################################ # ################################################################################ def __init__(self) -> None: # See doc for all the params at their declaration site (scroll up!) self.named_number_macros = {} self.ignored_warnings = [] self.ignored_warning_parts = [] def functions_api_prefixes_list(self) -> list[str]: assert isinstance(self.functions_api_prefixes, str) return split_string_by_pipe_char(self.functions_api_prefixes) def _int_from_str_or_named_number_macros(options: SrcmlcppOptions, int_str: Optional[str]) -> Optional[int]: if int_str is None: return None try: v = int(int_str) return v except ValueError: if int_str in options.named_number_macros: return options.named_number_macros[int_str] else: return None ``` -------------------------------- ### Generate Python and C++ Bindings with Litgen Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/01_10_00_quickstart.html This Python script uses the litgen library to generate stub code for Python (.pyi) and C++ binding code (.cpp) for a given header file. It prints the generated code to the console. ```python gen = litgen.generate_code_for_file(options, "mylib.h") print("===================================") print("=== Generated stub code (.pyi) ===") print("===================================") print(gen.stub_code) print() print("===================================") print("=== Generated pydef code (.cpp) ===") print("===================================") print(gen.pydef_code) ``` -------------------------------- ### Python and C++ binding example Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/11_05_00_post_processing.html Demonstrates a pybind11 binding example for a C++ function. It shows how to define a Python function that wraps a C++ function, likely for use in a Python environment. This snippet is associated with the copyright notice. ```python # 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); ``` -------------------------------- ### nanobind C++ Binding Code Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/02_00_00_first_steps.html This snippet demonstrates C++ code using the nanobind library to define Python bindings for functions 'add' and 'sub'. It specifies arguments, default values, and docstrings for the exposed functions. This is typically used for integrating C++ code with Python. ```cpp m.def("add", Add, nb::arg("x"), nb::arg("y") = 2, "Adds two integers"); m.def("sub", Sub, nb::arg("x"), nb::arg("y") = 2, "Substract two integers"); ``` -------------------------------- ### C++ nanobind Class Binding Example Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/06_05_00_classes.html This C++ code snippet shows a basic example of binding a class using nanobind. It defines a class 'Foo' and its constructor, along with a method 'HandleChoice' that accepts an argument with a default value. ```cpp pyClassFoo .def(py::init<>()) // implicit default constructor .def("handle_choice", &Foo::HandleChoice, py::arg("value") = Foo::Choice::A) ; ``` -------------------------------- ### Python: Download and display srcmlcpp_options.py content Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/_sources/02_03_00_options.ipynb This Python code downloads the srcmlcpp options file from a GitHub URL and displays it using `litgen_demo.show_python_code`. It relies on `code_utils.download_url_content` for retrieval. The output is an HTML object displaying the Python code. ```python litgen_options_code = code_utils.download_url_content( "https://raw.githubusercontent.com/pthom/litgen/main/src/srcmlcpp/srcmlcpp_options.py" ) litgen_demo.show_python_code(litgen_options_code, title="srcmlcpp/srcmlcpp_options.py") ``` -------------------------------- ### Nanobind C++ Binding Code Example Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/11_05_00_post_processing.html This snippet represents nanobind C++ binding code, specifically defining a function named 'add' with arguments 'param_0' and 'b'. It's a concise example of how nanobind is used for C++ to Python interop. ```c++ m.def("add", add, nb::arg("param\_0"), nb::arg("b")); ``` -------------------------------- ### C++: pybind11 Binding Example Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/09_05_00_preprocessor.html This is an example of C++ code using pybind11 to create Python bindings. It demonstrates how to bind C++ attributes like integers, floats, strings, and hexadecimal values to be accessible from Python. This requires the pybind11 library to be set up. ```cpp m.attr("VALUE") = 1; m.attr("FLOAT") = 1.5; m.attr("STRING") = "abc"; m.attr("HEX\_VALUE") = 0x00010009; ``` -------------------------------- ### GPL Notice for Interactive Terminal Output (Various Languages) Source: https://github.com/pthom/litgen/blob/main/LICENSE.txt This is a sample notice to be displayed by a program when it starts in interactive mode. It provides copyright information, a disclaimer of warranty, and instructions for users to view the license terms. This can be adapted for command-line programs in various languages. ```plaintext Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. ``` ```bash echo " Copyright (C) " ``` ```python print(" Copyright (C) ") print("This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.") print("This is free software, and you are welcome to redistribute it") print("under certain conditions; type `show c' for details.") ``` -------------------------------- ### C++: Example of mutable default parameter for comparison Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/05_05_00_functions.html This C++ code snippet provides an example of a mutable default parameter using `std::vector`. It is presented for comparison with Python's behavior, highlighting that default values in C++ (especially with nanobind) are typically re-evaluated per call. ```cpp void use_elems(const std::vector &elems = {}) { elems.push_back(1); std::cout << elems.size() << std::endl; } ``` -------------------------------- ### Python Class Initialization and Utility Methods Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/02_03_00_options.html Demonstrates the initialization of a class with default values and methods for retrieving string lists and converting strings to integers, handling potential errors and custom macro lookups. It includes a workaround for a specific GitHub issue. ```python class SrcmlcppOptions: fix_brace_init_default_value = True def __init__(self) -> None: # See doc for all the params at their declaration site (scroll up!) self.named_number_macros = {} self.ignored_warnings = [] self.ignored_warning_parts = [] def functions_api_prefixes_list(self) -> list[str]: assert isinstance(self.functions_api_prefixes, str) return split_string_by_pipe_char(self.functions_api_prefixes) def _int_from_str_or_named_number_macros(options: SrcmlcppOptions, int_str: Optional[str]) -> Optional[int]: if int_str is None: return None try: v = int(int_str) return v except ValueError: if int_str in options.named_number_macros: return options.named_number_macros[int_str] else: return None ``` -------------------------------- ### C++ nanobind binding for FooClass Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/02_00_00_first_steps.html Defines a C++ class 'FooClass' and binds it to Python using nanobind. This includes a constructor that takes an integer, read/write access to a public member 'mPublic', and a 'show_info' method. ```cpp auto pyClassFooClass = nb::class_ (m, "FooClass", "") .def(nb::init(), nb::arg("v")), .def_rw("m_public", &FooClass::mPublic, "") .def("show_info", &FooClass::ShowInfo) ; ``` -------------------------------- ### Litgen C++ to Python Binding Generation Example Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/05_05_00_functions.html This example shows the usage of the litgen library to generate Python bindings for C++ code. It configures litgen options to adapt mutable parameters with default values to autogenerated named constructors and then demonstrates this with a C++ code snippet containing nested structs. ```python options = litgen.LitgenOptions() options.fn_params_adapt_mutable_param_with_default_value__regex = r".*" options.fn_params_adapt_mutable_param_with_default_value__to_autogenerated_named_ctor = True litgen_demo.demo(options, cpp_code, show_pydef=False) ``` -------------------------------- ### C++ Function Declaration Example (C++) Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/03_05_00_code_layout.html This is a simple C++ function declaration that serves as an example input for code generation tools. It declares an integer function `add` that takes two integer arguments and includes a comment explaining its purpose. This snippet is often used to test or demonstrate code generation capabilities. ```cpp int add(int a, int b); // Adds two numbers ``` -------------------------------- ### Build Integration Tests for Nanobind using Justfile Source: https://github.com/pthom/litgen/blob/main/src/litgen/integration_tests/Readme.md This command builds the integration tests specifically for the nanobind library using the justfile. ```bash just build_integration_tests_nanobind ``` -------------------------------- ### Generate C++ Glue Code for Bindings Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/example_bindings/DasLib/Readme.html This C++ header file is intended to contain autogenerated glue code for C++ bindings. It includes the `` header and is marked with specific comments indicating that its content is generated and should not be modified manually. ```cpp #include // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! AUTOGENERATED CODE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // // Autogenerated code below! Do not edit! // Code will be generated here... // // Autogenerated code end // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! AUTOGENERATED CODE END !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ``` -------------------------------- ### Define Python Bindings for C++ Functions (pybind11) Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/02_00_00_first_steps.html This snippet demonstrates how to define Python bindings for C++ functions using the pybind11 library. It shows how to expose functions with default arguments and add docstrings for better Python integration. Ensure pybind11 is correctly installed and configured. ```Python m.def("add", Add, py::arg("x"), py::arg("y") \= 2, "Adds two integers"); m.def("sub", Sub, py::arg("x"), py::arg("y") \= 2, "Substract two integers"); ``` -------------------------------- ### Define Kernel Name (Python) Source: https://github.com/pthom/litgen/blob/main/docs/litgen_book/01_05_00_install_or_online.html This line of Python code defines the name of the kernel to be used. It is a simple variable assignment. ```python kernelName = 'python3' ``` -------------------------------- ### Subdirectory and Library Setup Source: https://github.com/pthom/litgen/blob/main/src/litgen/integration_tests/CMakeLists.txt Includes the `mylib_main` subdirectory to build the core C++ library named `mylib`. This library is designated as the `bound_library` for which Python bindings will be generated. ```cmake #################################################### # Build testrunner Bound C++ library #################################################### add_subdirectory(mylib/mylib_main) # Will build the library mylib set(bound_library mylib) # The library for which we are building bindings ```