# core URL: /api/compiler/core/ Section: compiler -------------------------------------------------------------------------------- core - Kida window.BENGAL_THEME_DEFAULTS = { appearance: 'light', palette: 'brown-bengal' }; window.Bengal = window.Bengal || {}; window.Bengal.enhanceBaseUrl = '/kida/assets/js/enhancements'; window.Bengal.watchDom = true; window.Bengal.debug = false; window.Bengal.enhanceUrls = { 'toc': '/kida/assets/js/enhancements/toc.632a9783.js', 'docs-nav': '/kida/assets/js/enhancements/docs-nav.57e4b129.js', 'tabs': '/kida/assets/js/enhancements/tabs.aac9e817.js', 'lightbox': '/kida/assets/js/enhancements/lightbox.1ca22aa1.js', 'interactive': '/kida/assets/js/enhancements/interactive.fc077855.js', 'mobile-nav': '/kida/assets/js/enhancements/mobile-nav.d991657f.js', 'action-bar': '/kida/assets/js/enhancements/action-bar.d62417f4.js', 'copy-link': '/kida/assets/js/enhancements/copy-link.7d9a5c29.js', 'data-table': '/kida/assets/js/enhancements/data-table.1f5bc1eb.js', 'lazy-loaders': '/kida/assets/js/enhancements/lazy-loaders.a5c38245.js', 'holo': '/kida/assets/js/enhancements/holo.ee13c841.js', 'link-previews': '/kida/assets/js/enhancements/link-previews.8d906535.js' }; (function () { try { var defaults = window.BENGAL_THEME_DEFAULTS || { appearance: 'system', palette: '' }; var defaultAppearance = defaults.appearance; if (defaultAppearance === 'system') { defaultAppearance = (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) ? 'dark' : 'light'; } var storedTheme = localStorage.getItem('bengal-theme'); var storedPalette = localStorage.getItem('bengal-palette'); var theme = storedTheme ? (storedTheme === 'system' ? defaultAppearance : storedTheme) : defaultAppearance; var palette = storedPalette ?? defaults.palette; document.documentElement.setAttribute('data-theme', theme); if (palette) { document.documentElement.setAttribute('data-palette', palette); } } catch (e) { document.documentElement.setAttribute('data-theme', 'light'); } })(); { "prerender": [ { "where": { "and": [ { "href_matches": "/docs/*" }, { "not": { "selector_matches": "[data-external], [target=_blank], .external" } } ] }, "eagerness": "conservative" } ], "prefetch": [ { "where": { "and": [ { "href_matches": "/*" }, { "not": { "selector_matches": "[data-external], [target=_blank], .external" } } ] }, "eagerness": "conservative" } ] } Skip to main content Magnifying Glass ESC Recent Clear Magnifying Glass No results for "" Start typing to search... ↑↓ Navigate ↵ Open ESC Close Powered by Lunr )彡 DocumentationInfoAboutArrow ClockwiseGet StartedCodeSyntaxTerminalUsageNoteTutorialsStarburstExtendingBookmarkReferenceTroubleshootingReleasesDevGitHubKida API Reference Magnifying Glass Search ⌘K Palette Appearance Chevron Down Mode Monitor System Sun Light Moon Dark Palette Snow Lynx Brown Bengal Silver Bengal Charcoal Bengal Blue Bengal List )彡 Magnifying Glass Search X Close Documentation Caret Down Info About Arrow Clockwise Get Started Code Syntax Terminal Usage Note Tutorials Starburst Extending Bookmark Reference Troubleshooting Releases Dev Caret Down GitHub Kida API Reference Palette Appearance Chevron Down Mode Monitor System Sun Light Moon Dark Palette Snow Lynx Brown Bengal Silver Bengal Charcoal Bengal Blue Bengal Kida API Reference Caret Right Analysis analyzer cache config dependencies landmarks metadata purity roles Caret Right Compiler Caret Right Statements basic control_flow functions special_blocks template_structure variables _protocols coalescing core expressions utils Caret Right Environment core exceptions filters loaders protocols registry tests Caret Right Parser Caret Right Blocks control_flow core functions special_blocks template_structure variables _protocols core errors expressions statements tokens Caret Right Utils html lru_cache workers _types bytecode_cache kida lexer nodes template tstring Kida API ReferenceCompiler ᗢ Caret Down Link Copy URL External Open LLM text Copy Copy LLM text Share with AI Ask Claude Ask ChatGPT Ask Gemini Ask Copilot Module compiler.core Kida Compiler Core — main Compiler class. The Compiler transforms Kida AST into Python AST, then compiles to executable code objects. Uses a mixin-based design for maintainability. Design Principles: AST-to-AST: Generate ast.Module, not source strings StringBuilder: Output via buf.append(), join at end Local caching: Cache _escape, _str, buf.append as locals O(1) dispatch: Dict-based node type → handler lookup Performance Optimizations: LOAD_FAST for cached functions (vs LOAD_GLOBAL + hash) Method lookup cached once: _append = buf.append Single ''.join(buf) at return (vs repeated concatenation) Line markers only for error-prone nodes (Output, For, If, etc.) Block Inheritance: Templates with {% extends %} generate: Block functions: _block_header(ctx, _blocks) Render function: Registers blocks, delegates to parent def _block_header(ctx, _blocks): buf = [] # Block body... return ''.join(buf) def render(ctx, _blocks=None): if _blocks is None: _blocks = {} _blocks.setdefault('header', _block_header) return _extends('base.html', ctx, _blocks) 1Class Classes Compiler 15 ▼ Compile Kida AST to Python code objects. The Compiler transforms a Kida Template AST into an `ast.… Compile Kida AST to Python code objects. The Compiler transforms a Kida Template AST into an ast.Module, then compiles it to a code object ready for exec(). The generated code defines a render(ctx, _blocks=None) function. Node Dispatch: Uses O(1) dict lookup for node type → handler: python dispatch = { "Data": self._compile_data, "Output": self._compile_output, "If": self._compile_if, ... } handler = dispatch[type(node).__name__] Line Tracking: For nodes that can cause runtime errors (Output, For, If, etc.), injects ctx['_line'] = N before the node's code. This enables rich error messages with source line numbers. Attributes Name Type Description _env — Parent Environment (for filter/test access) _name str | None Template name for error messages _filename str | None Source file path for compile() _locals set[str] Set of local variable names (loop vars, macro args) _blocks dict[str, Any] Dict of block_name → Block node (for inheritance) _block_counter int Counter for unique variable names Methods compile 3 Any ▼ Compile template AST to code object. def compile(self, node: TemplateNode, name: str | None = None, filename: str | None = None) -> Any Parameters Name Type Description node — Root Template node name — Template name for error messages Default: None filename — Source filename for error messages Default: None Returns Any Compiled code object ready for exec() Internal Methods 8 ▼ __init__ 1 ▼ def __init__(self, env: Environment) Parameters Name Type Description env — _collect_blocks 1 ▼ Recursively collect all Block nodes from the AST. This ensures nested blocks (… def _collect_blocks(self, nodes: Any) -> None Recursively collect all Block nodes from the AST. This ensures nested blocks (blocks inside blocks, blocks inside conditionals, etc.) are all registered for compilation. Parameters Name Type Description nodes — _compile_template 1 ast.Module ▼ Generate Python module from template. def _compile_template(self, node: TemplateNode) -> ast.Module Parameters Name Type Description node — Returns ast.Module _make_block_function 2 ast.FunctionDef ▼ Generate a block function: _block_name(ctx, _blocks) -> str. def _make_block_function(self, name: str, block_node: Any) -> ast.FunctionDef Parameters Name Type Description name — block_node — Returns ast.FunctionDef _make_render_function 1 ast.FunctionDef ▼ Generate the render(ctx, _blocks=None) function. Optimization: Cache global fu… def _make_render_function(self, node: TemplateNode) -> ast.FunctionDef Generate the render(ctx, _blocks=None) function. Optimization: Cache global function references as locals for O(1) LOAD_FAST instead of O(1) LOAD_GLOBAL + hash lookup. For templates with extends: def render(ctx, _blocks=None): if _blocks is None: _blocks = {} # Register child blocks _blocks.setdefault('name', _block_name) # Render parent with blocks return _extends('parent.html', ctx, _blocks) Parameters Name Type Description node — Returns ast.FunctionDef _make_line_marker 1 ast.stmt ▼ Generate ctx['_line'] = lineno statement for error tracking. def _make_line_marker(self, lineno: int) -> ast.stmt Parameters Name Type Description lineno — Returns ast.stmt _compile_node 1 list[ast.stmt] ▼ Compile a single AST node to Python statements. Complexity: O(1) type dispatch… def _compile_node(self, node: Any) -> list[ast.stmt] Compile a single AST node to Python statements. Complexity: O(1) type dispatch using class name lookup. For nodes that can cause runtime errors, injects a line marker statement (ctx['_line'] = N) before the node's code. This enables rich error messages with source line numbers. Parameters Name Type Description node — Returns list[ast.stmt] _get_node_dispatch 0 dict[str, Callable] ▼ Get node type dispatch table (cached on first call). def _get_node_dispatch(self) -> dict[str, Callable] Returns dict[str, Callable] ← Previous compiler Next → expressions List © 2026 Kida built in ᓚᘏᗢ { "linkPreviews": { "enabled": true, "hoverDelay": 200, "hideDelay": 150, "showSection": true, "showReadingTime": true, "showWordCount": true, "showDate": true, "showTags": true, "maxTags": 3, "includeSelectors": [".prose"], "excludeSelectors": ["nav", ".toc", ".breadcrumb", ".pagination", ".card", "[class*='-card']", ".tab-nav", "[class*='-widget']", ".child-items", ".content-tiles"], "allowedHosts": [], "allowedSchemes": ["https"], "hostFailureThreshold": 3 } } window.BENGAL_LAZY_ASSETS = { tabulator: '/kida/assets/js/tabulator.min.js', dataTable: '/kida/assets/js/data-table.js', mermaidToolbar: '/kida/assets/js/mermaid-toolbar.9de5abba.js', mermaidTheme: '/kida/assets/js/mermaid-theme.344822c5.js', graphMinimap: '/kida/assets/js/graph-minimap.ff04e939.js', graphContextual: '/kida/assets/js/graph-contextual.355458ba.js' }; window.BENGAL_ICONS = { close: '/kida/assets/icons/close.911d4fe1.svg', enlarge: '/kida/assets/icons/enlarge.652035e5.svg', copy: '/kida/assets/icons/copy.3d56e945.svg', 'download-svg': '/kida/assets/icons/download.04f07e1b.svg', 'download-png': '/kida/assets/icons/image.c34dfd40.svg', 'zoom-in': '/kida/assets/icons/zoom-in.237b4a83.svg', 'zoom-out': '/kida/assets/icons/zoom-out.38857c77.svg', reset: '/kida/assets/icons/reset.d26dba29.svg' }; Arrow Up -------------------------------------------------------------------------------- Metadata: - Word Count: 1194 - Reading Time: 6 minutes