Learn ADA-SPARK with Real Code Examples

Updated Nov 27, 2025

Explain

SPARK is a subset of Ada that removes unsafe or ambiguous features.

Uses contracts (pre/postconditions, invariants) for formal correctness.

GNATprove tool performs static analysis and proofs.

Designed for avionics, medical, defense, and railway systems.

Guarantees freedom from runtime errors (overflow, null dereference, etc.) through proofs.

Core Features

Packages, procedures, functions

Subtype constraints and range checks

Contracts (pragma Assume, Assert, Post, Pre, Loop_Invariant)

SPARK proof annotations

Pure, deterministic code model

Basic Concepts Overview

Packages - modular code units

Subtypes - type-safe constraints

Contracts - correctness rules

Proof obligations - automatically generated checks

Abstract data types - encapsulation for safety

Project Structure

src/ for code

gpr project file

spec (.ads) and body (.adb) files

proof annotations

test and harness modules

Building Workflow

Write Ada/SPARK code with contracts

Run GNATprove to generate/verify proofs

Fix proof failures or contract violations

Compile with GNAT

Deploy to embedded/RTOS target

Difficulty Use Cases

Beginner: simple procedures with contracts

Intermediate: packages and invariants

Advanced: data abstraction + loop invariants

Expert: full program proofs

Architect: DO-178C/IEC61508 certified systems

Comparisons

SPARK vs Ada: SPARK is the provable safe subset.

SPARK vs Rust: Rust focuses on memory safety; SPARK proves full correctness.

SPARK vs MISRA C: SPARK is more rigorous and verifiable.

SPARK vs SCADE: SPARK is code-level proofs; SCADE is model-based.

SPARK vs Eiffel: SPARK contracts are verifiable, not runtime only.

Versioning Timeline

1980s - Early SPARK origins

1990s - SPARK classic

2012 - SPARK 2014 redesign

2020 - Expanded contracts

2024 - RISC-V safety platforms

2025 - Modern Ada/SPARK integrations

Glossary

AoRTE - Absence of Runtime Errors

Contract - Formal correctness condition

OBL - Proof obligation

Spec - Package interface (.ads)

Body - Implementation (.adb)