Generate complete, production-ready functions and classes from formal specifications, design descriptions, type signatures, or natural language requirements. Use this skill when implementing APIs from specifications, creating data structures from schemas, building classes from UML diagrams, generating code from contracts, or translating design documents into code. Supports multiple programming languages and follows language-specific best practices.
Instrucciones de origen · Vista previa de solo lectura
name
function-class-generator
description
Generate complete, production-ready functions and classes from formal specifications, design descriptions, type signatures, or natural language requirements. Use this skill when implementing APIs from specifications, creating data structures from schemas, building classes from UML diagrams, generating code from contracts, or translating design documents into code. Supports multiple programming languages and follows language-specific best practices.
Function/Class Generator
Transform formal specifications, design descriptions, and requirements into complete, well-structured, production-ready code. Generates functions, classes, interfaces, and data structures with proper error handling, documentation, and tests.
Core Capabilities
1. Specification Parsing
Understand specifications from multiple sources:
Type signatures - Function signatures with input/output types
Function: binary_search
Inputs: sorted_array: List[int], target: int
Output: int (index of target, or -1 if not found)
Preconditions:
- sorted_array is sorted in ascending order
- sorted_array is not empty
Postconditions:
- If result >= 0: sorted_array[result] == target
- If result == -1: target not in sorted_array
Step 2: Design Implementation
Plan the structure:
Identify:
Main logic flow
Edge cases to handle
Validation needed
Error conditions
Helper functions required
For binary_search example:
Main logic: Binary search algorithm
Edge cases: Empty array, single element, target at boundaries
Validation: Array must be sorted, index bounds
Errors: Invalid input types, empty array
Helpers: None needed (self-contained)
Step 3: Generate Code
Create complete implementation:
Generated code:
defbinary_search(sorted_array: list[int], target: int) -> int:
"""
Search for target in sorted array using binary search.
Args:
sorted_array: List of integers sorted in ascending order
target: Integer value to search for
Returns:
Index of target if found, -1 otherwise
Raises:
ValueError: If sorted_array is empty
TypeError: If inputs are not of correct type
Examples:
>>> binary_search([1, 2, 3, 4, 5], 3)
2
>>> binary_search([1, 2, 3, 4, 5], 6)
-1
Time Complexity: O(log n)
Space Complexity: O(1)
"""ifnotisinstance(sorted_array, list):
raise TypeError("sorted_array must be a list")
ifnotisinstance(target, int):
raise TypeError("target must be an integer")
ifnot sorted_array:
raise ValueError("sorted_array cannot be empty")
left, right = 0, len(sorted_array) - 1while left <= right:
mid = left + (right - left) // 2# Avoid overflowif sorted_array[mid] == target:
return mid
elif sorted_array[mid] < target:
left = mid + 1else:
right = mid - 1return -1
Step 4: Add Documentation
Include comprehensive documentation:
Elements:
Docstring with description
Parameter descriptions
Return value description
Exceptions raised
Usage examples
Complexity analysis
Precondition/postcondition notes
Step 5: Generate Tests
Create validation tests:
import pytest
deftest_binary_search_found():
"""Test finding an element in the middle."""assert binary_search([1, 2, 3, 4, 5], 3) == 2deftest_binary_search_not_found():
"""Test element not in array."""assert binary_search([1, 2, 3, 4, 5], 6) == -1deftest_binary_search_first_element():
"""Test finding first element."""assert binary_search([1, 2, 3, 4, 5], 1) == 0deftest_binary_search_last_element():
"""Test finding last element."""assert binary_search([1, 2, 3, 4, 5], 5) == 4deftest_binary_search_single_element_found():
"""Test single-element array with target present."""assert binary_search([1], 1) == 0deftest_binary_search_single_element_not_found():
"""Test single-element array with target absent."""assert binary_search([1], 2) == -1deftest_binary_search_empty_array():
"""Test that empty array raises ValueError."""with pytest.raises(ValueError, match="cannot be empty"):
binary_search([], 1)
deftest_binary_search_invalid_array_type():
"""Test that invalid array type raises TypeError."""with pytest.raises(TypeError, match="must be a list"):
binary_search("not a list", 1)
deftest_binary_search_invalid_target_type():
"""Test that invalid target type raises TypeError."""with pytest.raises(TypeError, match="must be an integer"):
binary_search([1, 2, 3], "not an int")
Generation Patterns
Pattern 1: Function from Type Signature
Specification:
functioncalculateArea(width: number, height: number): number
Generated implementation:
/**
* Calculate the area of a rectangle.
*
* @paramwidth - Width of the rectangle (must be positive)
* @paramheight - Height of the rectangle (must be positive)
* @returns The calculated area (width * height)
* @throws {Error} If width or height is not positive
*
* @example
* ```typescript
* calculateArea(5, 10) // returns 50
* calculateArea(2.5, 4) // returns 10
* ```
*/functioncalculateArea(width: number, height: number): number {
if (width <= 0) {
thrownewError('Width must be positive');
}
if (height <= 0) {
thrownewError('Height must be positive');
}
return width * height;
}
Generated tests:
import { describe, it, expect } from'@jest/globals';
describe('calculateArea', () => {
it('should calculate area correctly', () => {
expect(calculateArea(5, 10)).toBe(50);
expect(calculateArea(2.5, 4)).toBe(10);
});
it('should handle decimal values', () => {
expect(calculateArea(3.5, 2.5)).toBeCloseTo(8.75);
});
it('should throw error for zero width', () => {
expect(() =>calculateArea(0, 10)).toThrow('Width must be positive');
});
it('should throw error for negative width', () => {
expect(() =>calculateArea(-5, 10)).toThrow('Width must be positive');
});
it('should throw error for zero height', () => {
expect(() =>calculateArea(10, 0)).toThrow('Height must be positive');
});
it('should throw error for negative height', () => {
expect(() =>calculateArea(10, -5)).toThrow('Height must be positive');
});
});
Pattern 2: Class from Specification
Specification:
Class: BankAccount
Purpose: Manage a bank account with deposits and withdrawals
Attributes:
- account_number: string (unique identifier)
- balance: decimal (current balance, must be >= 0)
- owner_name: string
Methods:
- deposit(amount): Add money to account
Precondition: amount > 0
Postcondition: balance increased by amount
- withdraw(amount): Remove money from account
Precondition: amount > 0 and amount <= balance
Postcondition: balance decreased by amount
- get_balance(): Return current balance
Postcondition: returns balance >= 0
Invariants:
- balance must always be >= 0
- account_number is immutable
Generated implementation:
from decimal import Decimal
from typing import Final
classInsufficientFundsError(Exception):
"""Raised when withdrawal amount exceeds account balance."""passclassInvalidAmountError(Exception):
"""Raised when transaction amount is invalid."""passclassBankAccount:
"""
Manage a bank account with deposits and withdrawals.
Invariants:
- Balance is always >= 0
- Account number is immutable once set
Attributes:
account_number: Unique account identifier (immutable)
balance: Current account balance (non-negative)
owner_name: Name of account owner
"""def__init__(self, account_number: str, owner_name: str, initial_balance: Decimal = Decimal('0')):
"""
Initialize a new bank account.
Args:
account_number: Unique account identifier
owner_name: Name of account owner
initial_balance: Starting balance (default: 0)
Raises:
ValueError: If account_number or owner_name is empty
InvalidAmountError: If initial_balance is negative
"""ifnot account_number:
raise ValueError("Account number cannot be empty")
ifnot owner_name:
raise ValueError("Owner name cannot be empty")
if initial_balance < 0:
raise InvalidAmountError("Initial balance cannot be negative")
self._account_number: Final[str] = account_number
self._balance: Decimal = initial_balance
self.owner_name: str = owner_name
@propertydefaccount_number(self) -> str:
"""Get account number (immutable)."""returnself._account_number
@propertydefbalance(self) -> Decimal:
"""Get current account balance."""returnself._balance
defdeposit(self, amount: Decimal) -> None:
"""
Add money to the account.
Args:
amount: Amount to deposit (must be positive)
Raises:
InvalidAmountError: If amount is not positive
Postcondition:
Balance increases by amount
"""if amount <= 0:
raise InvalidAmountError("Deposit amount must be positive")
self._balance += amount
defwithdraw(self, amount: Decimal) -> None:
"""
Remove money from the account.
Args:
amount: Amount to withdraw (must be positive and <= balance)
Raises:
InvalidAmountError: If amount is not positive
InsufficientFundsError: If amount exceeds current balance
Postcondition:
Balance decreases by amount
"""if amount <= 0:
raise InvalidAmountError("Withdrawal amount must be positive")
if amount > self._balance:
raise InsufficientFundsError(
f"Insufficient funds: balance={self._balance}, requested={amount}"
)
self._balance -= amount
defget_balance(self) -> Decimal:
"""
Return current account balance.
Returns:
Current balance (always >= 0)
"""returnself._balance
def__repr__(self) -> str:
"""Return string representation of account."""returnf"BankAccount(account_number={self._account_number!r}, balance={self._balance}, owner={self.owner_name!r})"
Generated tests:
import pytest
from decimal import Decimal
classTestBankAccount:
"""Test suite for BankAccount class."""deftest_init_valid(self):
"""Test creating account with valid parameters."""
account = BankAccount("12345", "John Doe", Decimal('100'))
assert account.account_number == "12345"assert account.balance == Decimal('100')
assert account.owner_name == "John Doe"deftest_init_default_balance(self):
"""Test creating account with default zero balance."""
account = BankAccount("12345", "John Doe")
assert account.balance == Decimal('0')
deftest_init_invalid_account_number(self):
"""Test that empty account number raises ValueError."""with pytest.raises(ValueError, match="Account number cannot be empty"):
BankAccount("", "John Doe")
deftest_init_invalid_owner_name(self):
"""Test that empty owner name raises ValueError."""with pytest.raises(ValueError, match="Owner name cannot be empty"):
BankAccount("12345", "")
deftest_init_negative_balance(self):
"""Test that negative initial balance raises InvalidAmountError."""with pytest.raises(InvalidAmountError, match="cannot be negative"):
BankAccount("12345", "John Doe", Decimal('-10'))
deftest_account_number_immutable(self):
"""Test that account number cannot be changed."""
account = BankAccount("12345", "John Doe")
with pytest.raises(AttributeError):
account.account_number = "67890"deftest_deposit_valid(self):
"""Test depositing positive amount."""
account = BankAccount("12345", "John Doe", Decimal('100'))
account.deposit(Decimal('50'))
assert account.balance == Decimal('150')
deftest_deposit_zero(self):
"""Test that depositing zero raises InvalidAmountError."""
account = BankAccount("12345", "John Doe")
with pytest.raises(InvalidAmountError, match="must be positive"):
account.deposit(Decimal('0'))
deftest_deposit_negative(self):
"""Test that depositing negative amount raises InvalidAmountError."""
account = BankAccount("12345", "John Doe")
with pytest.raises(InvalidAmountError, match="must be positive"):
account.deposit(Decimal('-10'))
deftest_withdraw_valid(self):
"""Test withdrawing valid amount."""
account = BankAccount("12345", "John Doe", Decimal('100'))
account.withdraw(Decimal('30'))
assert account.balance == Decimal('70')
deftest_withdraw_entire_balance(self):
"""Test withdrawing entire balance."""
account = BankAccount("12345", "John Doe", Decimal('100'))
account.withdraw(Decimal('100'))
assert account.balance == Decimal('0')
deftest_withdraw_insufficient_funds(self):
"""Test that withdrawing more than balance raises InsufficientFundsError."""
account = BankAccount("12345", "John Doe", Decimal('100'))
with pytest.raises(InsufficientFundsError, match="Insufficient funds"):
account.withdraw(Decimal('150'))
deftest_withdraw_zero(self):
"""Test that withdrawing zero raises InvalidAmountError."""
account = BankAccount("12345", "John Doe", Decimal('100'))
with pytest.raises(InvalidAmountError, match="must be positive"):
account.withdraw(Decimal('0'))
deftest_withdraw_negative(self):
"""Test that withdrawing negative amount raises InvalidAmountError."""
account = BankAccount("12345", "John Doe", Decimal('100'))
with pytest.raises(InvalidAmountError, match="must be positive"):
account.withdraw(Decimal('-10'))
deftest_get_balance(self):
"""Test getting account balance."""
account = BankAccount("12345", "John Doe", Decimal('100'))
assert account.get_balance() == Decimal('100')
assert account.get_balance() >= 0# Invariant checkdeftest_multiple_transactions(self):
"""Test sequence of deposits and withdrawals."""
account = BankAccount("12345", "John Doe", Decimal('100'))
account.deposit(Decimal('50')) # 150
account.withdraw(Decimal('30')) # 120
account.deposit(Decimal('10')) # 130
account.withdraw(Decimal('80')) # 50assert account.balance == Decimal('50')
deftest_repr(self):
"""Test string representation."""
account = BankAccount("12345", "John Doe", Decimal('100'))
repr_str = repr(account)
assert"12345"in repr_str
assert"John Doe"in repr_str
assert"100"in repr_str