leanprover / lean4

Lean 4 programming language and theorem prover
https://lean-lang.org
Apache License 2.0
4.74k stars 427 forks source link

feat: BitVec.toInt_abs #6154

Open bollu opened 4 days ago

bollu commented 4 days ago

This PR implements BitVec.toInt_abs.

The absolute value of x : BitVec w is naively a case split on the sign of x. However, recall that when x = intMin w, -x = x. Thus, the full value of abs x is computed by the case split:

theorem toInt_abs {x : BitVec w} :
  x.abs.toInt =
    if x = intMin w then (intMin w).toInt
    else if x.msb then -x.toInt
    else x.toInt

We also provide a variant of toInt_abs that hides the case split for x being positive or negative by using natAbs.

theorem toInt_abs_eq_natAbs {x : BitVec w} : x.abs.toInt =
    if x = intMin w then (intMin w).toInt else x.toInt.natAbs

Supercedes https://github.com/leanprover/lean4/pull/5787

leanprover-community-bot commented 4 days ago

Mathlib CI status (docs):

tobiasgrosser commented 4 days ago

Can you drop the mention of 'stacked pr' in the commit message?

bollu commented 4 days ago

@tobiasgrosser done

bollu commented 4 days ago

awaiting-review

bollu commented 4 days ago

changelog-library

kim-em commented 4 days ago

It doesn't need to be in this PR, but I would like to also have

theorem natAbs_toInt (x : BitVec w) : x.toInt.natAbs = if x.msb then x.toNat - (2^(w-1) - 1) else x.toNat

(didn't check the RHS carefully, but something like that ought to be true).