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
- Formal specifications - Pre/postconditions, invariants, contracts
- API documentation - OpenAPI, Swagger, JSON Schema
- UML diagrams - Class diagrams, sequence diagrams
- Natural language - Requirements and design descriptions
- Interface definitions - Protocol buffers, GraphQL schemas
2. Code Generation
Create complete implementations:
- Functions - Standalone functions with logic and validation
- Classes - Full class definitions with methods and properties
- Interfaces/Protocols - Abstract definitions and contracts
- Data structures - Custom types, enums, unions
- Error handling - Exceptions, error types, validation
- Documentation - Docstrings, comments, type hints
3. Best Practices Integration
Apply language-specific patterns:
- Naming conventions - Follow language standards
- Type safety - Use static typing where available
- Error handling - Appropriate exception handling
- Documentation - Clear docstrings and comments
- Testing - Generate unit tests alongside code
- SOLID principles - Single responsibility, open/closed, etc.
4. Validation and Testing
Ensure correctness:
- Type checking - Verify type correctness
- Contract validation - Check pre/postconditions
- Unit tests - Generate test cases
- Edge cases - Handle boundaries and exceptions
- Examples - Provide usage examples
Code Generation Workflow
Step 1: Parse Specification
Extract key information:
From type signature:
# Specification
def calculate_discount(price: float, percentage: float) -> float:
"""Calculate discounted price."""
pass
Extract:
- Function name:
calculate_discount - Parameters:
price(float),percentage(float) - Return type:
float - Purpose: Calculate discounted price
From formal specification:
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:
def binary_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)
"""
if not isinstance(sorted_array, list):
raise TypeError("sorted_array must be a list")
if not isinstance(target, int):
raise TypeError("target must be an integer")
if not sorted_array:
raise ValueError("sorted_array cannot be empty")
left, right = 0, len(sorted_array) - 1
while left <= right:
mid = left + (right - left) // 2 # Avoid overflow
if sorted_array[mid] == target:
return mid
elif sorted_array[mid] < target:
left = mid + 1
else:
right = mid - 1
return -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
def test_binary_search_found():
"""Test finding an element in the middle."""
assert binary_search([1, 2, 3, 4, 5], 3) == 2
def test_binary_search_not_found():
"""Test element not in array."""
assert binary_search([1, 2, 3, 4, 5], 6) == -1
def test_binary_search_first_element():
"""Test finding first element."""
assert binary_search([1, 2, 3, 4, 5], 1) == 0
def test_binary_search_last_element():
"""Test finding last element."""
assert binary_search([1, 2, 3, 4, 5], 5) == 4
def test_binary_search_single_element_found():
"""Test single-element array with target present."""
assert binary_search([1], 1) == 0
def test_binary_search_single_element_not_found():
"""Test single-element array with target absent."""
assert binary_search([1], 2) == -1
def test_binary_search_empty_array():
"""Test that empty array raises ValueError."""
with pytest.raises(ValueError, match="cannot be empty"):
binary_search([], 1)
def test_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)
def test_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:
function calculateArea(width: number, height: number): number
Generated implementation:
/**
* Calculate the area of a rectangle.
*
* @param width - Width of the rectangle (must be positive)
* @param height - 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
* ```
*/
function calculateArea(width: number, height: number): number {
if (width <= 0) {
throw new Error('Width must be positive');
}
if (height <= 0) {
throw new Error('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