The Lean Language Reference

17.2. Predicate Transformers🔗

A predicate transformer semantics is an interpretation of programs as functions from predicates to predicates, rather than values to values. A postcondition is an assertion that holds after running a program, while a precondition is an assertion that must hold prior to running the program in order for the postcondition to be guaranteed to hold.

The predicate transformer semantics used by vcgen transforms postconditions into the weakest preconditions under which the program will ensure the postcondition. An assertion P is weaker than P' if, in all states, P' suffices to prove P, but P does not suffice to prove P'. Logically equivalent assertions are considered to be equal.

The predicates in question can be stateful: they can mention the program's current state. Furthermore, postconditions can relate the return value and any exceptions thrown by the program to the final state. Each program type that can be used with vcgen is assigned an assertion type and an exception postcondition type by an instance of WP. For a state monad such as StateM Nat, an assertion is a predicate on the state, of type Nat → Prop. A postcondition additionally takes the return value as its first argument, and the exception postcondition includes an assertion for each exception that the program can throw.

17.2.1. Assertions and Logic🔗

The predicate transformer semantics of programs is based on a logic in which propositions may mention the program's state. Here, “state” refers not only to mutable state, but also to read-only values such as those that are provided via ReaderT. Different program types have different assertion types. vcgen requires only that an assertion type has an associated notion of entailment. An assertion P entails an assertion Q if Q holds in every situation in which P holds. The notion of “situation” is specific to the assertion type; if assertions may mention the current state, then entailment quantifies over all states. Entailment of assertions is always a Prop, regardless of the assertion type.

Entailment for an assertion type is specified by an instance of PartialOrder. Specifically, “P entails Q” is represented by P ⊑ Q. Because partial orders are antisymmetric, mutual entailment implies equality, so if P ⊑ Q and Q ⊑ P then P = Q.

🔗type class
Lean.Order.PartialOrder.{u} (α : Sort u) : Sort (max 1 u)
Lean.Order.PartialOrder.{u} (α : Sort u) : Sort (max 1 u)

A partial order is a reflexive, transitive and antisymmetric relation.

This is intended to be used in the construction of partial_fixpoint, and not meant to be used otherwise.

Lean.Order.PartialOrder.mk.{u}
rel : α → α → Prop

A “less-or-equal-to” or “approximates” relation.

This is intended to be used in the construction of partial_fixpoint, and not meant to be used otherwise.

rel_refl : ∀ {x : α}, x ⊑ x

The “less-or-equal-to” or “approximates” relation is reflexive.

rel_trans : ∀ {x y z : α}, x ⊑ y → y ⊑ z → x ⊑ z

The “less-or-equal-to” or “approximates” relation is transitive.

rel_antisymm : ∀ {x y : α}, x ⊑ y → y ⊑ x → x = y

The “less-or-equal-to” or “approximates” relation is antisymmetric.

A number of PartialOrder instances are provided by default and can be used as building blocks.

Propositions

P ⊑ Q means P → Q.

Unit

() ⊑ () is just True.

Pairs

Partial orders of pairs are defined component-wise. (a, x) ⊑ (b, y) if a ⊑ b and x ⊑ y.

Functions and Predicates

Partial orders of functions and predicates are given by universal quantification over the domain. For predicates over α, P ⊑ Q when ∀ x : α, P x ⊑ Q x. For functions, f ⊑ g when ∀ x, f x ⊑ g x.

Entailment at Different Assertion Types

At Prop, entailment is implication:

example (P Q : Prop) : (P ⊑ Q) = (P → Q) := rfl

At a state predicate type, entailment is implication at every state:

example (f g : Nat → Prop) : (f ⊑ g) = ∀ n, f n → g n := rfl

Entailment of pairs is conjunction of entailments:

example (f₁ f₂ : Nat → Prop) (g₁ g₂ : Bool → Prop) : ((f₁, g₁) ⊑ (f₂, g₂)) = ((f₁ ⊑ f₂) ∧ (g₁ ⊑ g₂)) := rfl

A concrete entailment between state predicates can be proved by unfolding the entailment order and reasoning about each state:

def Positive : Nat → Prop := fun n => 0 < n def AtLeastTwo : Nat → Prop := fun n => 2 ≤ n example : AtLeastTwo ⊑ Positive := ⊢ AtLeastTwo ⊑ Positive ⊢ ∀ (x : Nat), 2 ≤ x → 0 < x x:Nath:2 ≤ x⊢ 0 < x All goals completed! 🐙

17.2.1.1. Assertion Lattices🔗

While vcgen can be used with assertion languages that only have entailment, pure partial orders are not particularly expressive. Most verification tasks require a richer assertion type. Many of the remaining logical connectives can be enabled by providing a CompleteLattice instance that extends the PartialOrder.

🔗type class
Lean.Order.CompleteLattice.{u} (α : Sort u) : Sort (max 1 u)
Lean.Order.CompleteLattice.{u} (α : Sort u) : Sort (max 1 u)

A complete lattice is a partial order where every subset has a least upper bound.

Lean.Order.CompleteLattice.mk.{u}
rel : α → α → Prop
Inherited from
  1. PartialOrder α
rel_refl : ∀ {x : α}, x ⊑ x
Inherited from
  1. PartialOrder α
rel_trans : ∀ {x y z : α}, x ⊑ y → y ⊑ z → x ⊑ z
Inherited from
  1. PartialOrder α
rel_antisymm : ∀ {x y : α}, x ⊑ y → y ⊑ x → x = y
Inherited from
  1. PartialOrder α
has_sup : ∀ (c : α → Prop), Exists (is_sup c)

The least upper bound of an arbitrary subset exists.

The lattice structure provides the logical vocabulary of assertions:

  • The order relation ⊑ is entailment.

  • The meet ⊓ is conjunction and the join ⊔ is disjunction.

  • The top element ⊤ is the trivial assertion and the bottom element ⊥ is the absurd assertion.

  • The indexed supremum ⨆ is existential quantification and the indexed infimum ⨅ is universal quantification. Their notation resembles that of ordinary quantifiers; for example, ⨆ x : α, P x asserts the existence of something that satisfies P.

  • The Heyting implication ⇨ is implication internal to the assertion language.

The difference between entailment and implication is that entailment is a statement in Lean's logic, while implication is internal to the assertion language: for assertions P and Q, P ⊑ Q is a Prop while P ⇨ Q is again an assertion.

Std.WP comes with CompleteLattice instances for Prop, Unit, function types, and pairs. The lattice operations on Prop coincide with the ordinary logical connectives, with entailment being implication. The lattice operations on a function type such as Nat → Prop operate pointwise, so entailment of state predicates is universally-quantified implication. The lattice operations on a pair such as (Nat → Prop) × (Bool → Prop) operate component-wise, so entailment of paired predicates is the conjunction of entailments of the component predicates.

Ordinary propositions that do not mention the state can be embedded into any assertion lattice with corner brackets. This is written with the syntax ⌜P⌝, which is notation for Lean.Order.CompleteLattice.ofProp.

syntaxEmbedding Propositions
term ::= ...
    | Embedding of propositions into an CompleteLattice type. `⌜p⌝` embeds `p : Prop` as `⊤` if `p` holds
and `⊥` otherwise.⌜term⌝

Embedding of propositions into an CompleteLattice type. ⌜p⌝ embeds p : Prop as ⊤ if p holds and ⊥ otherwise.

🔗def
Lean.Order.CompleteLattice.ofProp.{u_1} {l : Type u_1} [CompleteLattice l] (p : Prop) : l
Lean.Order.CompleteLattice.ofProp.{u_1} {l : Type u_1} [CompleteLattice l] (p : Prop) : l

Embedding of propositions into an CompleteLattice type. ⌜p⌝ embeds p : Prop as ⊤ if p holds and ⊥ otherwise.

An assertion of the form ⌜p⌝ is pure: its truth is independent of the state. At the assertion type Prop, ⌜p⌝ is the proposition p itself, and at a state predicate type such as Nat → Prop, it is the constant predicate fun _ => p. Specifications for a concrete monad can therefore state propositions directly, as in fun s => s = n. Corner brackets are necessary when the assertion type is abstract, as in a specification that quantifies over a monad and its assertion type Pred. In this case, a proposition such as n = k is not an assertion, but ⌜n = k⌝ embeds it into Pred. The monad-polymorphic example at the end of this chapter uses corner brackets for this reason. vcgen moves pure preconditions into the ordinary Lean context, where they become hypotheses of the verification conditions.

Assertions for State Monads

The predicate ItIsSecret expresses that a state of type String is "secret":

def ItIsSecret : String → Prop := fun s => s = "secret"

Entailment between such assertions is pointwise implication:

example : ItIsSecret ⊑ (⌜True⌝ : String → Prop) := ⊢ ItIsSecret ⊑ ⌜True⌝ All goals completed! 🐙

17.2.2. Exception Postconditions🔗

A postcondition for successful termination is a function from the return value to an assertion. Programs that can throw exceptions additionally require an exception postcondition that asserts what holds when the program throws an exception. The exception postcondition type of a given monad is determined by its WP instance.

For example, the WP instance for ExceptT String (StateM Nat) Bool determines Nat → Prop as the assertion type, hence Bool → Nat → Prop as the postcondition type, and String → Nat → Prop as the exception postcondition type. A monad without exceptions has the exception postcondition type Unit.

For a base monad with assertion type Pred and exception postcondition type EPred, an exception layer such as ExceptT ε contributes one more exception postcondition, which gives the type (ε → Pred) × EPred.

Since unit and pair types come with PartialOrder instances, these “stacks” of exception postconditions are automatically assertion types as well. The WP instances for monad transformers ensure that stacks of monad transformers have corresponding exception postcondition stacks.

syntaxException Postcondition Stacks

The notation EStack⟨e₁, e₂, ...⟩ abbreviates the type of exception postcondition stack e₁ × (e₂ × (... × Unit)), and the notation estack⟨v₁, v₂, ...⟩ builds a value (v₁, v₂, ..., ()) of such a stack.

term ::= ...
    | Exception postcondition stack **type**: `EStack⟨ε₁ → l, ε₂ → l⟩` is `(ε₁ → l) × (ε₂ → l) × EStack⟨⟩`.EStack⟨term,*⟩
term ::= ...
    | Exception postcondition stack **value**: `estack⟨e₁, e₂⟩` is `(e₁, e₂, ())`.estack⟨term,*⟩

Specifications for programs that might throw exceptions come in two varieties. The total correctness interpretation ⦃P⦄ prog ⦃Q'⦄ asserts that, given P holds, then prog terminates normally and Q' holds for the result. The partial correctness interpretation ⦃P⦄ prog ⦃Q'; ⊤⦄ asserts that, given P holds, and if prog terminates normally then Q' holds for the result. A triple without an explicit exception postcondition carries the bottom assertion (⊥ : EPred) and thus has the total interpretation; between ⊥ and ⊤, the exception postcondition expresses a spectrum of correctness properties.

17.2.3. Predicate Transformers🔗

A predicate transformer is a function from postconditions into assertions that describe preconditions.

🔗structure
Lean.Order.PredTrans.{u, v, w} (Pred : Type u) (EPosts : Type v) [PartialOrder Pred] [PartialOrder EPosts] (α : Type w) : Type (max (max u v) w)
Lean.Order.PredTrans.{u, v, w} (Pred : Type u) (EPosts : Type v) [PartialOrder Pred] [PartialOrder EPosts] (α : Type w) : Type (max (max u v) w)

PredTrans Pred EPosts α is the type of monotone predicate transformers with result type α, over an ordered type Pred of assertions and an ordered type EPosts of exception postconditions. PredTrans.apply : PredTrans Pred EPosts α → (α → Pred) → EPosts → Pred runs the predicate transformer, and PredTrans.apply_mono proves that it is monotone in both ordered arguments. PredTrans.mk constructs predicate transformers. The definition of PredTrans.apply is opaque, for the efficiency of kernel reduction.

The partial order on predicate transformers is inherited pointwise from the assertion order: x ⊑ y when x.apply post epost ⊑ y.apply post epost for all post and epost. Every predicate transformer is monotone: if post ⊑ post' and epost ⊑ epost', then x.apply post epost ⊑ x.apply post' epost'.

🔗theorem
Lean.Order.PredTrans.apply_mono.{u, v, w} {Pred : Type u} {EPosts : Type v} [PartialOrder Pred] [PartialOrder EPosts] {α : Type w} (t : PredTrans Pred EPosts α) {post post' : α → Pred} {eposts eposts' : EPosts} : post ⊑ post' → eposts ⊑ eposts' → t.apply post eposts ⊑ t.apply post' eposts'
Lean.Order.PredTrans.apply_mono.{u, v, w} {Pred : Type u} {EPosts : Type v} [PartialOrder Pred] [PartialOrder EPosts] {α : Type w} (t : PredTrans Pred EPosts α) {post post' : α → Pred} {eposts eposts' : EPosts} : post ⊑ post' → eposts ⊑ eposts' → t.apply post eposts ⊑ t.apply post' eposts'

Stronger postconditions give a stronger precondition.

Predicate transformers form a monad. The pure operator is the identity transformer; it simply instantiates the postcondition with its argument. The bind operator composes predicate transformers.

🔗def
Lean.Order.PredTrans.pure.{u, v, w} {Pred : Type u} {EPosts : Type v} [PartialOrder Pred] [PartialOrder EPosts] {α : Type w} (a : α) : PredTrans Pred EPosts α
Lean.Order.PredTrans.pure.{u, v, w} {Pred : Type u} {EPosts : Type v} [PartialOrder Pred] [PartialOrder EPosts] {α : Type w} (a : α) : PredTrans Pred EPosts α

pure a applies the postcondition to a.

🔗def
Lean.Order.PredTrans.bind.{u, v, w} {Pred : Type u} {EPosts : Type v} [PartialOrder Pred] [PartialOrder EPosts] {α β : Type w} (x : PredTrans Pred EPosts α) (f : α → PredTrans Pred EPosts β) : PredTrans Pred EPosts β
Lean.Order.PredTrans.bind.{u, v, w} {Pred : Type u} {EPosts : Type v} [PartialOrder Pred] [PartialOrder EPosts] {α β : Type w} (x : PredTrans Pred EPosts α) (f : α → PredTrans Pred EPosts β) : PredTrans Pred EPosts β

bind x f threads the postcondition through the continuation f.

The helper operators PredTrans.pushArg, PredTrans.pushExceptT, and PredTrans.pushOptionT modify a predicate transformer by adding a standard side effect. They are used to implement the WP instances for transformers such as StateT, ExceptT, and OptionT; they can also be used to implement monads that can be thought of in terms of one of these. For example, PredTrans.pushArg is typically used for state monads, but can also be used to implement a reader monad's instance, treating the reader's value as read-only state.

🔗def
Lean.Order.PredTrans.pushArg.{u, v, w, z} {Pred : Type u} {EPosts : Type v} [PartialOrder Pred] [PartialOrder EPosts] {α : Type w} {σ : Type z} (x : σ → PredTrans Pred EPosts (α × σ)) : PredTrans (σ → Pred) EPosts α
Lean.Order.PredTrans.pushArg.{u, v, w, z} {Pred : Type u} {EPosts : Type v} [PartialOrder Pred] [PartialOrder EPosts] {α : Type w} {σ : Type z} (x : σ → PredTrans Pred EPosts (α × σ)) : PredTrans (σ → Pred) EPosts α

Adds a state argument to a predicate transformer.

Given a state-dependent transformer σ → PredTrans Pred EPosts (α × σ), produces a transformer over σ → Pred that threads the state through postconditions.

🔗def
Lean.Order.PredTrans.pushExceptT.{u, v, w, z} {Pred : Type u} {EPosts : Type v} [PartialOrder Pred] [PartialOrder EPosts] {α : Type w} {ε : Type z} (x : PredTrans Pred EPosts (Except ε α)) : PredTrans Pred ((ε → Pred) × EPosts) α
Lean.Order.PredTrans.pushExceptT.{u, v, w, z} {Pred : Type u} {EPosts : Type v} [PartialOrder Pred] [PartialOrder EPosts] {α : Type w} {ε : Type z} (x : PredTrans Pred EPosts (Except ε α)) : PredTrans Pred ((ε → Pred) × EPosts) α

Adds an exception postcondition layer to a predicate transformer, mirroring ExceptT.

Given a transformer over Except ε α, produces one over α with an additional exception postcondition for ε. The normal and error postconditions are combined via pushExcept.

🔗def
Lean.Order.PredTrans.pushOptionT.{u, v, w} {Pred : Type u} {EPosts : Type v} [PartialOrder Pred] [PartialOrder EPosts] {α : Type w} (x : PredTrans Pred EPosts (Option α)) : PredTrans Pred ((Unit → Pred) × EPosts) α
Lean.Order.PredTrans.pushOptionT.{u, v, w} {Pred : Type u} {EPosts : Type v} [PartialOrder Pred] [PartialOrder EPosts] {α : Type w} (x : PredTrans Pred EPosts (Option α)) : PredTrans Pred ((Unit → Pred) × EPosts) α

Adds an early-termination layer to a predicate transformer, mirroring OptionT.

Given a transformer over Option α, produces one over α with an additional exception postcondition for the none case.

17.2.3.1. Weakest Preconditions🔗

The weakest precondition semantics of a program type is provided by the WP type class. An instance WP Prog Value Pred EPred interprets programs of type Prog with results of type Value as monotone predicate transformers over the assertion type Pred and the exception postcondition type EPred. The type Prog determines Value, Pred and EPred as outParams. The function wp applies the interpretation: wp prog post epost is the weakest precondition under which the program prog establishes the postcondition post and the exception postcondition epost.

🔗type class
Std.WP.WP.{u, v, w, w'} (Prog : Type u) (Value : outParam (Type v)) (Pred : outParam (Type w)) (EPosts : outParam (Type w')) [PartialOrder Pred] [PartialOrder EPosts] : Type (max (max (max u v) w) w')
Std.WP.WP.{u, v, w, w'} (Prog : Type u) (Value : outParam (Type v)) (Pred : outParam (Type w)) (EPosts : outParam (Type w')) [PartialOrder Pred] [PartialOrder EPosts] : Type (max (max (max u v) w) w')

Weakest precondition interpretation of a program type Prog whose results have type Value, as a monotone predicate transformer over assertions Pred with exception postconditions EPosts.

Std.WP.WP.mk.{u, v, w, w'}
trans : Prog → PredTrans Pred EPosts Value

The weakest precondition transformer for a program.

wpTrans : Prog → PredTrans Pred EPosts Value

Deprecated alias for trans; provide either field when defining an instance.

trans_monotone : ∀ (x : Prog), (WP.trans x).Monotone

Deprecated: every transformer is monotone by PredTrans.apply_mono.

wp_trans_monotone : ∀ (x : Prog), (WP.trans x).Monotone

Deprecated alias for trans_monotone.

🔗def
Std.WP.WP.wp.{u, v, w, w'} {Prog : Type u} {Value : Type v} {Pred : Type w} {EPosts : Type w'} [PartialOrder Pred] [PartialOrder EPosts] [self : WP Prog Value Pred EPosts] (x : Prog) (post : Value → Pred) (eposts : EPosts) : Pred
Std.WP.WP.wp.{u, v, w, w'} {Prog : Type u} {Value : Type v} {Pred : Type w} {EPosts : Type w'} [PartialOrder Pred] [PartialOrder EPosts] [self : WP Prog Value Pred EPosts] (x : Prog) (post : Value → Pred) (eposts : EPosts) : Pred

Weakest precondition of x for normal postcondition post and exception postcondition eposts. The WP interpretation can be supplied explicitly via dot notation (inst.wp x post eposts).

A program prog that is conjunctive distributes a weakest precondition of a meet of two postconditions into a meet of the weakest preconditions of the postconditions. The type class WP.IsConjunctive captures this property, which allows two specifications for prog to be combined into a single strongest one. This is analogous to Triple.and, which combines Hoare triples.

🔗def
Std.WP.WP.IsConjunctive.{u, v, w, z} {Prog : Type u} {Value : Type v} {Pred : Type w} {EPosts : Type z} [CompleteLattice Pred] [CompleteLattice EPosts] [WP Prog Value Pred EPosts] (x : Prog) : Prop
Std.WP.WP.IsConjunctive.{u, v, w, z} {Prog : Type u} {Value : Type v} {Pred : Type w} {EPosts : Type z} [CompleteLattice Pred] [CompleteLattice EPosts] [WP Prog Value Pred EPosts] (x : Prog) : Prop

The transformer of the program x is conjunctive.

17.2.3.2. Monads That Preserve Weakest Preconditions🔗

Most of the built-in specification lemmas for vcgen rely on the presence of a MonadicWP instance. A WP instance is provided for a particular type, but a monad is a polymorphic type. StateM Nat Unit and StateM Nat String are different types, but their weakest preconditions should be related. Instances of MonadicWP assign a WP interpretation to every type that the monad can be applied to. The accompanying class MonadicWP.IsLaxDistrib states that this interpretation is a lax monad morphism, which means that the interpretation is sound for the monad's implementations of pure and bind:

  • Soundness with respect to the monad's pure means that, for every postcondition, the weakest precondition of pure a is entailed by the result of applying PredTrans.pure a to that postcondition, which simply asserts the postcondition for a.

  • Soundness with respect to the monad's bind means that, for every postcondition, the weakest precondition of x >>= f is entailed by the result of applying WP.trans x >>= WP.trans ∘ f to that postcondition, where >>= is the bind of predicate transformers.

Informally, an instance of MonadicWP.IsLaxDistrib m means that the weakest precondition operation distributes, up to entailment, over the monad's operations. The distributive property is called lax because it demands only entailments, rather than equivalences or equality. Given such an instance, to prove something about a Lean.Parser.Term.do : termdo block it suffices to prove it about the chain of elements of the block. In other words, a MonadicWP instance together with MonadicWP.IsLaxDistrib enables compositional reasoning about Lean.Parser.Term.do : termdo blocks.

🔗type class
Std.WP.MonadicWP.{u, v, w, w'} (m : Type u → Type v) (Pred : outParam (Type w)) (EPosts : outParam (Type w')) [PartialOrder Pred] [PartialOrder EPosts] : Type (max (max (max (u + 1) v) w) w')
Std.WP.MonadicWP.{u, v, w, w'} (m : Type u → Type v) (Pred : outParam (Type w)) (EPosts : outParam (Type w')) [PartialOrder Pred] [PartialOrder EPosts] : Type (max (max (max (u + 1) v) w) w')

The WP interpretation of all programs m α of a monad m.

Std.WP.MonadicWP.mk.{u, v, w, w'}
toWP : (α : Type u) → WP (m α) α Pred EPosts

The interpretation of the programs m α.

🔗type class
Std.WP.MonadicWP.IsLaxDistrib.{u, v, w, w'} (m : Type u → Type v) {Pred : outParam (Type w)} {EPosts : outParam (Type w')} [Monad m] [PartialOrder Pred] [PartialOrder EPosts] [MonadicWP m Pred EPosts] : Prop
Std.WP.MonadicWP.IsLaxDistrib.{u, v, w, w'} (m : Type u → Type v) {Pred : outParam (Type w)} {EPosts : outParam (Type w')} [Monad m] [PartialOrder Pred] [PartialOrder EPosts] [MonadicWP m Pred EPosts] : Prop

wp is sound for pure and bind: post a implies wp (pure a) post eposts, and wp x (fun a => wp (f a) post eposts) eposts implies wp (x >>= f) post eposts. So a proof of a program can proceed through its parts.

Std.WP.MonadicWP.IsLaxDistrib.mk.{u, v, w, w'}
pure_le : ∀ {α : Type u} (a : α), pure a ⊑ WP.trans (pure a)

pure a implies the transformer of pure a.

bind_le : ∀ {α β : Type u} (x : m α) (f : α → m β),
  (do
      let a ← WP.trans x
      WP.trans (f a)) ⊑
    WP.trans (x >>= f)

The bind of the transformers implies the transformer of x >>= f.

Some monadic predicate transformers are strict monad morphisms. This means that the interpretation is complete with respect to pure and bind:

  • Completeness with respect to the monad's pure means that, for every postcondition, the weakest precondition of pure a is equal to the result of applying PredTrans.pure a to that postcondition, which simply asserts the postcondition for a.

  • Completeness with respect to the monad's bind means that, for every postcondition, the weakest precondition of x >>= f is equal to the result of applying WP.trans x >>= WP.trans ∘ f to that postcondition, where >>= is the bind of predicate transformers.

An instance of MonadicWP.IsDistrib m means that the weakest precondition operation distributes over the monad's operations without loss of logical strength. In particular, rewriting wp (x >>= f) post eposts into wp x (fun a => wp (f a) post eposts) eposts results in a goal that's provable exactly when the original goal was provable. These instances enable the lemmas MonadicWP.wp_pure_eq and MonadicWP.wp_bind_eq to be used with rw and simp to rewrite goals that use predicate transformers.

🔗type class
Std.WP.MonadicWP.IsDistrib.{u, v, w, w'} (m : Type u → Type v) {Pred : outParam (Type w)} {EPosts : outParam (Type w')} [Monad m] [PartialOrder Pred] [PartialOrder EPosts] [MonadicWP m Pred EPosts] : Prop
Std.WP.MonadicWP.IsDistrib.{u, v, w, w'} (m : Type u → Type v) {Pred : outParam (Type w)} {EPosts : outParam (Type w')} [Monad m] [PartialOrder Pred] [PartialOrder EPosts] [MonadicWP m Pred EPosts] : Prop

wp distributes exactly over pure and bind: the preconditions of IsLaxDistrib are also necessary, so rewriting wp (x >>= f) into the composed precondition loses nothing.

Std.WP.MonadicWP.IsDistrib.mk.{u, v, w, w'}
pure_le : ∀ {α : Type u} (a : α), pure a ⊑ WP.trans (pure a)
Inherited from
  1. MonadicWP.IsLaxDistrib m
bind_le : ∀ {α β : Type u} (x : m α) (f : α → m β),
  (do
      let a ← WP.trans x
      WP.trans (f a)) ⊑
    WP.trans (x >>= f)
Inherited from
  1. MonadicWP.IsLaxDistrib m
trans_pure : ∀ {α : Type u} (a : α), WP.trans (pure a) = pure a

The transformer of pure a is pure a.

trans_bind : ∀ {α β : Type u} (x : m α) (f : α → m β),
  WP.trans (x >>= f) = do
    let a ← WP.trans x
    WP.trans (f a)

The transformer of a bind is the bind of the transformers.

Missing MonadicWP Instance

The single-field structure Identity acts like the identity monad Id. It has a WP instance, but no MonadicWP instance:

structure Identity (α : Type u) where run : α variable {α : Type u} instance : Monad Identity where pure x := ⟨x⟩ bind x f := f x.run instance : WP (Identity α) α Prop EStack⟨⟩ where trans x := PredTrans.mk (apply := fun post _ => post x.run) (apply_mono := fun hpost _ => hpost x.run) theorem Identity.of_run_eq_wp {x : α} {prog : Identity α} (h : Identity.run prog = x) (P : α → Prop) (hwp : wp prog P ()) : P x := α:Type ux:αprog:Identity αh:prog.run = xP:α → Prophwp:wp prog P ()⊢ P x All goals completed! 🐙

The missing instance prevents vcgen from using its specifications for pure and bind. For example, the following function reverses a list with a Lean.Parser.Term.doFor : doElem`for x in e do s` iterates over `e` assuming `e`'s type has an instance of the `ForIn` typeclass. `break` and `continue` are supported inside `for` loops. `for x in e, x2 in e2, ... do s` iterates over the given collections in parallel, until at least one of them is exhausted. The types of `e2` etc. must implement the `Std.ToStream` typeclass.for loop in Identity:

def rev (xs : List α) : Identity (List α) := do let mut out := [] for x in xs do out := x :: out return out

The theorem rev_correct states that rev agrees with List.reverse. Without a MonadicWP instance, vcgen cannot decompose rev into a sequence of steps in Id and reports that no specification applies to the program:

theorem rev_correct {xs : List α} : (rev xs).run = xs.reverse := α:Type uxs:List α⊢ (rev xs).run = xs.reverse α:Type uxs:List αx:List αh:(rev xs).run = x⊢ x = xs.reverse α:Type uxs:List αx:List αh:(rev xs).run = x⊢ wp (rev xs) (fun x => x = xs.reverse) () No spec applicable to program do let __s ← forIn xs out fun x __s => have out := __s; have out := x :: out; pure (ForInStep.yield out) have out : List α := __s pure out in monad Identity. Candidates were [SpecProof.global Std.WP.Spec.bind].All goals completed! 🐙 [rev]
No spec applicable to program do
  let __s ←
    forIn xs out fun x __s =>
        have out := __s;
        have out := x :: out;
        pure (ForInStep.yield out)
  have out : List α := __s
  pure out in monad Identity. Candidates were [SpecProof.global Std.WP.Spec.bind].

When no specification is applicable to bind, the problem is usually a missing MonadicWP instance. The issue can be resolved by adding a suitable instance:

instance : MonadicWP Identity Prop EStack⟨⟩ where toWP _ := inferInstance instance : MonadicWP.IsLaxDistrib Identity where pure_le _ := fun _ _ => Pred:Type uEPred:Type vα✝¹:Type winst✝²:PartialOrder Predinst✝¹:PartialOrder EPredProg:Type uValue:Type vinst✝:WP Prog Value Pred EPredprog:Progpost:Value → Predepost:EPredα:Type uα✝:Type u_1x✝²:α✝x✝¹:α✝ → Propx✝:EStack⟨⟩⊢ (pure x✝²).apply x✝¹ x✝ ⊑ (WP.trans (pure x✝²)).apply x✝¹ x✝ All goals completed! 🐙 bind_le _ _ := fun _ _ => Pred:Type uEPred:Type vα✝¹:Type winst✝²:PartialOrder Predinst✝¹:PartialOrder EPredProg:Type uValue:Type vinst✝:WP Prog Value Pred EPredprog:Progpost:Value → Predepost:EPredα:Type uα✝:Type u_1β✝:Type u_1x✝³:Identity α✝x✝²:α✝ → Identity β✝x✝¹:β✝ → Propx✝:EStack⟨⟩⊢ (do let a ← WP.trans x✝³ WP.trans (x✝² a)).apply x✝¹ x✝ ⊑ (WP.trans (x✝³ >>= x✝²)).apply x✝¹ x✝ All goals completed! 🐙

With this instance, and a suitable invariant, vcgen and the grind-mode tactic finish can prove the theorem.

theorem rev_correct {xs : List α} : (rev xs).run = xs.reverse := α:Type uxs:List α⊢ (rev xs).run = xs.reverse α:Type uxs:List αx:List αh:(rev xs).run = x⊢ x = xs.reverse α:Type uxs:List αx:List αh:(rev xs).run = x⊢ wp (rev xs) (fun x => x = xs.reverse) () α:Type uxs:List αx:List αh:(rev xs).run = x⊢ wp (do let __s ← forIn xs [] fun x __s => pure (ForInStep.yield (x :: __s)) pure __s) (fun x => x = xs.reverse) () α:Type uxs:List αx:List αh:(rev xs).run = x⊢ [] = [].reverseα:Type uxs:List αx:List αh:(rev xs).run = xpref✝:List αcur✝:αsuff✝:List α_h✝:xs = pref✝ ++ cur✝ :: suff✝b✝:List α⊢ cur✝ :: pref✝.reverse = (pref✝ ++ [cur✝]).reverse invariants · fun pref suff out => out = pref.reverse with All goals completed! 🐙

17.2.3.3. Soundness Lemmas🔗

Monads that can be invoked from pure code typically provide an invocation operator that takes any required input state as a parameter and returns either a value paired with an output state or some kind of exceptional value. Examples include StateT.run, ExceptT.run, and Id.run. Soundness lemmas provide a bridge between statements about invocations of monadic programs and those programs' weakest precondition semantics as given by their WP instances. They show that a property about the invocation is true if its weakest precondition is true.

🔗theorem
Std.WP.Id.of_run_eq_wp.{u} {α : Type u} {x : α} {prog : Id α} (h : prog.run = x) (P : α → Prop) (hwp : wp prog P ()) : P x
Std.WP.Id.of_run_eq_wp.{u} {α : Type u} {x : α} {prog : Id α} (h : prog.run = x) (P : α → Prop) (hwp : wp prog P ()) : P x

Soundness for Id: if wp prog P holds, then P holds of Id.run prog.

🔗theorem
Std.WP.StateM.of_run_eq_wp.{u_1} {α σ : Type u_1} {x : α × σ} {prog : StateM σ α} {s : σ} (h : StateT.run prog s = x) (P : α × σ → Prop) (hwp : wp prog (fun a s' => P (a, s')) () s) : P x
Std.WP.StateM.of_run_eq_wp.{u_1} {α σ : Type u_1} {x : α × σ} {prog : StateM σ α} {s : σ} (h : StateT.run prog s = x) (P : α × σ → Prop) (hwp : wp prog (fun a s' => P (a, s')) () s) : P x

Soundness for StateM: if wp prog P s holds, then P holds of the value and final state of StateT.run prog s.

🔗theorem
Std.WP.StateM.of_run'_eq_wp {α σ : Type} {x : α} {prog : StateM σ α} {s : σ} (h : StateT.run' prog s = x) (P : α → Prop) (hwp : wp prog (fun a x => P a) () s) : P x
Std.WP.StateM.of_run'_eq_wp {α σ : Type} {x : α} {prog : StateM σ α} {s : σ} (h : StateT.run' prog s = x) (P : α → Prop) (hwp : wp prog (fun a x => P a) () s) : P x

Soundness for StateM, at the value alone: if wp prog P s holds, then P holds of StateT.run' prog s.

🔗theorem
Std.WP.ReaderM.of_run_eq_wp {α ρ : Type} {x : α} {prog : ReaderM ρ α} {r : ρ} (h : ReaderT.run prog r = x) (P : α → Prop) (hwp : wp prog (fun a x => P a) () r) : P x
Std.WP.ReaderM.of_run_eq_wp {α ρ : Type} {x : α} {prog : ReaderM ρ α} {r : ρ} (h : ReaderT.run prog r = x) (P : α → Prop) (hwp : wp prog (fun a x => P a) () r) : P x

Soundness for ReaderM: if wp prog P r holds, then P holds of ReaderT.run prog r.

🔗theorem
Std.WP.Except.of_eq_wp {ε α : Type} {x prog : Except ε α} (h : prog = x) (P : Except ε α → Prop) (hwp : wp prog (fun a => P (Except.ok a)) fun e => P (Except.error e)) : P x
Std.WP.Except.of_eq_wp {ε α : Type} {x prog : Except ε α} (h : prog = x) (P : Except ε α → Prop) (hwp : wp prog (fun a => P (Except.ok a)) fun e => P (Except.error e)) : P x

Soundness for Except: the postcondition takes an ok case and an error case, and wp prog holds of prog itself.

🔗theorem
Std.WP.Option.of_eq_wp.{u} {α : Type u} {x prog : Option α} (h : prog = x) (P : Option α → Prop) (hwp : wp prog (fun a => P (some a)) fun x => P none) : P x
Std.WP.Option.of_eq_wp.{u} {α : Type u} {x prog : Option α} (h : prog = x) (P : Option α → Prop) (hwp : wp prog (fun a => P (some a)) fun x => P none) : P x

Soundness for Option: the postcondition takes a some case and a none case, and wp prog holds of prog itself.

🔗theorem
Std.WP.EStateM.of_run_eq_wp {ε σ α : Type} {x : EStateM.Result ε σ α} {prog : EStateM ε σ α} {s : σ} (h : prog.run s = x) (P : EStateM.Result ε σ α → Prop) (hwp : wp prog (fun a s' => P (EStateM.Result.ok a s')) (fun e s' => P (EStateM.Result.error e s')) s) : P x
Std.WP.EStateM.of_run_eq_wp {ε σ α : Type} {x : EStateM.Result ε σ α} {prog : EStateM ε σ α} {s : σ} (h : prog.run s = x) (P : EStateM.Result ε σ α → Prop) (hwp : wp prog (fun a s' => P (EStateM.Result.ok a s')) (fun e s' => P (EStateM.Result.error e s')) s) : P x

Soundness for EStateM: if wp prog P s holds, then P holds of (prog.run s).

17.2.4. Hoare Triples🔗

A Hoare triple (Hoare, 1969)Marginal noteC. A. R. Hoare (1969). “An Axiomatic Basis for Computer Programming”. Communications of the ACM. 12(10), pp. 576–583. consists of a precondition, a program, and a postcondition. Running the program in a state for which the precondition is true results in a state where the postcondition is true.

🔗structure
Std.WP.Triple.{u, v, w, w'} {Pred : Type w} {EPosts : Type w'} {Prog : Type u} {Value : Type v} [PartialOrder Pred] [PartialOrder EPosts] (x : Prog) [WP Prog Value Pred EPosts] (pre : Pred) (post : Value → Pred) (eposts : EPosts) : Prop
Std.WP.Triple.{u, v, w, w'} {Pred : Type w} {EPosts : Type w'} {Prog : Type u} {Value : Type v} [PartialOrder Pred] [PartialOrder EPosts] (x : Prog) [WP Prog Value Pred EPosts] (pre : Pred) (post : Value → Pred) (eposts : EPosts) : Prop

A Hoare triple for reasoning about programs. A Hoare triple Triple x pre post eposts is a specification for x: if assertion pre holds before x, then postcondition post holds after running x (and eposts handles any errors).

Std.WP.Triple.intro.{u, v, w, w'}

Construct a triple from a weakest precondition entailment.

le_wp : pre ⊑ wp x post eposts

The weakest precondition entailment witnessing the triple.

syntaxHoare Triples
term ::= ...
    | Hoare triple notation without exception postcondition (defaults to `⊥`). An optional `(m := …)`
after the precondition ascribes the program to monad `…`.⦃ term ⦄ term ⦃ term ⦄
term ::= ...
    | Hoare triple notation with an exception postcondition:
`⦃ P ⦄ x ⦃ Q; E ⦄ := Triple x P Q E`.⦃ term ⦄ term ⦃ term; term ⦄

⦃ P ⦄ x ⦃ Q; E ⦄ is syntactic sugar for Triple x P Q E. When the exception postcondition is omitted, as in ⦃ P ⦄ x ⦃ Q ⦄, it defaults to the bottom assertion ⊥, asserting that the program does not throw an exception.

🔗theorem
Std.WP.Triple.and.{u, v, w, w'} {Prog : Type u} {Value : Type v} {Pred : Type w} {EPosts : Type w'} [CompleteLattice Pred] [CompleteLattice EPosts] [WP Prog Value Pred EPosts] {x : Prog} [WP.IsConjunctive x] {pre₁ pre₂ : Pred} {post₁ post₂ : Value → Pred} {eposts₁ eposts₂ : EPosts} (h₁ : ⦃ pre₁ ⦄ x ⦃ post₁; eposts₁ ⦄) (h₂ : ⦃ pre₂ ⦄ x ⦃ post₂; eposts₂ ⦄) : ⦃ pre₁ ⊓ pre₂ ⦄ x ⦃ post₁ ⊓ post₂; eposts₁ ⊓ eposts₂ ⦄
Std.WP.Triple.and.{u, v, w, w'} {Prog : Type u} {Value : Type v} {Pred : Type w} {EPosts : Type w'} [CompleteLattice Pred] [CompleteLattice EPosts] [WP Prog Value Pred EPosts] {x : Prog} [WP.IsConjunctive x] {pre₁ pre₂ : Pred} {post₁ post₂ : Value → Pred} {eposts₁ eposts₂ : EPosts} (h₁ : ⦃ pre₁ ⦄ x ⦃ post₁; eposts₁ ⦄) (h₂ : ⦃ pre₂ ⦄ x ⦃ post₂; eposts₂ ⦄) : ⦃ pre₁ ⊓ pre₂ ⦄ x ⦃ post₁ ⊓ post₂; eposts₁ ⊓ eposts₂ ⦄

Conjunction of two Hoare triple specifications for a program x. This theorem decomposes proofs: prove unrelated facts about x separately, then combine them here.

🔗theorem
Std.WP.Triple.mp.{u, v, w, w'} {Prog : Type u} {Value : Type v} {Pred : Type w} {EPosts : Type w'} [CompleteLattice Pred] [CompleteLattice EPosts] [WP Prog Value Pred EPosts] {x : Prog} [WP.IsConjunctive x] [Heyting Pred] [Heyting EPosts] {pre₁ pre₂ : Pred} {post₁ post₂ : Value → Pred} {eposts₁ eposts₂ : EPosts} (h₁ : ⦃ pre₁ ⦄ x ⦃ post₁; eposts₁ ⦄) (h₂ : ⦃ pre₂ ⦄ x ⦃ post₁ ⇨ post₂; eposts₁ ⇨ eposts₂ ⦄) : ⦃ pre₁ ⊓ pre₂ ⦄ x ⦃ post₁ ⊓ post₂; eposts₁ ⊓ eposts₂ ⦄
Std.WP.Triple.mp.{u, v, w, w'} {Prog : Type u} {Value : Type v} {Pred : Type w} {EPosts : Type w'} [CompleteLattice Pred] [CompleteLattice EPosts] [WP Prog Value Pred EPosts] {x : Prog} [WP.IsConjunctive x] [Heyting Pred] [Heyting EPosts] {pre₁ pre₂ : Pred} {post₁ post₂ : Value → Pred} {eposts₁ eposts₂ : EPosts} (h₁ : ⦃ pre₁ ⦄ x ⦃ post₁; eposts₁ ⦄) (h₂ : ⦃ pre₂ ⦄ x ⦃ post₁ ⇨ post₂; eposts₁ ⇨ eposts₂ ⦄) : ⦃ pre₁ ⊓ pre₂ ⦄ x ⦃ post₁ ⊓ post₂; eposts₁ ⊓ eposts₂ ⦄

Modus ponens for two Hoare triple specifications of a program x. This theorem separates proofs. Let h₁ establish a basic postcondition post₁ for x, and let h₂ establish the advanced postcondition post₂ under the assumption post₁. Then mp h₁ h₂ establishes post₂ for x.

17.2.5. Specification Lemmas🔗

Specification lemmas are designated theorems that associate a Hoare triple with a program construct, such as bind, pure, a loop, or an application of a library function. A given program construct may have multiple specification lemmas that are applicable in different situations; they are tried in priority order until one can be instantiated.

The vcgen tactic decomposes a goal P ⊑ wp prog Q E by applying a specification lemma whose program matches prog, as the section on verification conditions describes. If no specification lemma applies to prog, then vcgen reports an error that names prog and the candidate lemmas. Specification lemmas make reasoning about programs modular: the specification lemma of a function f is proved once, and vcgen applies it at every call of f without unfolding the definition of f. In this respect, pure and bind are ordinary functions: the specification lemmas Spec.pure and Spec.bind hold in every monad with a MonadicWP instance.

When applied to a theorem whose statement is a Hoare triple, the spec attribute registers the theorem as a specification lemma. These lemmas are used in order of priority.

The spec attribute may also be applied to definitions. On definitions, it indicates that the definition should be unfolded during verification condition generation.

attributeSpecification Lemmas
attr ::= ...
    | Marks a specification for the `vcgen` tactic.

* On a theorem `foo_spec : ⦃P⦄ foo a b c ⦃Q⦄`, `vcgen` uses `foo_spec` for calls to `foo`.
* On a definition `foo` or an equation that `@[simp]` accepts, `vcgen` rewrites calls with its
  equations.spec prio?

Marks a specification for the vcgen tactic.

  • On a theorem foo_spec : ⦃P⦄ foo a b c ⦃Q⦄, vcgen uses foo_spec for calls to foo.

  • On a definition foo or an equation that @[simp] accepts, vcgen rewrites calls with its equations.

A logical variable is a universally quantified variable of a specification lemma that does not occur in the program. Logical variables are used to relate the initial state to the final state and the return value.

An auto-framing specification is a specification lemma whose postcondition is a universally quantified variable, with a precondition that is stated in terms of that variable. When vcgen applies an auto-framing specification, unification instantiates the postcondition with the assertion that the rest of the program requires; this means that there's no need to prove that the postcondition entails the subsequent precondition. Every fact that the postcondition states about parts of the state that the program does not change is preserved without further proof. As an example, the specification lemma Spec.bind is auto-framing: its precondition is the weakest precondition of the first action with respect to the weakest precondition of the second.

Std.WP.Spec.bind.{u, v, w, w'} {m : Type u → Type v} {Pred : Type w} {EPosts : Type w'} [Lean.Order.PartialOrder Pred] [Lean.Order.PartialOrder EPosts] [MonadicWP m Pred EPosts] {α β : Type u} {post : β → Pred} {eposts : EPosts} [Monad m] [MonadicWP.IsLaxDistrib m] (x : m α) (f : α → m β) : ⦃ wp x (fun a => binderNameHint a f (wp (f a) post eposts)) eposts ⦄ x >>= f ⦃ post; eposts ⦄
Logical Variables

The function double doubles the value of a Nat state:

def double : StateM Nat Unit := do modify (2 * ·)

Its specification should relate the initial and final states, but it cannot know their precise values. The specification uses a logical variable to stand for the initial state:

theorem double_spec {n : Nat} : ⦃ fun s => s = n ⦄ double ⦃ fun _ s => s = 2 * n ⦄ := n:Nat⊢ ⦃ fun s => s = n ⦄ double ⦃ fun x s => s = 2 * n ⦄ n:Nat⊢ ⦃ fun s => s = n ⦄ modify fun x => 2 * x ⦃ fun x s => s = 2 * n ⦄ All goals completed! 🐙 with finish

The assertion in the precondition is a function because the assertion type of StateM Nat is Nat → Prop.

17.2.6. Invariant Specifications🔗

The specification lemmas for ForIn.forIn and ForIn'.forIn' take parameters of type Invariant, and vcgen ensures that invariants are not accidentally generated by other automation.

🔗def
Std.WP.Invariant.{u₁, u₂, uₚ} (α : Type u₁) (β : Type u₂) (Pred : Type uₚ) : Type (max (max u₂ uₚ) u₁)
Std.WP.Invariant.{u₁, u₂, uₚ} (α : Type u₁) (β : Type u₂) (Pred : Type uₚ) : Type (max (max u₂ uₚ) u₁)

The type of loop invariants used by the specifications of for ... in ... loops. A loop invariant maps the elements consumed so far, the elements remaining, and the accumulator state to an assertion.

Invariants use lists to model the sequence of values in a Lean.Parser.Term.doFor : doElem`for x in e do s` iterates over `e` assuming `e`'s type has an instance of the `ForIn` typeclass. `break` and `continue` are supported inside `for` loops. `for x in e, x2 in e2, ... do s` iterates over the given collections in parallel, until at least one of them is exhausted. The types of `e2` etc. must implement the `Std.ToStream` typeclass.for loop. An invariant is a function of the prefix of elements that the loop has already consumed, the suffix of elements that remain, the current accumulator state, and any further state arguments of the monad's assertion language.

When a loop contains a Lean.Parser.Term.doReturn : doElem`return e` inside of a `do` block makes the surrounding block evaluate to `pure e`, skipping any further statements. Note that uses of the `do` keyword in other syntax like in `for _ in _ do` do not constitute a surrounding block in this sense; in supported editors, the corresponding `do` keyword of the surrounding block is highlighted when hovering over `return`. The term `e` can start on a later line if it starts in a column to the right of `return`. `return` not followed by such a term is equivalent to `return ()`.return, the loop's state type includes an additional Option value that tracks whether an early return occurred, and if so, the returned value. In other words, the state type has the form Option γ × β. The first projection is none when no early return has occurred, and some x when x is returned early.

The specification lemma Spec.forIn_pure_earlyReturn applies to loops that return early. It provides an interface for reasoning about early return directly, rather than via the encoding. In addition to Spec.forIn_pure_earlyReturn, there are similar special-purpose lemmas for other structures that support loops.

🔗theorem
Std.WP.Spec.forIn_pure_earlyReturn.{u₁, u₂, v, w, uₚ, uₑ} {α : Type u₁} {β : Type u₂} {m : Type u₂ → Type v} {Pred : Type uₚ} {EPosts : Type uₑ} [CompleteLattice Pred] [PartialOrder EPosts] [MonadicWP m Pred EPosts] [Monad m] [MonadicWP.IsLaxDistrib m] {ρ : Type w} [ForIn m ρ α] [ForIn Id ρ α] [Std.Internal.PureForIn m ρ α] {γ δ : Type u₂} {xs : ρ} {init : β} {f : α → Option γ × β → m (ForInStep (Option γ × β))} {kRet : Option γ × β → γ → m δ} {k : Option γ × β → m δ} {post : δ → Pred} {eposts : EPosts} (inv : Invariant α β Pred) (step : ∀ (pref : List α) (cur : α) (suff : List α), ForIn.toList xs = pref ++ cur :: suff → ∀ (b : β), ⦃ inv pref (cur :: suff) b ⦄ f cur (none, b) ⦃ fun r => match r with | ForInStep.yield (none, b') => inv (pref ++ [cur]) suff b' | ForInStep.done (none, b') => inv (ForIn.toList xs) [] b' | ForInStep.done (some x, b') => wp (kRet (some x, b') x) post eposts | ForInStep.yield (some val, snd) => ⊥; eposts ⦄) (exit : ∀ (b : β), ⦃ inv (ForIn.toList xs) [] b ⦄ k (none, b) ⦃ post; eposts ⦄) : ⦃ inv [] (ForIn.toList xs) init ⦄ do let s ← forIn xs (none, init) f match s.fst with | some x => kRet s x | none => k s ⦃ post; eposts ⦄
Std.WP.Spec.forIn_pure_earlyReturn.{u₁, u₂, v, w, uₚ, uₑ} {α : Type u₁} {β : Type u₂} {m : Type u₂ → Type v} {Pred : Type uₚ} {EPosts : Type uₑ} [CompleteLattice Pred] [PartialOrder EPosts] [MonadicWP m Pred EPosts] [Monad m] [MonadicWP.IsLaxDistrib m] {ρ : Type w} [ForIn m ρ α] [ForIn Id ρ α] [Std.Internal.PureForIn m ρ α] {γ δ : Type u₂} {xs : ρ} {init : β} {f : α → Option γ × β → m (ForInStep (Option γ × β))} {kRet : Option γ × β → γ → m δ} {k : Option γ × β → m δ} {post : δ → Pred} {eposts : EPosts} (inv : Invariant α β Pred) (step : ∀ (pref : List α) (cur : α) (suff : List α), ForIn.toList xs = pref ++ cur :: suff → ∀ (b : β), ⦃ inv pref (cur :: suff) b ⦄ f cur (none, b) ⦃ fun r => match r with | ForInStep.yield (none, b') => inv (pref ++ [cur]) suff b' | ForInStep.done (none, b') => inv (ForIn.toList xs) [] b' | ForInStep.done (some x, b') => wp (kRet (some x, b') x) post eposts | ForInStep.yield (some val, snd) => ⊥; eposts ⦄) (exit : ∀ (b : β), ⦃ inv (ForIn.toList xs) [] b ⦄ k (none, b) ⦃ post; eposts ⦄) : ⦃ inv [] (ForIn.toList xs) init ⦄ do let s ← forIn xs (none, init) f match s.fst with | some x => kRet s x | none => k s ⦃ post; eposts ⦄
🔗theorem
Std.WP.Spec.forIn'_pure_earlyReturn.{u₁, u₂, v, w, uₚ, uₑ} {α : Type u₁} {β : Type u₂} {m : Type u₂ → Type v} {Pred : Type uₚ} {EPosts : Type uₑ} [CompleteLattice Pred] [PartialOrder EPosts] [MonadicWP m Pred EPosts] [Monad m] [MonadicWP.IsLaxDistrib m] {ρ : Type w} {d : Membership α ρ} [ForIn' m ρ α d] [ForIn Id ρ α] [Std.Internal.LawfulMemForInId ρ α] [Std.Internal.PureForIn' m ρ α] {γ δ : Type u₂} {xs : ρ} {init : β} {f : (a : α) → a ∈ xs → Option γ × β → m (ForInStep (Option γ × β))} {kRet : Option γ × β → γ → m δ} {k : Option γ × β → m δ} {post : δ → Pred} {eposts : EPosts} (inv : Invariant α β Pred) (step : ∀ (pref : List α) (cur : α) (suff : List α) (h : ForIn.toList xs = pref ++ cur :: suff) (b : β), ⦃ inv pref (cur :: suff) b ⦄ f cur ⋯ (none, b) ⦃ fun r => match r with | ForInStep.yield (none, b') => inv (pref ++ [cur]) suff b' | ForInStep.done (none, b') => inv (ForIn.toList xs) [] b' | ForInStep.done (some x, b') => wp (kRet (some x, b') x) post eposts | ForInStep.yield (some val, snd) => ⊥; eposts ⦄) (exit : ∀ (b : β), ⦃ inv (ForIn.toList xs) [] b ⦄ k (none, b) ⦃ post; eposts ⦄) : ⦃ inv [] (ForIn.toList xs) init ⦄ do let s ← forIn' xs (none, init) f match s.fst with | some x => kRet s x | none => k s ⦃ post; eposts ⦄
Std.WP.Spec.forIn'_pure_earlyReturn.{u₁, u₂, v, w, uₚ, uₑ} {α : Type u₁} {β : Type u₂} {m : Type u₂ → Type v} {Pred : Type uₚ} {EPosts : Type uₑ} [CompleteLattice Pred] [PartialOrder EPosts] [MonadicWP m Pred EPosts] [Monad m] [MonadicWP.IsLaxDistrib m] {ρ : Type w} {d : Membership α ρ} [ForIn' m ρ α d] [ForIn Id ρ α] [Std.Internal.LawfulMemForInId ρ α] [Std.Internal.PureForIn' m ρ α] {γ δ : Type u₂} {xs : ρ} {init : β} {f : (a : α) → a ∈ xs → Option γ × β → m (ForInStep (Option γ × β))} {kRet : Option γ × β → γ → m δ} {k : Option γ × β → m δ} {post : δ → Pred} {eposts : EPosts} (inv : Invariant α β Pred) (step : ∀ (pref : List α) (cur : α) (suff : List α) (h : ForIn.toList xs = pref ++ cur :: suff) (b : β), ⦃ inv pref (cur :: suff) b ⦄ f cur ⋯ (none, b) ⦃ fun r => match r with | ForInStep.yield (none, b') => inv (pref ++ [cur]) suff b' | ForInStep.done (none, b') => inv (ForIn.toList xs) [] b' | ForInStep.done (some x, b') => wp (kRet (some x, b') x) post eposts | ForInStep.yield (some val, snd) => ⊥; eposts ⦄) (exit : ∀ (b : β), ⦃ inv (ForIn.toList xs) [] b ⦄ k (none, b) ⦃ post; eposts ⦄) : ⦃ inv [] (ForIn.toList xs) init ⦄ do let s ← forIn' xs (none, init) f match s.fst with | some x => kRet s x | none => k s ⦃ post; eposts ⦄
🔗theorem
Std.WP.Spec.forIn_string_earlyReturn.{u₂, v, uₚ, uₑ} {β : Type u₂} {m : Type u₂ → Type v} {Pred : Type uₚ} {EPosts : Type uₑ} [CompleteLattice Pred] [PartialOrder EPosts] [MonadicWP m Pred EPosts] [Monad m] [LawfulMonad m] [MonadicWP.IsLaxDistrib m] {s : String} {γ δ : Type u₂} {init : β} {f : Char → Option γ × β → m (ForInStep (Option γ × β))} {kRet : Option γ × β → γ → m δ} {k : Option γ × β → m δ} {post : δ → Pred} {eposts : EPosts} (inv : StringInvariant s β Pred) (step : ∀ (pos : s.Pos) (b : β) (h : pos ≠ s.endPos), ⦃ inv pos b ⦄ f (pos.get h) (none, b) ⦃ fun r => match r with | ForInStep.yield (none, b') => inv (pos.next h) b' | ForInStep.done (none, b') => inv s.endPos b' | ForInStep.done (some x, b') => wp (kRet (some x, b') x) post eposts | ForInStep.yield (some val, snd) => ⊥; eposts ⦄) (exit : ∀ (b : β), ⦃ inv s.endPos b ⦄ k (none, b) ⦃ post; eposts ⦄) : ⦃ inv s.startPos init ⦄ do let t ← forIn s (none, init) f match t.fst with | some x => kRet t x | none => k t ⦃ post; eposts ⦄
Std.WP.Spec.forIn_string_earlyReturn.{u₂, v, uₚ, uₑ} {β : Type u₂} {m : Type u₂ → Type v} {Pred : Type uₚ} {EPosts : Type uₑ} [CompleteLattice Pred] [PartialOrder EPosts] [MonadicWP m Pred EPosts] [Monad m] [LawfulMonad m] [MonadicWP.IsLaxDistrib m] {s : String} {γ δ : Type u₂} {init : β} {f : Char → Option γ × β → m (ForInStep (Option γ × β))} {kRet : Option γ × β → γ → m δ} {k : Option γ × β → m δ} {post : δ → Pred} {eposts : EPosts} (inv : StringInvariant s β Pred) (step : ∀ (pos : s.Pos) (b : β) (h : pos ≠ s.endPos), ⦃ inv pos b ⦄ f (pos.get h) (none, b) ⦃ fun r => match r with | ForInStep.yield (none, b') => inv (pos.next h) b' | ForInStep.done (none, b') => inv s.endPos b' | ForInStep.done (some x, b') => wp (kRet (some x, b') x) post eposts | ForInStep.yield (some val, snd) => ⊥; eposts ⦄) (exit : ∀ (b : β), ⦃ inv s.endPos b ⦄ k (none, b) ⦃ post; eposts ⦄) : ⦃ inv s.startPos init ⦄ do let t ← forIn s (none, init) f match t.fst with | some x => kRet t x | none => k t ⦃ post; eposts ⦄
🔗theorem
Std.WP.Spec.forIn_stringSlice_earlyReturn.{u₂, v, uₚ, uₑ} {β : Type u₂} {m : Type u₂ → Type v} {Pred : Type uₚ} {EPosts : Type uₑ} [CompleteLattice Pred] [PartialOrder EPosts] [MonadicWP m Pred EPosts] [Monad m] [LawfulMonad m] [MonadicWP.IsLaxDistrib m] {s : String.Slice} {γ δ : Type u₂} {init : β} {f : Char → Option γ × β → m (ForInStep (Option γ × β))} {kRet : Option γ × β → γ → m δ} {k : Option γ × β → m δ} {post : δ → Pred} {eposts : EPosts} (inv : StringSliceInvariant s β Pred) (step : ∀ (pos : s.Pos) (b : β) (h : pos ≠ s.endPos), ⦃ inv pos b ⦄ f (pos.get h) (none, b) ⦃ fun r => match r with | ForInStep.yield (none, b') => inv (pos.next h) b' | ForInStep.done (none, b') => inv s.endPos b' | ForInStep.done (some x, b') => wp (kRet (some x, b') x) post eposts | ForInStep.yield (some val, snd) => ⊥; eposts ⦄) (exit : ∀ (b : β), ⦃ inv s.endPos b ⦄ k (none, b) ⦃ post; eposts ⦄) : ⦃ inv s.startPos init ⦄ do let t ← forIn s (none, init) f match t.fst with | some x => kRet t x | none => k t ⦃ post; eposts ⦄
Std.WP.Spec.forIn_stringSlice_earlyReturn.{u₂, v, uₚ, uₑ} {β : Type u₂} {m : Type u₂ → Type v} {Pred : Type uₚ} {EPosts : Type uₑ} [CompleteLattice Pred] [PartialOrder EPosts] [MonadicWP m Pred EPosts] [Monad m] [LawfulMonad m] [MonadicWP.IsLaxDistrib m] {s : String.Slice} {γ δ : Type u₂} {init : β} {f : Char → Option γ × β → m (ForInStep (Option γ × β))} {kRet : Option γ × β → γ → m δ} {k : Option γ × β → m δ} {post : δ → Pred} {eposts : EPosts} (inv : StringSliceInvariant s β Pred) (step : ∀ (pos : s.Pos) (b : β) (h : pos ≠ s.endPos), ⦃ inv pos b ⦄ f (pos.get h) (none, b) ⦃ fun r => match r with | ForInStep.yield (none, b') => inv (pos.next h) b' | ForInStep.done (none, b') => inv s.endPos b' | ForInStep.done (some x, b') => wp (kRet (some x, b') x) post eposts | ForInStep.yield (some val, snd) => ⊥; eposts ⦄) (exit : ∀ (b : β), ⦃ inv s.endPos b ⦄ k (none, b) ⦃ post; eposts ⦄) : ⦃ inv s.startPos init ⦄ do let t ← forIn s (none, init) f match t.fst with | some x => kRet t x | none => k t ⦃ post; eposts ⦄
🔗theorem
Std.WP.Spec.forIn_loop_earlyReturn.{v, uₚ, uₑ, u, u_1} {β : Type u} {m : Type u → Type v} {Pred : Type uₚ} {EPosts : Type uₑ} [Monad m] [MonadTail m] [CompleteLattice Pred] [CompleteLattice EPosts] [MonadicWP m Pred EPosts] [MonadicWP.IsLaxDistrib m] {γ δ : Type u} {l : Lean.Loop} {init : β} {f : Unit → Option γ × β → m (ForInStep (Option γ × β))} {kRet : Option γ × β → γ → m δ} {k : Option γ × β → m δ} {post : δ → Pred} [∀ (P : Pred), PreservesSup (meet P)] (measure : Variant (Option γ × β) Pred) (inv : WhileInvariant β Pred) (einv : EPosts) (step : ∀ (b : β) (mb : measure.γ), ⦃ measure.EvalsTo (none, b) mb ⊓ inv false b ⦄ f () (none, b) ⦃ fun r => match r with | ForInStep.yield (none, b') => measure.EvalsBelow (none, b') mb ⊓ inv false b' | ForInStep.done (none, b') => inv true b' | ForInStep.done (some x, b') => wp (kRet (some x, b') x) post einv | ForInStep.yield (some val, snd) => ⊥; einv ⦄) (exit : ∀ (b : β), ⦃ inv true b ⦄ k (none, b) ⦃ post; einv ⦄) : ⦃ inv false init ⦄ do let s ← forIn l (none, init) f match s.fst with | some x => kRet s x | none => k s ⦃ post; einv ⦄
Std.WP.Spec.forIn_loop_earlyReturn.{v, uₚ, uₑ, u, u_1} {β : Type u} {m : Type u → Type v} {Pred : Type uₚ} {EPosts : Type uₑ} [Monad m] [MonadTail m] [CompleteLattice Pred] [CompleteLattice EPosts] [MonadicWP m Pred EPosts] [MonadicWP.IsLaxDistrib m] {γ δ : Type u} {l : Lean.Loop} {init : β} {f : Unit → Option γ × β → m (ForInStep (Option γ × β))} {kRet : Option γ × β → γ → m δ} {k : Option γ × β → m δ} {post : δ → Pred} [∀ (P : Pred), PreservesSup (meet P)] (measure : Variant (Option γ × β) Pred) (inv : WhileInvariant β Pred) (einv : EPosts) (step : ∀ (b : β) (mb : measure.γ), ⦃ measure.EvalsTo (none, b) mb ⊓ inv false b ⦄ f () (none, b) ⦃ fun r => match r with | ForInStep.yield (none, b') => measure.EvalsBelow (none, b') mb ⊓ inv false b' | ForInStep.done (none, b') => inv true b' | ForInStep.done (some x, b') => wp (kRet (some x, b') x) post einv | ForInStep.yield (some val, snd) => ⊥; einv ⦄) (exit : ∀ (b : β), ⦃ inv true b ⦄ k (none, b) ⦃ post; einv ⦄) : ⦃ inv false init ⦄ do let s ← forIn l (none, init) f match s.fst with | some x => kRet s x | none => k s ⦃ post; einv ⦄

These lemmas transform invariants for loops without early return into invariants for loops with early return. Given an invariant for the loop's mutable variables, the lemmas construct a suitable invariant that includes the value that might be returned early. They require a specification of how the loop body preserves the invariant in step:

  • The yield case shows that continuing ordinarily to the next iteration preserves the invariant, after updating its view of the collection.

  • The done cases track uses of Lean.Parser.Term.doBreak : doElem`break` exits the surrounding `for` loop.break (with none) and Lean.Parser.Term.doReturn : doElem`return e` inside of a `do` block makes the surrounding block evaluate to `pure e`, skipping any further statements. Note that uses of the `do` keyword in other syntax like in `for _ in _ do` do not constitute a surrounding block in this sense; in supported editors, the corresponding `do` keyword of the surrounding block is highlighted when hovering over `return`. The term `e` can start on a later line if it starts in a column to the right of `return`. `return` not followed by such a term is equivalent to `return ()`.return (with some).

  • The yield case with some must be impossible, because a loop that has returned early does not continue with another iteration.

The exit premise must demonstrate that the final invariant suffices for the code after the loop to establish the postcondition. These lemmas are found automatically by vcgen. However, understanding their structure can make it much easier to understand why a loop has the verification conditions that it does.

Invariants for Loops with Early Return

This function contains a loop that terminates as soon as it sees a negative number, returning it:

def findNeg (xs : List Int) : Option Int := Id.run do for x in xs do if x < 0 then return some x return none

One potential specification for this loop is that if it returns some, then the returned value is a negative member of the list, while if it returns none, then there are no negative values in the list. After using vcgen, there are a number of unfinished goals:

theorem findNeg_goals (xs : List Int) : (∀ y, findNeg xs = some y → y ∈ xs ∧ y < 0) ∧ (findNeg xs = none → ∀ y ∈ xs, 0 ≤ y) := unsolved goals xs:List Int⊢ Invariant Int PUnit Prop xs:List Int⊢ ?inv1 [] (ForIn.toList xs) PUnit.unit xs pref✝:List Intcur✝:Intsuff✝:List Int_h✝:ForIn.toList xs = pref✝ ++ cur✝ :: suff✝b✝:PUnita✝:?inv1 pref✝ (cur✝ :: suff✝) b✝h✝:cur✝ < 0x✝¹:Intx✝:some cur✝ = some x✝¹⊢ x✝¹ ∈ xs xs pref✝:List Intcur✝:Intsuff✝:List Int_h✝:ForIn.toList xs = pref✝ ++ cur✝ :: suff✝b✝:PUnita✝:?inv1 pref✝ (cur✝ :: suff✝) b✝h✝:cur✝ < 0x✝¹:Intx✝:some cur✝ = some x✝¹⊢ x✝¹ < 0 xs pref✝:List Intcur✝:Intsuff✝:List Int_h✝:ForIn.toList xs = pref✝ ++ cur✝ :: suff✝b✝:PUnita✝:?inv1 pref✝ (cur✝ :: suff✝) b✝h✝:cur✝ < 0x✝²:some cur✝ = nonex✝¹:Intx✝:x✝¹ ∈ xs⊢ 0 ≤ x✝¹ xs pref✝:List Intcur✝:Intsuff✝:List Int_h✝:ForIn.toList xs = pref✝ ++ cur✝ :: suff✝b✝:PUnita✝:?inv1 pref✝ (cur✝ :: suff✝) b✝h✝:¬cur✝ < 0⊢ ?inv1 (pref✝ ++ [cur✝]) suff✝ PUnit.unit xs:List Intb✝:PUnita✝:?inv1 (ForIn.toList xs) [] b✝x✝¹:Intx✝:none = some x✝¹⊢ x✝¹ ∈ xs xs:List Intb✝:PUnita✝:?inv1 (ForIn.toList xs) [] b✝x✝¹:Intx✝:none = some x✝¹⊢ x✝¹ < 0 xs:List Intb✝:PUnita✝:?inv1 (ForIn.toList xs) [] b✝x✝¹:Intx✝:x✝¹ ∈ xs⊢ 0 ≤ x✝¹xs:List Int⊢ (∀ (y : Int), findNeg xs = some y → y ∈ xs ∧ y < 0) ∧ (findNeg xs = none → ∀ (y : Int), y ∈ xs → 0 ≤ y) xs:List Intr:Option Inth:findNeg xs = r⊢ (∀ (y : Int), r = some y → y ∈ xs ∧ y < 0) ∧ (r = none → ∀ (y : Int), y ∈ xs → 0 ≤ y) xs:List Intr:Option Inth:findNeg xs = r⊢ wp (do let __s ← forIn xs (none, ()) fun x __s => if x < 0 then pure (ForInStep.done (some (some x), ())) else pure (ForInStep.yield (none, ())) match __s.fst with | some r => pure r | none => pure none) (fun r => (∀ (y : Int), r = some y → y ∈ xs ∧ y < 0) ∧ (r = none → ∀ (y : Int), y ∈ xs → 0 ≤ y)) () xs:List Int⊢ wp (do let __s ← forIn xs (none, ()) fun x __s => if x < 0 then pure (ForInStep.done (some (some x), ())) else pure (ForInStep.yield (none, ())) match __s.fst with | some r => pure r | none => pure none) (fun r => (∀ (y : Int), r = some y → y ∈ xs ∧ y < 0) ∧ (r = none → ∀ (y : Int), y ∈ xs → 0 ≤ y)) () xs:List Int⊢ Invariant Int PUnit Propxs:List Int⊢ ?inv1 [] (ForIn.toList xs) PUnit.unitxs:List Intpref✝:List Intcur✝:Intsuff✝:List Int_h✝:ForIn.toList xs = pref✝ ++ cur✝ :: suff✝b✝:PUnita✝:?inv1 pref✝ (cur✝ :: suff✝) b✝h✝:cur✝ < 0x✝¹:Intx✝:some cur✝ = some x✝¹⊢ x✝¹ ∈ xsxs:List Intpref✝:List Intcur✝:Intsuff✝:List Int_h✝:ForIn.toList xs = pref✝ ++ cur✝ :: suff✝b✝:PUnita✝:?inv1 pref✝ (cur✝ :: suff✝) b✝h✝:cur✝ < 0x✝¹:Intx✝:some cur✝ = some x✝¹⊢ x✝¹ < 0xs:List Intpref✝:List Intcur✝:Intsuff✝:List Int_h✝:ForIn.toList xs = pref✝ ++ cur✝ :: suff✝b✝:PUnita✝:?inv1 pref✝ (cur✝ :: suff✝) b✝h✝:cur✝ < 0x✝²:some cur✝ = nonex✝¹:Intx✝:x✝¹ ∈ xs⊢ 0 ≤ x✝¹xs:List Intpref✝:List Intcur✝:Intsuff✝:List Int_h✝:ForIn.toList xs = pref✝ ++ cur✝ :: suff✝b✝:PUnita✝:?inv1 pref✝ (cur✝ :: suff✝) b✝h✝:¬cur✝ < 0⊢ ?inv1 (pref✝ ++ [cur✝]) suff✝ PUnit.unitxs:List Intb✝:PUnita✝:?inv1 (ForIn.toList xs) [] b✝x✝¹:Intx✝:none = some x✝¹⊢ x✝¹ ∈ xsxs:List Intb✝:PUnita✝:?inv1 (ForIn.toList xs) [] b✝x✝¹:Intx✝:none = some x✝¹⊢ x✝¹ < 0xs:List Intb✝:PUnita✝:?inv1 (ForIn.toList xs) [] b✝x✝¹:Intx✝:x✝¹ ∈ xs⊢ 0 ≤ x✝¹

The first unfinished goal is an invariant for the loop. Because vcgen used the specification lemma Spec.forIn_pure_earlyReturn, the invariant doesn't need to track early returns itself. This reasoning is captured in subsequent verification conditions. The value of the invariant provided in this case appears as the metavariable ?inv1 in subsequent goals.

xs:List Int⊢ Invariant Int PUnit Prop

The first verification condition is that the invariant holds at the start of the loop:

xs:List Int⊢ ?inv1 [] (ForIn.toList xs) PUnit.unit

The next three verification conditions come from the done and some case of the step premise of Spec.forIn_pure_earlyReturn. They describe the early return from the loop. Due to simplification, there is one verification condition for each conjunct in the some case of the theorem statement:

xs pref✝:List Intcur✝:Intsuff✝:List Int_h✝:ForIn.toList xs = pref✝ ++ cur✝ :: suff✝b✝:PUnita✝:?inv1 pref✝ (cur✝ :: suff✝) b✝h✝:cur✝ < 0x✝¹:Intx✝:some cur✝ = some x✝¹⊢ x✝¹ ∈ xs
xs pref✝:List Intcur✝:Intsuff✝:List Int_h✝:ForIn.toList xs = pref✝ ++ cur✝ :: suff✝b✝:PUnita✝:?inv1 pref✝ (cur✝ :: suff✝) b✝h✝:cur✝ < 0x✝¹:Intx✝:some cur✝ = some x✝¹⊢ x✝¹ < 0

The next goal is the none conjunct of the specification, which is on the early-return path. Because early return always returns some, there is an inconsistent assumption in the context, which renders this goal easy to prove:

xs pref✝:List Intcur✝:Intsuff✝:List Int_h✝:ForIn.toList xs = pref✝ ++ cur✝ :: suff✝b✝:PUnita✝:?inv1 pref✝ (cur✝ :: suff✝) b✝h✝:cur✝ < 0x✝²:some cur✝ = nonex✝¹:Intx✝:x✝¹ ∈ xs⊢ 0 ≤ x✝¹

The next goal comes from the yield and none case of step. It requires that the invariant be preserved by a loop iteration that does not return early. This goal provides some insight into what the invariant should be. Assuming that the prefix satisfies the invariant and that the current element is nonnegative, it should be possible to demonstrate that the extended prefix also satisfies the invariant:

xs pref✝:List Intcur✝:Intsuff✝:List Int_h✝:ForIn.toList xs = pref✝ ++ cur✝ :: suff✝b✝:PUnita✝:?inv1 pref✝ (cur✝ :: suff✝) b✝h✝:¬cur✝ < 0⊢ ?inv1 (pref✝ ++ [cur✝]) suff✝ PUnit.unit

The next two goals are trivial cases that arise from the loop running to completion. They come from the exit premise of Spec.forIn_pure_earlyReturn. When the loop terminates normally, findNeg returns none, so the cases for some have inconsistent assumptions:

xs:List Intb✝:PUnita✝:?inv1 (ForIn.toList xs) [] b✝x✝¹:Intx✝:none = some x✝¹⊢ x✝¹ ∈ xs
xs:List Intb✝:PUnita✝:?inv1 (ForIn.toList xs) [] b✝x✝¹:Intx✝:none = some x✝¹⊢ x✝¹ < 0

Finally, upon termination, the invariant should guarantee the function's postcondition when the entire list is taken as the prefix. This verification condition also comes from the exit premise of Spec.forIn_pure_earlyReturn. Examining the goal reveals that the invariant needs to imply that all elements of the list are nonnegative:

xs:List Intb✝:PUnita✝:?inv1 (ForIn.toList xs) [] b✝x✝¹:Intx✝:x✝¹ ∈ xs⊢ 0 ≤ x✝¹

Providing a suitable invariant allows finish to dispatch all the verification conditions. A good choice is that every element of the prefix is nonnegative:

theorem findNeg_spec (xs : List Int) : (∀ y, findNeg xs = some y → y ∈ xs ∧ y < 0) ∧ (findNeg xs = none → ∀ y ∈ xs, 0 ≤ y) := xs:List Int⊢ (∀ (y : Int), findNeg xs = some y → y ∈ xs ∧ y < 0) ∧ (findNeg xs = none → ∀ (y : Int), y ∈ xs → 0 ≤ y) xs:List Intr:Option Inth:findNeg xs = r⊢ (∀ (y : Int), r = some y → y ∈ xs ∧ y < 0) ∧ (r = none → ∀ (y : Int), y ∈ xs → 0 ≤ y) xs:List Intr:Option Inth:findNeg xs = r⊢ wp (do let __s ← forIn xs (none, ()) fun x __s => if x < 0 then pure (ForInStep.done (some (some x), ())) else pure (ForInStep.yield (none, ())) match __s.fst with | some r => pure r | none => pure none) (fun r => (∀ (y : Int), r = some y → y ∈ xs ∧ y < 0) ∧ (r = none → ∀ (y : Int), y ∈ xs → 0 ≤ y)) () xs:List Intr:Option Inth:findNeg xs = rx✝¹:Intx✝:x✝¹ ∈ []⊢ 0 ≤ x✝¹xs:List Intr:Option Inth:findNeg xs = rpref✝:List Intcur✝:Intsuff✝:List Int_h✝:ForIn.toList xs = pref✝ ++ cur✝ :: suff✝b✝:PUnita✝:∀ (y : Int), y ∈ pref✝ → 0 ≤ yh✝:cur✝ < 0x✝¹:Intx✝:some cur✝ = some x✝¹⊢ x✝¹ ∈ xsxs:List Intr:Option Inth:findNeg xs = rpref✝:List Intcur✝:Intsuff✝:List Int_h✝:ForIn.toList xs = pref✝ ++ cur✝ :: suff✝b✝:PUnita✝:∀ (y : Int), y ∈ pref✝ → 0 ≤ yh✝:cur✝ < 0x✝¹:Intx✝:some cur✝ = some x✝¹⊢ x✝¹ < 0xs:List Intr:Option Inth:findNeg xs = rpref✝:List Intcur✝:Intsuff✝:List Int_h✝:ForIn.toList xs = pref✝ ++ cur✝ :: suff✝b✝:PUnita✝:∀ (y : Int), y ∈ pref✝ → 0 ≤ yh✝:¬cur✝ < 0x✝¹:Intx✝:x✝¹ ∈ pref✝ ++ [cur✝]⊢ 0 ≤ x✝¹xs:List Intr:Option Inth:findNeg xs = rb✝:PUnita✝:∀ (y : Int), y ∈ ForIn.toList xs → 0 ≤ yx✝¹:Intx✝:x✝¹ ∈ xs⊢ 0 ≤ x✝¹ invariants · fun pref suff _ => ∀ y ∈ pref, 0 ≤ y with All goals completed! 🐙