Verify code correctness statically against specifications using type checking, contract verification, and formal methods. Use when: (1) Verifying type safety and null safety in Python, Java, or C/C++ code, (2) Checking design-by-contract specifications (preconditions, postconditions, invariants), (3) Validating code against formal specifications, (4) Ensuring code quality and correctness before runtime, (5) Finding potential bugs through static analysis. Supports Python (mypy, contracts), Java (javac, JML), and provides verification scripts and contract specification guidelines.
Install with Codex or Claude Copy this prompt, paste it into Codex, Claude, or another assistant, and let it review the skill page and install it for you.
A direct command skips the review prompt. Inspect the source before running it.
Verify code correctness statically against specifications using type checking, contract verification, and formal methods. Use when: (1) Verifying type safety and null safety in Python, Java, or C/C++ code, (2) Checking design-by-contract specifications (preconditions, postconditions, invariants), (3) Validating code against formal specifications, (4) Ensuring code quality and correctness before runtime, (5) Finding potential bugs through static analysis. Supports Python (mypy, contracts), Java (javac, JML), and provides verification scripts and contract specification guidelines.
Static Reasoning Verifier
Verify code correctness statically against specifications through type checking, contract verification, and formal reasoning.
Quick Start
Verify Python Code
# Type checking and contract verification
python scripts/verify_python.py src/app.py
# Strict mode (enforce all type annotations)
python scripts/verify_python.py src/ --strict
Verify type correctness using static type checkers:
Python (mypy):
defadd(a: int, b: int) -> int:
return a + b
result: int = add(, )
result: = add(, )
5
10
# ✅ Type safe
str
5
10
# ❌ Type error
Java:
publicintadd(int a, int b) {
return a + b;
}
intresult= add(5, 10); // ✅ Type safeStringresult= add(5, 10); // ❌ Compile error
2. Contract Verification
Verify preconditions, postconditions, and invariants:
Python:
defsqrt(x: float) -> float:
"""
Calculate square root.
Requires:
- x >= 0
Ensures:
- result * result ≈ x
"""assert x >= 0, "Input must be non-negative"
result = x ** 0.5assertabs(result * result - x) < 1e-10return result
public@NonNull String getName(@NonNull User user) {
return user.getName(); // Safe - user cannot be null
}
Python:
from typing importOptionaldeffind_user(user_id: int) -> Optional[User]:
"""May return None if user not found."""return database.get_user(user_id)
Verification Workflow
1. Write Specifications
Define contracts for functions/methods:
defdivide(a: float, b: float) -> float:
"""
Divide two numbers.
Precondition:
- b != 0
Postcondition:
- result * b ≈ a
Raises:
ValueError: If b is zero
"""if b == 0:
raise ValueError("Division by zero")
return a / b
2. Add Type Annotations
from typing importList, Optionaldefprocess_items(items: List[int], threshold: int = 0) -> List[int]:
"""Filter items above threshold."""return [item for item in items if item > threshold]
Found 3 issue(s): 1 error(s), 2 warning(s)
ERRORS:
❌ src/utils.py:15 [type]
Argument 1 to "divide" has incompatible type "str"; expected "float"
💡 Check argument type matches function signature
WARNINGS:
⚠️ src/math.py:42 [contract]
Function 'sqrt' has parameters but no preconditions specified
💡 Add 'Requires:' section in docstring or @requires decorator
5. Fix Issues
Update code to satisfy specifications:
# Before (type error)
result = divide("10", 5)
# After (type safe)
result = divide(10.0, 5.0)
Python Verification
Type Checking with mypy
The verification script uses mypy for static type checking:
python scripts/verify_python.py src/ --strict
Checks:
Type compatibility
Function signatures
Return types
Optional/None handling
Example:
defgreet(name: str) -> str:
returnf"Hello, {name}"
greet("Alice") # ✅ Valid
greet(123) # ❌ Type error: expected str, got int
Contract Verification
Checks design-by-contract specifications:
Decorator-based:
from contracts import requires, ensures
@requires(lambda x: x >= 0)@ensures(lambda result: result >= 0)defsqrt(x: float) -> float:
return x ** 0.5
See java_jml.md for complete JML specification guide.
Common Verification Patterns
Range Validation
defset_age(person: Person, age: int) -> None:
"""
Requires: 0 <= age <= 150
Ensures: person.age == age
"""assert0 <= age <= 150, "Age must be between 0 and 150"
person.age = age
Collection Constraints
defprocess_batch(items: List[Item]) -> None:
"""
Requires:
- len(items) > 0
- len(items) <= 1000
"""assertlen(items) > 0, "Batch cannot be empty"assertlen(items) <= 1000, "Batch too large"# Process items
State Invariants
classStack:
"""
Invariant:
- 0 <= self.size <= self.capacity
- All elements before size are not None
"""defpush(self, item):
"""
Requires: not self.is_full() and item is not None
Ensures: self.size == old(self.size) + 1
"""assertnotself.is_full()
assert item isnotNoneself.items[self.size] = item
self.size += 1self._check_invariant()
Best Practices
1. Write Contracts First
Define specifications before implementation:
defsort_list(items: List[int]) -> List[int]:
"""
Sort list in ascending order.
Requires:
- items is a list
Ensures:
- len(result) == len(items)
- result is sorted ascending
- result contains same elements as items
"""# Implementation here
2. Keep Contracts Simple
# ✅ Good - Simple, cleardefwithdraw(amount: float):
"""Requires: amount > 0 and amount <= balance"""assert amount > 0and amount <= self.balance
# ❌ Bad - Too complexdefwithdraw(amount: float):
"""Requires: (amount > 0 and amount <= balance) or (overdraft_allowed and amount <= balance + overdraft_limit)"""
3. Use Type Annotations Consistently
# ✅ Good - All parameters and return types annotateddefcalculate_total(items: List[Item], tax_rate: float) -> float:
returnsum(item.price for item in items) * (1 + tax_rate)
# ❌ Bad - Missing annotationsdefcalculate_total(items, tax_rate):
returnsum(item.price for item in items) * (1 + tax_rate)
4. Verify Early and Often
# Verify after every significant change
python scripts/verify_python.py src/
# Integrate into CI/CD
make verify # Run verification in build pipeline
5. Document Side Effects
defupdate_database(user: User) -> None:
"""
Update user in database.
Requires:
- user.id is set
Ensures:
- Database contains updated user
Side effects:
- Modifies database
- May raise DatabaseError
"""
Troubleshooting
Type Errors
Problem: Incompatible type error
Solution:
# Add explicit type annotation or cast
result: int = int(value) # Cast to int
result = cast(int, value) # Type cast
Problem: Optional type handling
Solution:
defget_name(user: Optional[User]) -> str:
if user isNone:
return"Unknown"return user.name # Safe - checked for None