32 Commits
Author SHA1 Message Date
Aaron SinclairandClaude ea7dadc5ae Implement self-hosted debug console and @external decorator
This commit completes the self-hosting of Ritz's debug console and
introduces the @external decorator for elegant JavaScript bridge functions.

## Major Features

### 1. Self-Hosted Debug Console (DebugConsole.py)
- Entire debug console UI written in Ritz itself
- Signal-based state management for toggle functionality
- Displays runtime stats (memory, signals, DOM nodes, logs)
- Live reactive updates when signals change in main app
- Keyboard shortcut support (Ctrl+`)

### 2. @external Decorator for JavaScript Bridges
- Pythonic decorator syntax: @external or @bridge
- Parser automatically recognizes and tracks external functions
- Codegen emits proper LLVM declarations
- No more hacky string checks (startswith("js_"))
- Clean, declarative bridge function definitions

Example:
```python
@external
def js_toggle_debug_console():
    pass

def toggle():
    js_toggle_debug_console()  # Clean call to JS bridge
```

### 3. Enhanced RitzLoader Debug Mode
- `new RitzLoader({ debug: true })` auto-loads DebugConsole.wasm
- Keyboard shortcut registration (Ctrl+` toggle)
- Runtime stats injection (memory, signals, DOM nodes)
- Automatic status element hiding when debug enabled
- Debug console isolated in separate WASM runtime

## Bug Fixes

- Fixed reactive text node scoping (prevent global name collisions)
- Fixed CSS specificity for debug console status (use #ritz-debug)
- Fixed signal cross-contamination between runtimes (scope to rootElement)
- Fixed parser to handle expression statements in function bodies
- Fixed conditional branch rendering (append children to wrapper divs)

## Infrastructure Improvements

- Added H4 and Pre elements to syntax.py
- Parser handles @external decorator on top-level functions
- Codegen pre-collects external functions before emitting declarations
- Runtime scopes querySelector to prevent cross-runtime interference
- Debug stats update reactively on every signal change

## Files Added/Modified

New files:
- examples/runtime/DebugConsole.py - Self-hosted debug UI
- examples/runtime/DebugConsole.wasm - Compiled debug console (1.8KB)
- PHASE4_CLEANUP.md - Next phase planning document

Modified:
- ritz/parser.py - @external decorator support
- ritz/llvm_codegen_signals.py - External function handling
- ritz/syntax.py - Added external/bridge decorators, H4, Pre
- examples/runtime/ritz-runtime.js - Debug mode, stats updates
- examples/runtime/styles.css - Merged debug styles
- examples/template.html - Debug mode enabled by default
- examples/highfive/HighFive.html - Simplified using template

## Known Issues (Addressed in PHASE4_CLEANUP.md)

1. Debug console shifts page RIGHT (should shift LEFT)
2. Toggle implementation un-Ritzy (calls JS to manipulate DOM)
   - Should use reactive class binding + @event decorator
   - Needs event object bridge for keyboard events
3. Missing test infrastructure

## Next Steps (Phase 4)

See PHASE4_CLEANUP.md for detailed plan:
- Implement reactive class binding (signal-driven classes)
- Add @event decorator for declarative event registration
- Build event object bridge (access event.key, event.ctrlKey)
- Create Python test mode (execute without browser)
- Add comprehensive test suite
- Update all examples to use new patterns

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-15 18:28:24 -08:00
Aaron SinclairandClaude ddd2c03a9d Implement RitzMain() convention and Main.wasm standard
**Convention: RitzMain() entry point**
Every Ritz file now requires a `@component def RitzMain()` as the entry point.
This provides a consistent, predictable entry point for all applications.

**Universal Main.wasm output**
Build system now always outputs Main.wasm instead of ComponentName.wasm.
This means every example uses the exact same HTML boilerplate!

**Changes:**

**Codegen (llvm_codegen_signals.py):**
- Check for RitzMain component at generation time
- Error if RitzMain not found: "No RitzMain component found!"
- Always call `render_RitzMain()` from main() entry point
- Fix: Scope reactive text nodes to components (`@reactive_text_ComponentName_N_node`)
  - Prevents global name collisions when multiple components have reactive text

**Build (build.py):**
- Output Main.wasm in same directory as source file
- Output Main.ll (LLVM IR) for inspection
- Convention over configuration!

**Loader (ritz-runtime.js):**
- Auto-detect component name from WASM filename
- `new RitzLoader().load('Main.wasm')` - no second parameter needed!
- Component name used only for status messages

**Template (examples/template.html):**
- Minimal boilerplate - literally 25 lines
- Just copy and change nothing!
- Loads Main.wasm - works for every example

**Styles (examples/runtime/styles.css):**
- Shared styles for all examples
- Clean, modern defaults
- App container, buttons, inputs, typography

**Example (HighFive):**
```python
@component
def HighFive():
    # ... component logic

@component
def RitzMain():
    """Entry point - required!"""
    yield HighFive()
```

**Result:**
✅ Every example: copy template.html, change nothing
✅ Every example: builds to Main.wasm
✅ Consistent entry point: RitzMain()
✅ No more component name boilerplate

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-15 15:46:36 -08:00
Aaron SinclairandClaude 999327172e Reorganize HighFive example into highfive/ subdirectory
**Structure Before:**
examples/
  ├── HighFive.py, HighFive.html, HighFive.wasm, HighFive.ll (loose files)
  ├── highfive.html (old duplicate)
  ├── tabs/Tabs.*
  └── textinput/TextInput.*

**Structure After:**
examples/
  ├── highfive/HighFive.*
  ├── tabs/Tabs.*
  └── textinput/TextInput.*

**Changes:**
- Moved all HighFive.* files to examples/highfive/ subdirectory
- Updated paths in HighFive.html: runtime/ → ../runtime/
- Removed old duplicate highfive.html file
- Now consistent with tabs/ and textinput/ structure

**Testing:**
Access via: http://localhost:8111/highfive/HighFive.html

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-15 15:16:06 -08:00
Aaron SinclairandClaude a43b325755 Fix HighFive example paths and rebuild with latest codegen
**Bug:** HighFive.html couldn't load - "main function not found"
**Root Cause:** Incorrect paths in HTML (../runtime/ instead of runtime/)

**Fixes:**
1. Updated HighFive.html paths:
   - ../runtime/ritz-runtime.js → runtime/ritz-runtime.js
   - ../runtime/ritz-debug.js → runtime/ritz-debug.js
   - ../runtime/ritz-debug.css → runtime/ritz-debug.css

2. Rebuilt HighFive.wasm with latest codegen (includes LLVM syntax fixes)

**Result:**
✅ HighFive example now loads correctly
✅ All runtime scripts found at correct paths

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-15 15:09:37 -08:00
Aaron SinclairandClaude 7efa7786cf Fix conditional branch rendering: append children to wrapper
**Bug:** Conditional branches (match/case) rendered empty content.
- Tabs would switch but show no content in each tab
- Wrapper div was created but children never appended to it

**Root Cause:**
In `_emit_conditional_branch_function`, statements were rendered but
their return values were discarded:
```python
for stmt in body:
    self._emit_statement(stmt)  # ← return value ignored!
```

**Fix:**
Append returned elements to wrapper, just like `_emit_with` does:
```python
for stmt in body:
    child_var = self._emit_statement(stmt)
    if child_var:
        self.lines.append(f"call void @js_append_child(i32 %{wrapper_var}, i32 %{child_var})")
```

**LLVM Before:**
```llvm
%var87 = call i32 @js_create_element(...)  ; wrapper
%var89 = call i32 @js_create_element(...)  ; content
; ... build var89's children ...
ret i32 %var87  ; ← var89 never appended!
```

**LLVM After:**
```llvm
%var87 = call i32 @js_create_element(...)  ; wrapper
%var89 = call i32 @js_create_element(...)  ; content
; ... build var89's children ...
call void @js_append_child(i32 %var87, i32 %var89)  ; ← FIX!
ret i32 %var87
```

**Result:**
✅ Tabs example now shows content in each tab
✅ Vertical tabs (nested conditionals) also work

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-15 15:05:10 -08:00
Aaron SinclairandClaude 0b77c2ff3c Implement reactive text nodes & fix LLVM syntax for clang 20
**Reactive Text Nodes:**
- F-strings with signal dependencies now update automatically
- Added js_create_text_with_int() and js_update_text_with_int() for efficient "prefix{int}" pattern
- Text nodes stored in @reactive_text_N_node globals for updates
- Scan and track f-string dependencies during collection phase

**Binary Operations:**
- Implemented BinOp support in parser and codegen
- Maps Add → add i32, Sub → sub i32, Mult → mul i32, Div → sdiv i32, Mod → srem i32
- count = count + 1 now generates correct arithmetic instead of store i32 0

**LLVM Syntax Fixes (clang 20 compatibility):**
- Fixed getelementptr syntax: removed parentheses around type
- Before: getelementptr inbounds ([N x i8], [N x i8]* @str, ...)
- After:  getelementptr inbounds [N x i8], [N x i8]* @str, ...
- Created _emit_string_ptr() helper for consistent string pointer generation
- Fixed in: element creation, attribute setting, event binding, select instructions

**Runtime (ritz-runtime.js):**
- Added js_create_text_with_int(prefix, intValue) - creates text node with "prefix" + intValue
- Added js_update_text_with_int(node, prefix, intValue) - updates text content

**Result:**
✅ TextInput counter increments/decrements correctly
✅ Tabs example works (reactive attributes, conditionals)
✅ Both examples compile with clang 20

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-15 15:00:36 -08:00
Aaron SinclairandClaude d8a2e28fd5 Fix tabs onclick handlers by inlining components
**Problem:**
- HTab/VTab components received onclick as a parameter
- When binding events, codegen used parameter name "onclick" instead of actual function
- Runtime couldn't find handler function in WASM exports

**Root Cause:**
We don't support passing functions as component parameters yet. When a child
component uses onclick=onclick where onclick is a parameter, we bind the
string "onclick" instead of tracking which function was actually passed.

**Fix:**
Inlined HTab and VTab components back into parent components. Now lambdas
are directly on Button elements, so they generate proper synthetic handlers
(_lambda_0_Tabs, _lambda_1_Tabs, etc.) that get exported.

**Result:**
✅ All tab click handlers now work
✅ Handlers exported: _lambda_0_Tabs, _lambda_1_Tabs, _lambda_2_Tabs,
   _lambda_0_VerticalTabs, _lambda_1_VerticalTabs, _lambda_2_VerticalTabs

**TODO:**
Implement function pointers/delegates as component parameters to restore
component reusability (tracked in TYPE_SYSTEM_ROADMAP.md)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-15 14:41:53 -08:00
Aaron SinclairandClaude e1219ea0c1 Implement binary operations (BinOp) support
**Parser changes (parser.py):**
- Added ast.BinOp handling in _transform_expr()
- Emits: {type: "binop", left: ..., op: "Add|Sub|Mult|Div|Mod", right: ...}

**Codegen changes (llvm_codegen_signals.py):**
- Added BinOp handling in _emit_expr()
- Maps Python ops to LLVM instructions:
  - Add → add i32
  - Sub → sub i32
  - Mult → mul i32
  - Div → sdiv i32 (signed division)
  - Mod → srem i32 (signed remainder)

**Result:**
Before: count = count + 1 → store i32 0 (WRONG!)
After:  count = count + 1 → load, add i32 1, store ✓

**Still TODO:**
The counter buttons now UPDATE the signal correctly, but the display
doesn't update because f-string text nodes aren't reactive yet.
We need reactive text nodes (similar to reactive attributes).

All 55 tests passing ✓

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-15 12:18:16 -08:00
Aaron SinclairandClaude 60bbad9c68 Fix TextInput.html to use correct RitzLoader API
Changed from RitzRuntime.loadComponent() (doesn't exist) to
new RitzLoader().load() (correct API).

Also updated DOM element IDs:
- #root → #app (RitzLoader default)
- Added #status div for load status messages
- Added styling for status indicator

Should now load properly in browser.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-15 12:15:04 -08:00
Aaron SinclairandClaude 443cca5662 Add TextInput example exposing type system limitations + roadmap
Created a new example that demonstrates what we need for proper string/type support:

**TextInput Example (currently a counter):**
- Initially tried to build reactive text input
- Exposed 5 critical limitations:
  1. String signals stored as i32 (should be i8*)
  2. F-string interpolation incomplete (f"Count: {count}" → "0")
  3. No oninput event (only onclick supported)
  4. No event value passing (can't get input.value)
  5. No string operations (len, concat, etc.)

**Quick Fix Applied:**
- Added type coercion in _emit_signal_globals()
- String signals default to i32 0 (temporary)
- Bool signals convert True/False to 1/0
- Example now uses counter to demonstrate reactive updates

**TYPE_SYSTEM_ROADMAP.md:**
Complete implementation plan for proper type support:
- Phase 1: Type hints extraction (already works!)
- Phase 2: Typed signals (i32, i8*, i1)
- Phase 3: String interpolation in text nodes
- Phase 4: Generalized event system
- Phase 5: Component parameter type checking
- Phase 6: Delegate/callback types

This example will drive the type system implementation. Once complete,
text input will work with proper string signals and reactive updates.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-15 11:53:56 -08:00
Aaron SinclairandClaude 134ddc4c42 Fix duplicate append bug and componentize tabs
**Bug Fixes:**
- Fixed duplicate js_append_child calls causing DOM element re-insertion
- Elements were being appended twice: once by self-append logic, once by parent loop
- This was breaking CSS transitions on vertical tabs (elements moved in DOM)
- Removed self-append logic from _emit_with() and _emit_yield_component()

**Refactoring:**
- Created reusable HTab and VTab components for horizontal/vertical tabs
- Reduced repetitive tab code from 9 lines per tab to 1 line
- Improved code maintainability and reusability
- WASM bundle size reduced from 5987 bytes to 4690 bytes (22% reduction!)

**Result:**
- CSS transitions now work smoothly on vertical tabs ✓
- All 55 tests passing ✓
- Cleaner, more composable tab components ✓

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-15 11:39:53 -08:00
Aaron SinclairandClaude 1575571f3e Implement reactive attributes for minimal DOM updates
Features:
- Track attributes that depend on signals (ternary expressions)
- Store element references in globals for reactive attributes
- Re-evaluate and update only changed attributes when signals change
- Similar to reactive conditionals but for attributes

Performance:
- Minimal DOM updates - only changed attributes are updated
- No full re-renders, no virtual DOM diffing
- Direct attribute updates via js_set_attribute

Example:
  class_='tab active' if tab_index == 0 else 'tab'

When tab_index changes, only the class attribute updates.

Implementation:
- Collection phase: scan for attributes with signal dependencies
- Render phase: store element references to globals
- Signal update: re-evaluate expression and update attribute

All tests passing (55 passed, 2 skipped)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-15 11:23:09 -08:00
Aaron SinclairandClaude b0e38db22c Fix nested components - render functions now return i32
Changes:
- Component render functions return i32 (root element) instead of void
- Nested components (yield SomeComponent()) now work correctly
- Added main() entry point that calls top-level component and sets root
- Updated runtime to call main() instead of render_ComponentName()

Note: Active state in ternary expressions still needs reactive updates
This commit fixes the nested component rendering issue

All tests passing (51 passed, 2 skipped)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-15 11:16:23 -08:00
Aaron SinclairandClaude adf95f424d Fix lambda event handlers & add ternary expression support
Fixes:
- Lambda functions now correctly pass arguments to handlers
- Function parameters properly emitted in LLVM IR
- Event handlers defined with parameter lists

New feature - Ternary expressions:
- Support Python ternary syntax (x if cond else y) in props
- Eliminates repetitive if/else blocks for active states
- Before: 6 lines per tab button
- After: 1 line with ternary expression

Example:
  class_='tab active' if active else 'tab'

All tests passing (51 passed, 2 skipped)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-15 11:07:58 -08:00
Aaron SinclairandClaude c947bcf6e0 Update Tabs example to use lambda event handlers
Replace verbose boilerplate (set_tab_0, set_tab_1, etc.) with clean
lambda syntax using the new feature.

Before (18 lines of boilerplate):
  def set_tab_0(): tab_index = 0
  def set_tab_1(): tab_index = 1
  def set_tab_2(): tab_index = 2
  def set_setting_0(): setting_tab = 0
  def set_setting_1(): setting_tab = 1
  def set_setting_2(): setting_tab = 2

After (2 lines):
  def set_tab(value): tab_index = value
  def set_setting(value): setting_tab = value

Usage:
  onclick=lambda: set_tab(0)
  onclick=lambda: set_setting(1)

Generated WASM: 8810 bytes (smaller than before!)
Lambda functions: 36 total (12 per component × 2 components)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-15 10:48:40 -08:00
Aaron SinclairandClaude e09a6dedc8 Add component props and lambda event handlers (TDD)
Implements two major features using Test-Driven Development:

1. Component Props/Parameters:
   - Components can accept parameters: @component def Button(label)
   - Arguments passed when yielding: yield Button("Click me")
   - Default values supported: def Tabs(orientation=0)
   - Codegen passes arguments correctly to render functions

2. Lambda Event Handlers:
   - Support onclick=lambda: function_call() syntax
   - Parser converts lambdas to synthetic functions
   - Synthetic functions auto-named: _lambda_0_ComponentName
   - Codegen emits lambda functions as event handlers
   - Clean syntax vs set_tab_0/1/2 boilerplate

Implementation:
   - Added _process_lambdas_in_component() to scan & convert
   - Lambda detection in _transform_expr()
   - "expr" statement type for lambda bodies
   - Component argument passing in _emit_yield_component()
   - Constants vs variables handled correctly in args

Tests (TDD Style):
   - test_component_props.py (8 tests) - all passing
   - test_lambda_simple.py (3 tests) - all passing
   - 46 total tests passing

Examples:
   # Before (verbose)
   def set_tab_0(): tab = 0
   def set_tab_1(): tab = 1
   with Button(onclick=set_tab_0): yield "Tab 0"

   # After (clean)
   with Button(onclick=lambda: set_tab(0)): yield "Tab 0"
   with Button(onclick=lambda: set_tab(1)): yield "Tab 1"

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-15 10:45:17 -08:00
Aaron SinclairandClaude e686903170 Fix reactive conditional rendering with proper branch swapping
Implements efficient reactive conditionals that pre-render branches once
and swap DOM nodes without recreation, enabling fast switching with
thousands of elements.

Key Fixes:
- Runtime now calls reevaluate_conditional_*() on signal changes
- Match/case swap logic uses phi nodes to load correct old case
- Previously hardcoded case_0 as old value, causing accumulation
- Branch render functions now wrap all content in container div

Implementation:
- Pre-render both if/else branches at init
- Store roots in globals (@cond_N_then_root, @cond_N_else_root)
- On signal change, swap DOM nodes via js_replace_at_marker()
- Match statements use switch/phi pattern to select old case

Tests:
- Added test_reactive_conditionals.py (5 new tests)
- Updated test_llvm_codegen_conditional.py for reactive infrastructure
- All 35 tests passing

Performance: No re-rendering on switches, perfect for dynamic content.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-15 10:32:40 -08:00
Aaron SinclairandClaude ac7726df46 Wire up reactive signal updates to conditionals
Critical change that makes conditionals reactive:

- Added signal_conditional_deps map to track dependencies
- Added _extract_signals_from_expr() to find signals in expressions
- Populate dependency map during _collect_conditionals()
- Replace TODO comments in signal setters with reevaluate calls

How it works:
1. During collection, analyze if/match test/subject expressions
2. Extract all signal names referenced in conditions
3. Build map: signal_name -> [conditional_ids that use it]
4. When signal is updated (assign/augassign), call reevaluate for each dependent conditional

Example: set_tab_0() now:
  store i32 0, i32* @signal_Tabs_tab_index
  call void @reevaluate_conditional_4()
  call void @reevaluate_conditional_5()
  call void @reevaluate_conditional_6()
  call void @reevaluate_conditional_7()

This makes tabs fully interactive!

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-15 03:57:15 -08:00
Aaron SinclairandClaude 3540c44abb Implement reactive match/case rendering
- Implemented _emit_match_reactive() to generate init/reevaluate functions
- Modified _emit_match() to create markers and call init functions
- Init function pre-renders all cases and uses switch to insert active one
- Reevaluate function checks if subject changed and swaps DOM

Match init function:
- Calls _render_cond_X_case_Y() for each case
- Stores all case roots in globals
- Evaluates subject with switch instruction
- Inserts matching case at marker position

Fallback to _emit_match_static() if not collected.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-15 03:55:26 -08:00
Aaron SinclairandClaude 44db8ff022 Integrate reactive rendering into _emit_if()
Modified _emit_if() to:
- Create marker node via js_create_marker()
- Append marker to parent element
- Store marker ID in global
- Call _init_conditional_X() to render and insert active branch

Branch render functions work correctly:
- Build element tree locally
- Return root element ID
- Called by init function to pre-render all branches

Fallback to _emit_if_static() if conditional not collected.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-15 03:53:38 -08:00
Aaron SinclairandClaude 8bf1c38858 Add reactive conditional infrastructure
- Collect conditionals during IR scan (if/match statements)
- Emit conditional state globals (marker, current, branch roots)
- Generate init functions that pre-render all branches
- Generate reevaluate functions that swap DOM on condition change
- Add JS function declarations for markers and swapping

Not yet integrated with actual rendering - still emitting static if/match.
Next: modify _emit_if() to use reactive approach.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-15 03:51:01 -08:00
Aaron Sinclair 9f601b1787 Fix element appending in conditional branches
- Add parent_element_stack to track nesting context
- Elements inside if/match branches append to parent
- Fixes: Li elements inside if statements now append to Ul parent
- Tabs now render visibly!
- TODO: Fix duplicate appends
- All tests passing (30/30)
2025-11-15 03:43:06 -08:00
Aaron Sinclair cdddbf675a Add component parameter support and fix JS runtime
- Emit function parameters in component signature
- JS runtime passes props as positional arguments
- Remove incorrect return value handling (components call js_set_root internally)
- Enables: def Tabs(orientation=0)
- All tests passing (30/30)
2025-11-15 03:39:43 -08:00
Aaron Sinclair 41474aceda Add basic component composition support
- Handle yield_component statement type
- Call child component render function
- Enables: yield VerticalTabs()
- All tests passing (30/30)
- Tabs.wasm size: 3185 → 3205 bytes
2025-11-15 03:36:38 -08:00
Aaron Sinclair cd89f75c1c Implement match/case statement code generation
- Add _emit_match() using LLVM switch instruction
- Handle value patterns and wildcard (case _:) patterns
- Each case gets its own basic block with branch to end
- Wildcard case becomes default label in switch
- All tests passing (30/30)
- Tabs.wasm size: 1908 → 3185 bytes
2025-11-15 03:35:31 -08:00
Aaron Sinclair e18baf3106 Add direct signal assignment in event handlers
- Handle 'assign' type statements in _emit_handler_statement()
- Evaluate value expression and store to signal global
- Enables patterns like: setting_tab = 0
- All tests passing (30/30)
2025-11-15 03:33:45 -08:00
Aaron Sinclair 74ff1e7e9f Support multiple components in single file with scoped signals
- Update generate_llvm_ir() to accept list of component dicts
- Process each component with own signal/handler state
- Scope signal globals with component name prefix (@signal_ComponentName_signalName)
- Add _signal_global() helper for scoped signal names
- Update tests for scoped signal names
- All tests passing (30/30)
2025-11-15 03:32:38 -08:00
Aaron Sinclair 0063a8536c Add comparison operator support for if conditions
- Extend _emit_expr() to handle 'compare' type expressions
- Map Python comparison ops (Gt, Lt, Eq, etc) to LLVM icmp predicates
- Convert i1 result to i32 for compatibility
- All conditional tests passing (3/3)
2025-11-15 03:29:57 -08:00
Aaron Sinclair 044eda2293 Implement basic if statement rendering in LLVM IR
- Add _emit_if() method to handle if statements
- Add _emit_expr() to evaluate signal references and constants
- Create basic blocks for then/else/merge
- Convert condition to i1 and branch
- Test passing: test_if_statement_codegen
2025-11-15 03:28:44 -08:00
Aaron Sinclair a3cd1df40a Fix parser test: args → params 2025-11-15 03:25:46 -08:00
Aaron Sinclair 81d51d5617 Parser: Support multiple components in one file, change args to params with defaults 2025-11-15 03:25:13 -08:00
Aaron Sinclair 635d466874 Implement Python → LLVM IR → WASM reactive framework
MAJOR ACHIEVEMENT: Full working reactive framework!

## What's Working

✅ Python → AST → Ritz IR → LLVM IR → WASM pipeline
✅ Reactive signals stored in WASM memory (@signal_name = global i32)
✅ Event handlers exported from WASM and callable from JS
✅ Clean runtime with RitzLoader and debug tools
✅ Two working examples: HelloWorld and HighFive counter

## Core Components

### Parser (ritz/parser.py)
- Uses Python's ast module to parse components
- Handles @component decorator, signals, event handlers
- Supports yield, with statements, f-strings, augmented assignment (+=)
- Clean syntax: from ritz.syntax import *

### LLVM IR Code Generator (ritz/llvm_codegen_signals.py)
- Generates LLVM IR directly (not C!)
- Signals as global variables in WASM memory
- Exports getter/setter functions for each signal
- Exports event handler functions for JS to call
- UTF-8 string handling

### Build System (ritz/build.py)
- Python → AST → IR → LLVM IR → clang --target=wasm32 → WASM
- Saves intermediate .ll files for inspection
- Debug symbols support (-g flag)

### Runtime (runtime/ritz-runtime.js)
- RitzRuntime class: DOM bridge for WASM
- RitzLoader class: Simplified component loading
- Debug bar with Ctrl+` toggle
- Signal updates trigger DOM updates

## Examples

### HelloWorld.py
Simple static content - renders <p>Hello World</p>

### HighFive.py
Reactive counter with:
- Signal in WASM memory (high_fives = signal(0))
- Event handler (increment function)
- DOM updates on signal change

## Test Coverage

- 4 parser tests (all passing)
- 4 LLVM codegen tests (all passing)
- 4 signal parsing tests (all passing)
- Code formatted with black and ruff

## Next Steps

- <script type="text/ritz"> in-browser compilation
- Better signal-to-DOM binding tracking
- More complex examples (TodoMVC, forms, lists)
- Playwright browser tests

---

This is a genuinely innovative framework: write Python, compile to WASM,
run with reactive signals in WASM memory. No virtual DOM, no transpilation,
just compiled Python with fine-grained reactivity.

🎉 Python → WASM → Reactive UI is REAL!
2025-11-15 01:50:40 -08:00