function-class-generator
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.
git clone --depth 1 https://github.com/ArabelaTso/Skills-4-SE /tmp/function-class-generator && cp -r /tmp/function-class-generator/skills/function-class-generator ~/.claude/skills/function-class-generatorSKILL.md
# 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:**
```python
# 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:**
```python
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:
```python
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 TypeApplies abstract interpretation using different abstract domains (intervals, octagons, polyhedra, sign, congruence) to statically analyze program variables and infer invariants, value ranges, and relationships. Use when analyzing program properties, inferring loop invariants, detecting potential errors, or understanding variable relationships through static analysis.
Uses abstract interpretation to automatically infer loop invariants, function preconditions, and postconditions for formal verification. Generates invariants that capture program behavior and support correctness proofs in Dafny, Isabelle, Coq, and other verification systems. Use when adding formal specifications to code, generating verification conditions, inferring contracts for functions, or discovering loop invariants for proofs.
Performs abstract interpretation over source code to infer possible program states, variable ranges, and data properties without executing the program. Reports potential runtime errors including out-of-bounds accesses, null dereferences, type inconsistencies, division by zero, and integer overflows. Use when analyzing code for potential runtime errors, performing static analysis, checking safety properties, or verifying program behavior without execution.
Performs abstract interpretation to produce summarized execution traces and high-level program behavior representations. Highlights key control flow paths, variable relationships, loop invariants, function summaries, and potential runtime states using abstract domains (intervals, signs, nullness, etc.). Use when analyzing program behavior, understanding execution paths, computing loop invariants, tracking variable ranges, detecting potential runtime errors, or generating program summaries without concrete execution.
Create ACSL (ANSI/ISO C Specification Language) formal annotations for C/C++ programs. Use this skill when working with formal verification, adding function contracts (requires/ensures), loop invariants, assertions, memory safety annotations, or any ACSL specifications. Supports Frama-C verification and generates comprehensive formal specifications for C/C++ code.
CLI-based browser automation with persistent page state using ref-based element interaction. Use when users ask to navigate websites, interact with web pages, fill forms, take screenshots, test web applications, or extract information from web pages.
Detects and analyzes ambiguous language in software requirements and user stories. Use when reviewing requirements documents, user stories, specifications, or any software requirement text to identify vague quantifiers, unclear scope, undefined terms, missing edge cases, subjective language, and incomplete specifications. Provides detailed analysis with clarifying questions and suggested improvements.
Design and review APIs with suggestions for endpoints, parameters, return types, and best practices. Use when designing new APIs from requirements, reviewing existing API designs, generating API documentation, or getting implementation guidance. Supports REST APIs with focus on endpoint structure, request/response schemas, authentication, pagination, filtering, versioning, and OpenAPI specifications. Triggers when users ask to design, review, document, or improve APIs.