Skip to content

feat(compiler): implement stack-frame based local variable allocation to support recursion (#44) - #58

Merged
sql-hkr merged 1 commit into
mainfrom
feat/stack-frame-local-vars
Oct 29, 2026
Merged

sql-hkr merged 1 commit into
mainfrom
feat/stack-frame-local-vars

Conversation

@sql-hkr

@sql-hkr sql-hkr commented Oct 29, 2026

Copy link
Copy Markdown
Owner

Summary

Closes #44.

This PR implements a frame-pointer based stack-frame model (using the AVR Y register pair R29:R28) for local variables and function parameters, enabling robust recursive function calls and preserving caller state.

Key Changes

  • CPU & Assembler (cpu.py, assembler.py):
    • Implemented LDD Rd, Y+q / Z+q and STD Y+q / Z+q, Rr instructions for indirect addressing with displacement.
    • Supported reading/writing Stack Pointer via standard AVR I/O ports 0x3D (SPL) and 0x3E (SPH) in IN and OUT.
    • Added operand parsing for Y+q, Z+q in the assembler.
  • Compiler (compiler.py):
    • Added _collect_locals to discover all function parameters and local variable declarations across blocks and statements.
    • Implemented function prologue: saves caller Y, reads SP into Y (IN R28, 0x3D; IN R29, 0x3E), allocates local stack space via SBIW R28, <locals_size>, and updates SP.
    • Implemented function epilogue: restores stack space via ADIW R28, <locals_size>, updates SP, restores caller Y, and returns (RET).
    • Switched local scalar variable reading/writing and prefix/postfix increment/decrement to LDD / STD.
    • Added peephole optimization rule eliminating redundant LDD immediately following STD.
  • Tests:
    • Added unit tests for recursive Fibonacci (fib(7)), recursive Factorial with local variables, nested multi-frame calls, and global variable interactions inside functions.
    • Maintained 100% statement coverage across cpu.py, compiler.py, and assembler.py (342 tests passing).

Verification

  • uv run pytest --cov=tiny8.compiler --cov=tiny8.cpu --cov=tiny8.assembler (100% coverage, 342 passed)
  • uv run ruff check src/ tests/ (all passed)
  • uv run ruff format --check src/ tests/ (clean)

@sql-hkr
sql-hkr merged commit abc0949 into main Oct 29, 2026
4 checks passed
@sql-hkr
sql-hkr deleted the feat/stack-frame-local-vars branch October 29, 2026 14:51
@codecov

codecov Bot commented Oct 29, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(compiler): implement stack-frame based local variable allocation to support recursion

1 participant