blob: 45e63f0f3fda9e522f8d8f9137ddd59e2f9f589b [file]
/-
Copyright (c) 2024 Lean FRO, LLC. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joe Hendrix, Wojciech Nawrocki, Leonardo de Moura, Mario Carneiro, Alex Keizer, Harun Khan, Abdalrhman M Mohamed
-/
module
prelude
public import Init.Grind.Tactics
import Init.Data.Nat.Basic
public section
set_option linter.missingDocs true
/-!
This module exists to provide the very basic `BitVec` definitions required for
`Init.Data.UInt.BasicAux`.
-/
namespace BitVec
section Nat
instance instOfNat : OfNat (BitVec n) i where ofNat := .ofNat n i
/-- Return the bound in terms of toNat. -/
theorem isLt (x : BitVec w) : x.toNat < 2^w := x.toFin.isLt
/--
Converts a natural number to a bitvector of width `w`, returning the largest representable value
if the number is too large.
Returns `2^w - 1` for natural numbers greater than or equal to `2^w`.
-/
def ofNatClamp (w n : Nat) : BitVec w :=
if h : n < 2 ^ w then
BitVec.ofNatLT n h
else
BitVec.ofNatLT (2 ^ w - 1) (Nat.sub_lt (Nat.two_pow_pos w) Nat.one_pos)
end Nat
section arithmetic
/--
Adds two bitvectors. This can be interpreted as either signed or unsigned addition modulo `2^n`.
Usually accessed via the `+` operator.
SMT-LIB name: `bvadd`.
-/
@[expose, implicit_reducible]
protected def add (x y : BitVec n) : BitVec n := .ofNat n (x.toNat + y.toNat)
instance : Add (BitVec n) := ⟨BitVec.add⟩
/--
Subtracts one bitvector from another. This can be interpreted as either signed or unsigned subtraction
modulo `2^n`. Usually accessed via the `-` operator.
-/
@[expose, implicit_reducible]
protected def sub (x y : BitVec n) : BitVec n := .ofNat n ((2^n - y.toNat) + x.toNat)
instance : Sub (BitVec n) := ⟨BitVec.sub⟩
end arithmetic
end BitVec