How kojix2/crython works
Main Components
• The Crystal Application Layer: This is where users embed Python code within their Crystal applications. It handles the session management (e.g., Crython.session), calling functions, and error handling.
• The Binding/Integration Layer: Represented by the “src/crython/libpython” directory, which interfaces with the Python C API (modules like “pyerrors”, “pythonrun”, “refcount”, etc.).
• The Data Type Conversion Modules: Split into two sub-components:
• Conversion from Crystal to Python – “src/crython/py2cr” (handling basic data types, collections, etc.).
• Conversion from Python to Crystal – “src/crython/cr2py” (with files like array.cr, bool.cr, complex.cr, etc.).
• The Error Management Component: Where Python exceptions are caught and converted to corresponding Crystal exceptions (“src/crython/error.cr” and parts in the libpython directory).
• Examples & Tests: Although not part of the runtime architecture, these confirm the intended usage patterns and help clarify the flow (see the “examples” and “spec” directories).
Relationships and Interactions
• The Crystal Application Layer (user code) sends requests to the high-level Crython API.
• The API then interacts with the Binding Layer to initialize or communicate with the Python interpreter.
• When data exchange is required, the system routes calls to the conversion modules (cr2py for preparing data for Python, and py2cr for bringing back Python objects as Crystal types).
• Errors generated during Python runtime are captured in the libpython or error modules and are passed back to the user’s context for handling.
• APIs such as “Crython.import”, “Crython.eval”, and the session block manage this orchestration.
Architectural Patterns & Design Principles
• Separation of Concerns: Clear division between interfacing with Python (libpython), converting data types, and providing a simple API for users.
• Layered Architecture: The user-facing API (session management, module imports) sits on top of the integration layers (conversion and binding), which in turn abstract the lower-level Python interpreter operations.
• Modular Design: Each directory and module corresponds to a distinct functionality (type conversion, error handling) that can be updated independently.