|
| 1 | +# Implementation Details |
| 2 | + |
| 3 | +This document provides an overview of the internal architecture and design decisions of `jinja.cpp`. |
| 4 | + |
| 5 | +## Architecture |
| 6 | + |
| 7 | +The engine follows a standard compiler/interpreter pipeline: |
| 8 | + |
| 9 | +1. **Lexer (`Lexer` class)**: |
| 10 | + * Scans the input string. |
| 11 | + * Tokenizes Jinja delimiters `{{ ... }}`, `{% ... %}`, `{# ... #}`. |
| 12 | + * Handles whitespace control modifiers (`-`, like `{{-`) by tracking state and stripping preceding/succeeding whitespace from text tokens. |
| 13 | + * Produces a flat list of `Token`s. |
| 14 | + |
| 15 | +2. **Parser (`Parser` class)**: |
| 16 | + * Recursive Descent Parser. |
| 17 | + * Converts the valid tokens into an Abstract Syntax Tree (AST). |
| 18 | + * Handles operator precedence for expressions. |
| 19 | + * Supports: |
| 20 | + * Binary operators (`+`, `-`, `*`, `/`, `%`, `==`, `!=`, `<`, `>`, `<=`, `>=`, `and`, `or`, `in`, `not in`, `~`). |
| 21 | + * Unary operators (`not`, `-`). |
| 22 | + * Literals (String, Number, Boolean, Array, Object). |
| 23 | + * Variables and Attribute Access (`foo.bar`, `foo['bar']`). |
| 24 | + * Function Calls and Filters (`foo | filter`). |
| 25 | + * Control Structures (`for`, `if`, `set`, `macro`). |
| 26 | + |
| 27 | +3. **AST (`Node` hierarchy)**: |
| 28 | + * Base `Node` class with virtual `render(Context&, string& out)` method. |
| 29 | + * Nodes: `TextNode`, `PrintNode`, `ForStmt`, `IfNode`, `SetNode`, `MacroNode`. |
| 30 | + * Expressions (`Expr` hierarchy) evaluate to `nlohmann::json` values. |
| 31 | + |
| 32 | +4. **Interpreter / Renderer (`Template::render`)**: |
| 33 | + * Iterates through root nodes and calls `render`. |
| 34 | + * Manages `Context` (scopes, variables). |
| 35 | + |
| 36 | +## Supported Features |
| 37 | + |
| 38 | +### Filters |
| 39 | +* **`tojson(indent=None)`**: Serializes a variable to JSON string. Supports indentation. |
| 40 | +* **`safe`**: Marks a string as safe (no-op in this implementation as HTML escaping is not enforced by default, but supported for compatibility). *Note: Implicitly supported by pass-through.* |
| 41 | +* **`string`**: Converts a value to its string representation. |
| 42 | +* **`length`**: Returns the size of a list, string, or object. |
| 43 | +* **`trim`**: Removes leading and trailing whitespace from a string. |
| 44 | +* **`items`**: Returns a list of `[key, value]` pairs from a dictionary (useful for iterating over objects). |
| 45 | +* **`capitalize`**: Capitalizes the first character of a string and lowercases the rest. |
| 46 | +* **`lower`**: Converts a string to lowercase. |
| 47 | +* **`upper`**: Converts a string to uppercase. |
| 48 | +* **`map(attribute=name)`**: Extracts a specific attribute from each element in a list (e.g., `users | map(attribute='name')`). |
| 49 | + |
| 50 | +### Global Functions |
| 51 | +* **`range([start], stop, [step])`**: Generates a sequence of integers. |
| 52 | +* **`namespace(...)`**: Creates a mutable object, useful for updating variables inside loops (e.g., `set ns.i = ns.i + 1`). |
| 53 | +* **`strftime_now(format)`**: Returns the current time formatted according to the given string. |
| 54 | + |
| 55 | +### Tests (`is ...`) |
| 56 | +* **`defined`**: Checks if a variable exists. |
| 57 | +* **`undefined`**: Checks if a variable is not defined. |
| 58 | +* **`none`**: Checks if a variable is null. |
| 59 | +* **`boolean`**: Checks if a variable is a boolean. |
| 60 | +* **`string`**: Checks if a variable is a string. |
| 61 | +* **`number`**: Checks if a variable is a number. |
| 62 | +* **`sequence` / `iterable`**: Checks if a variable is a list or string. |
| 63 | +* **`mapping`**: Checks if a variable is an object/dictionary. |
| 64 | +* **`true` / `false`**: Checks boolean value. |
| 65 | + |
| 66 | +## Key Implementation Features |
| 67 | + |
| 68 | +### 1. JSON Data Model |
| 69 | +We utilize `nlohmann::json` as the unified data type for all variables. This simplifies type checking and allows easy integration with JSON-based LLM APIs. |
| 70 | + |
| 71 | +### 2. Custom Function / Filter Dispatch |
| 72 | +* **Filters**: Implemented in `FilterExpr`. Standard Jinja2 filters like `safe`, `tojson`, `trim`, `lower` are hardcoded. |
| 73 | +* **Functions**: `CallExpr` handles global functions (`range`, `namespace`) and user-registered functions. |
| 74 | +* **User Hooks**: `Template::add_function` allows users to bind C++ lambdas to Jinja function calls. |
| 75 | + |
| 76 | +### 3. `tojson` Serialization |
| 77 | +Strict control over JSON serialization is critical for chat templates (e.g., Tool definitions). |
| 78 | +We implemented a custom recursive serializer `to_json_string` (in `src/jinja.cpp`) that: |
| 79 | +* Supports indentation matching Python's generic output. |
| 80 | +* **Sorts keys** in a specific order (`type` -> `function` -> `name` -> ...) to match common LLM training data formats, ensuring high consistency. |
| 81 | + |
| 82 | +### 4. Whitespace Control |
| 83 | +Jinja2's `lstrip_blocks` and `trim_blocks` behavior is partially emulated in the Lexer. The manual whitespace stripping logic (`trim_prev`, `trim_next`) ensures that the generated prompt doesn't contain excess newlines, which can affect LLM performance. |
| 84 | + |
| 85 | +### 5. C++11 Compatibility |
| 86 | +To support a wide range of deployment environments: |
| 87 | +* Structure bindings were replaced with standard iterators. |
| 88 | +* `std::make_unique` polyfill used for C++11. |
| 89 | + |
| 90 | +## Testing Strategy |
| 91 | + |
| 92 | +* **Real Data**: We use `tests/test_chat_template.json` generated from the official Python `transformers` library on typically supported models. |
| 93 | +* **Fuzzy Matching**: For dynamic content (like dates), tests use regex normalization to ensure pass consistency across time and environments. |
0 commit comments