use std::fmt;
use std::hash::{Hash, Hasher};
use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
use std::sync::{Arc, OnceLock};
use num_bigint::BigInt;
use crate::atom::{Atom, mix64};
use crate::ctx::{Ctx, ValueOrder};
use crate::error::{ErrorKind, Result, ValueError};
use crate::function_domain::{DomainInner, GeneralFcn};
use crate::int::Int;
#[derive(Clone)]
pub enum Value {
Bool(bool),
Int(i64),
BigInt(Arc<BigInt>),
Str(Atom),
Model(Atom),
Set(Set),
Fcn(Fcn),
}
const K_BOOL: u64 = 0x1f83_d9ab_fb41_bd6b;
const K_INT: u64 = 0x5be0_cd19_137e_2179;
pub(crate) const K_STR: u64 = 0x6a09_e667_f3bc_c908;
const K_MV: u64 = 0xbb67_ae85_84ca_a73b;
pub(crate) const K_SET: u64 = 0x3c6e_f372_fe94_f82b;
const K_FCN: u64 = 0xa54f_f53a_5f1d_36f1;
pub(crate) fn mix2(a: u64, b: u64) -> u64 {
mix64(a ^ b.rotate_left(29).wrapping_mul(0x9e37_79b9_7f4a_7c15))
}
pub(crate) fn int_hash(v: i64) -> u64 {
#[allow(clippy::cast_sign_loss, reason = "bit reinterpretation for hashing")]
mix64((v as u64) ^ K_INT)
}
impl Value {
pub const TRUE: Self = Self::Bool(true);
pub const FALSE: Self = Self::Bool(false);
#[must_use]
pub fn int(i: Int) -> Self {
match i {
Int::Small(v) => Self::Int(v),
Int::Big(b) => match Int::from_big((*b).clone()) {
Int::Small(v) => Self::Int(v),
Int::Big(_) => Self::BigInt(b),
},
}
}
#[must_use]
pub fn as_int(&self) -> Option<Int> {
match self {
Self::Int(v) => Some(Int::Small(*v)),
Self::BigInt(b) => Some(Int::from_big((**b).clone())),
_ => None,
}
}
#[must_use]
pub const fn as_bool(&self) -> Option<bool> {
match self {
Self::Bool(b) => Some(*b),
_ => None,
}
}
#[must_use]
pub const fn as_set(&self) -> Option<&Set> {
match self {
Self::Set(s) => Some(s),
_ => None,
}
}
#[must_use]
pub const fn as_fcn(&self) -> Option<&Fcn> {
match self {
Self::Fcn(f) => Some(f),
_ => None,
}
}
#[must_use]
pub fn hash64(&self) -> u64 {
match self {
Self::Bool(b) => mix64(K_BOOL ^ u64::from(*b)),
Self::Int(v) => int_hash(*v),
Self::BigInt(b) => match self.as_int().and_then(|i| i.to_i64()) {
Some(v) => int_hash(v),
None => b
.to_signed_bytes_le()
.iter()
.fold(K_INT, |h, d| mix2(h, u64::from(*d))),
},
Self::Str(a) => mix2(K_STR, a.text_hash()),
Self::Model(a) => mix2(K_MV, a.text_hash()),
Self::Set(s) => s.hash64(),
Self::Fcn(f) => f.0.hash,
}
}
#[must_use]
pub fn kind_name(&self) -> &'static str {
match self {
Self::Bool(_) => "boolean",
Self::Int(_) | Self::BigInt(_) => "integer",
Self::Str(_) => "string",
Self::Model(_) => "model value",
Self::Set(_) => "set",
Self::Fcn(_) => "function",
}
}
}
impl From<bool> for Value {
fn from(b: bool) -> Self {
Self::Bool(b)
}
}
impl From<i64> for Value {
fn from(v: i64) -> Self {
Self::Int(v)
}
}
impl From<Int> for Value {
fn from(v: Int) -> Self {
Self::int(v)
}
}
impl Hash for Value {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write_u64(self.hash64());
}
}
impl PartialEq for Value {
fn eq(&self, other: &Self) -> bool {
crate::order::semantic_eq(self, other)
}
}
impl Eq for Value {}
impl fmt::Debug for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match crate::print::to_debug_string(self) {
Some(s) => f.write_str(&s),
None => write!(f, "<{}>", self.kind_name()),
}
}
}
#[derive(Clone)]
pub struct Set(pub(crate) Arc<SetInner>);
pub(crate) struct SetInner {
pub(crate) order: ValueOrder,
pub(crate) hash: OnceLock<u64>,
pub(crate) elems: OnceLock<Arc<[Value]>>,
pub(crate) tlc_norm: AtomicBool,
pub(crate) fp: crate::fp64::FpCache,
pub(crate) repr: SetRepr,
}
pub trait DeferredSet: Send + Sync + fmt::Debug + std::any::Any {
fn kind(&self) -> DeferredKind;
fn elements(&self, ctx: Ctx) -> Result<Vec<Value>>;
fn member(&self, elem: &Value, ctx: Ctx) -> Option<Result<bool>>;
fn key(&self) -> Vec<Value> {
Vec::new()
}
fn as_any(&self) -> Option<&dyn std::any::Any> {
None
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum DeferredKind {
Filter,
Map,
Cup,
Cap,
Diff,
Union,
}
pub(crate) enum SetRepr {
Enum,
Raw(Box<[Value]>),
Interval(Int, Int),
Subset(Value),
FcnSet(Value, Value),
RcdSet(Box<[(Atom, Value)]>),
Product(Box<[Value]>),
Nat,
Int,
Strings,
Seq(Value),
Deferred(Arc<dyn DeferredSet>),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SetKind {
Enum,
Raw,
Interval,
Subset,
FcnSet,
RcdSet,
Product,
Nat,
Int,
Strings,
Seq,
Deferred,
}
impl Set {
pub(crate) fn new(order: ValueOrder, repr: SetRepr) -> Self {
Self(Arc::new(SetInner {
order,
hash: OnceLock::new(),
elems: OnceLock::new(),
tlc_norm: AtomicBool::new(false),
fp: crate::fp64::FpCache::new(),
repr,
}))
}
pub(crate) fn from_sorted(order: ValueOrder, elems: Vec<Value>) -> Self {
let set = Self::new(order, SetRepr::Enum);
let elems: Arc<[Value]> = elems.into();
let _ = set.0.hash.set(set_hash(
elems.iter().map(Value::hash64),
elems.len() as u128,
));
let _ = set.0.elems.set(elems);
set
}
#[must_use]
pub fn stored_elements(&self) -> Option<&[Value]> {
match &self.0.repr {
SetRepr::Enum => self.0.elems.get().map(AsRef::as_ref),
SetRepr::Raw(e) => Some(e),
_ => None,
}
}
#[must_use]
pub fn has_cached_elements(&self) -> bool {
self.0.elems.get().is_some()
}
#[must_use]
pub fn kind(&self) -> SetKind {
match &self.0.repr {
SetRepr::Enum => SetKind::Enum,
SetRepr::Raw(_) => SetKind::Raw,
SetRepr::Interval(..) => SetKind::Interval,
SetRepr::Subset(_) => SetKind::Subset,
SetRepr::FcnSet(..) => SetKind::FcnSet,
SetRepr::RcdSet(_) => SetKind::RcdSet,
SetRepr::Product(_) => SetKind::Product,
SetRepr::Nat => SetKind::Nat,
SetRepr::Int => SetKind::Int,
SetRepr::Strings => SetKind::Strings,
SetRepr::Seq(_) => SetKind::Seq,
SetRepr::Deferred(_) => SetKind::Deferred,
}
}
#[must_use]
pub fn order(&self) -> ValueOrder {
self.0.order
}
#[must_use]
pub fn is_infinite(&self) -> bool {
crate::enumerate::is_infinite(self)
}
pub fn elements(&self, ctx: Ctx) -> Result<Arc<[Value]>> {
if !matches!(
self.0.repr,
SetRepr::Enum | SetRepr::Raw(_) | SetRepr::Deferred(_)
) {
crate::enumerate::size(self, ctx)?;
}
let e = self.cached_elements(ctx)?;
self.mark_normalized();
Ok(e)
}
pub fn concrete_element_stream(&self, ctx: Ctx) -> Result<Option<crate::SetElementStream>> {
crate::stream::concrete_raw(self, ctx)
}
pub fn concrete_subset_stream(&self, ctx: Ctx) -> Result<Option<crate::ConcreteSubsetStream>> {
crate::stream::concrete_subset(self, ctx)
}
pub fn peek_elements(&self, ctx: Ctx) -> Result<Arc<[Value]>> {
self.quiet_elements(ctx)
}
pub(crate) fn quiet_elements(&self, ctx: Ctx) -> Result<Arc<[Value]>> {
if let Some(e) = self.0.elems.get() {
return Ok(e.clone());
}
let _quiet = quiet::Quiet::enter();
self.cached_elements(ctx)
}
fn cached_elements(&self, ctx: Ctx) -> Result<Arc<[Value]>> {
if let Some(e) = self.0.elems.get() {
return Ok(e.clone());
}
let before = quiet::suppressed();
let e: Arc<[Value]> = crate::enumerate::enumerate(self, ctx)?.into();
if quiet::suppressed() == before {
Ok(self.0.elems.get_or_init(|| e).clone())
} else {
Ok(e)
}
}
#[must_use]
pub fn is_tlc_normalized(&self) -> bool {
match self.0.repr {
SetRepr::Raw(_) => self.0.tlc_norm.load(AtomicOrdering::Acquire),
_ => true,
}
}
pub(crate) fn mark_normalized(&self) {
if matches!(self.0.repr, SetRepr::Raw(_)) && !self.is_tlc_normalized() {
if quiet::active() {
quiet::note_suppressed();
} else {
self.0.tlc_norm.store(true, AtomicOrdering::Release);
}
}
}
pub fn size(&self, ctx: Ctx) -> Result<u64> {
crate::enumerate::size(self, ctx)
}
#[must_use]
pub fn hash64(&self) -> u64 {
*self
.0
.hash
.get_or_init(|| crate::order::compute_set_hash(self))
}
pub(crate) fn repr(&self) -> &SetRepr {
&self.0.repr
}
#[must_use]
pub fn as_interval(&self) -> Option<(&Int, &Int)> {
match &self.0.repr {
SetRepr::Interval(a, b) => Some((a, b)),
_ => None,
}
}
#[must_use]
pub fn as_fcn_set(&self) -> Option<(&Value, &Value)> {
match &self.0.repr {
SetRepr::FcnSet(d, r) => Some((d, r)),
_ => None,
}
}
#[must_use]
pub fn as_rcd_set(&self) -> Option<&[(Atom, Value)]> {
match &self.0.repr {
SetRepr::RcdSet(f) => Some(f),
_ => None,
}
}
#[must_use]
pub fn as_product(&self) -> Option<&[Value]> {
match &self.0.repr {
SetRepr::Product(f) => Some(f),
_ => None,
}
}
#[must_use]
pub fn ptr_eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
#[must_use]
pub fn addr(&self) -> usize {
Arc::as_ptr(&self.0).addr()
}
#[must_use]
pub fn as_deferred(&self) -> Option<&Arc<dyn DeferredSet>> {
match &self.0.repr {
SetRepr::Deferred(d) => Some(d),
_ => None,
}
}
#[must_use]
pub fn components(&self) -> Vec<(Option<Atom>, Value)> {
match &self.0.repr {
SetRepr::Subset(b) | SetRepr::Seq(b) => vec![(None, b.clone())],
SetRepr::FcnSet(d, r) => vec![(None, d.clone()), (None, r.clone())],
SetRepr::Product(fs) => fs.iter().map(|f| (None, f.clone())).collect(),
SetRepr::RcdSet(fs) => fs
.iter()
.map(|(a, f)| (Some(a.clone()), f.clone()))
.collect(),
_ => Vec::new(),
}
}
#[must_use]
pub fn raw_elements(&self) -> Option<&[Value]> {
match &self.0.repr {
SetRepr::Raw(e) if !self.is_tlc_normalized() => Some(e),
_ => None,
}
}
}
pub(crate) mod quiet {
use std::cell::Cell;
thread_local! {
static DEPTH: Cell<u32> = const { Cell::new(0) };
static SUPPRESSED: Cell<u64> = const { Cell::new(0) };
}
pub(crate) struct Quiet(());
impl Quiet {
pub(crate) fn enter() -> Self {
DEPTH.with(|d| d.set(d.get().saturating_add(1)));
Self(())
}
}
impl Drop for Quiet {
fn drop(&mut self) {
DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
}
}
pub(crate) fn active() -> bool {
DEPTH.with(Cell::get) > 0
}
pub(crate) fn suppressed() -> u64 {
SUPPRESSED.with(Cell::get)
}
pub(crate) fn note_suppressed() {
SUPPRESSED.with(|s| s.set(s.get().wrapping_add(1)));
}
}
#[must_use]
pub fn quiet_operation_active() -> bool {
quiet::active()
}
pub(crate) const HASH_ELEMENT_LIMIT: u128 = 1 << 16;
pub(crate) fn set_hash(hashes: impl Iterator<Item = u64>, len: u128) -> u64 {
let sum = if len <= HASH_ELEMENT_LIMIT {
hashes.fold(0u64, |acc, h| acc.wrapping_add(mix64(h)))
} else {
0x9e37_79b9_7f4a_7c15
};
#[allow(clippy::cast_possible_truncation, reason = "hash mixing")]
mix2(K_SET ^ (len as u64), sum)
}
#[derive(Clone)]
pub struct Fcn(pub(crate) Arc<FcnInner>);
pub(crate) struct FcnInner {
pub(crate) hash: u64,
pub(crate) metadata: crate::receiver::FunctionMetadata,
pub(crate) fp: crate::fp64::FpCache,
pub(crate) repr: FcnRepr,
}
pub(crate) enum FcnRepr {
Tuple(Box<[Value]>),
Record(Box<[(Atom, Value)]>),
General(GeneralFcn),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DomainLookup {
Unknown,
Missing,
Found(usize),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FcnKind {
Tuple,
Record,
General,
}
fn fcn_hash<'a>(pairs: impl Iterator<Item = (u64, &'a Value)>, len: usize) -> u64 {
let sum = pairs.fold(0u64, |acc, (dh, v)| acc.wrapping_add(mix2(dh, v.hash64())));
mix2(K_FCN ^ (len as u64), sum)
}
impl Fcn {
pub(crate) fn tuple(elems: Vec<Value>) -> Self {
Self::tuple_as(elems, true)
}
pub(crate) fn tuple_fcn(elems: Vec<Value>) -> Self {
Self::tuple_as(elems, false)
}
fn tuple_as(elems: Vec<Value>, literal: bool) -> Self {
Self::tuple_metadata(
elems,
crate::receiver::FunctionMetadata::new(ValueOrder::default(), literal),
)
}
pub(crate) fn tuple_metadata(
elems: Vec<Value>,
metadata: crate::receiver::FunctionMetadata,
) -> Self {
let hash = fcn_hash(
elems
.iter()
.enumerate()
.map(|(i, v)| (int_hash(i64::try_from(i).unwrap_or(i64::MAX) + 1), v)),
elems.len(),
);
Self(Arc::new(FcnInner {
hash,
metadata,
fp: crate::fp64::FpCache::new(),
repr: FcnRepr::Tuple(elems.into_boxed_slice()),
}))
}
pub(crate) fn record(fields: Vec<(Atom, Value)>, order: ValueOrder, literal: bool) -> Self {
Self::record_metadata(
fields,
crate::receiver::FunctionMetadata::new(order, literal),
)
}
pub(crate) fn record_metadata(
fields: Vec<(Atom, Value)>,
metadata: crate::receiver::FunctionMetadata,
) -> Self {
let hash = fcn_hash(
fields.iter().map(|(a, v)| (mix2(K_STR, a.text_hash()), v)),
fields.len(),
);
Self(Arc::new(FcnInner {
hash,
metadata,
fp: crate::fp64::FpCache::new(),
repr: FcnRepr::Record(fields.into_boxed_slice()),
}))
}
pub(crate) fn general(pairs: Vec<(Value, Value)>, order: ValueOrder) -> Self {
let hash = fcn_hash(pairs.iter().map(|(d, v)| (d.hash64(), v)), pairs.len());
Self(Arc::new(FcnInner {
hash,
metadata: crate::receiver::FunctionMetadata::new(order, false),
fp: crate::fp64::FpCache::new(),
repr: FcnRepr::General(GeneralFcn::new(pairs, order)),
}))
}
#[must_use]
pub fn kind(&self) -> FcnKind {
match &self.0.repr {
FcnRepr::Tuple(_) => FcnKind::Tuple,
FcnRepr::Record(_) => FcnKind::Record,
FcnRepr::General(_) => FcnKind::General,
}
}
#[must_use]
pub fn is_record_literal(&self) -> bool {
self.0.metadata.literal() && matches!(self.0.repr, FcnRepr::Record(_))
}
#[must_use]
pub fn is_tuple_literal(&self) -> bool {
self.0.metadata.literal() && matches!(self.0.repr, FcnRepr::Tuple(_))
}
#[must_use]
pub fn order(&self) -> ValueOrder {
self.0.metadata.order()
}
#[must_use]
pub fn len(&self) -> usize {
match &self.0.repr {
FcnRepr::Tuple(e) => e.len(),
FcnRepr::Record(f) => f.len(),
FcnRepr::General(p) => p.len(),
}
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
#[must_use]
pub fn as_tuple(&self) -> Option<&[Value]> {
match &self.0.repr {
FcnRepr::Tuple(e) => Some(e),
_ => None,
}
}
#[must_use]
pub fn as_record(&self) -> Option<&[(Atom, Value)]> {
match &self.0.repr {
FcnRepr::Record(f) => Some(f),
_ => None,
}
}
#[must_use]
pub fn entry(&self, i: usize) -> Option<(Value, &Value)> {
match &self.0.repr {
FcnRepr::Tuple(e) => e
.get(i)
.map(|v| (Value::Int(i64::try_from(i).unwrap_or(i64::MAX) + 1), v)),
FcnRepr::Record(f) => f.get(i).map(|(a, v)| (Value::Str(a.clone()), v)),
FcnRepr::General(p) => p.get(i).map(|(d, v)| (d.clone(), v)),
}
}
#[must_use]
pub fn entry_cow(&self, i: usize) -> Option<(std::borrow::Cow<'_, Value>, &Value)> {
match &self.0.repr {
FcnRepr::General(p) => p.get(i).map(|(d, v)| (std::borrow::Cow::Borrowed(d), v)),
_ => self.entry(i).map(|(d, v)| (std::borrow::Cow::Owned(d), v)),
}
}
#[must_use]
pub fn checked_domain_index(&self, argument: &Value) -> DomainLookup {
match &self.0.repr {
FcnRepr::General(p) => p.domain.checked_index(argument),
_ => DomainLookup::Unknown,
}
}
#[must_use]
pub fn tlc_domain_indices(&self) -> Option<&[usize]> {
match &self.0.repr {
FcnRepr::General(p) => p.domain.tlc_order(),
_ => None,
}
}
pub fn iter(&self) -> impl Iterator<Item = (Value, &Value)> + '_ {
(0..self.len()).filter_map(move |i| self.entry(i))
}
pub fn values(&self) -> impl Iterator<Item = &Value> + '_ {
let (tuple, record, general) = match &self.0.repr {
FcnRepr::Tuple(e) => (Some(e.iter()), None, None),
FcnRepr::Record(f) => (None, Some(f.iter().map(|(_, v)| v)), None),
FcnRepr::General(p) => (None, None, Some(p.iter().map(|(_, v)| v))),
};
tuple
.into_iter()
.flatten()
.chain(record.into_iter().flatten())
.chain(general.into_iter().flatten())
}
#[must_use]
pub fn apply(&self, arg: &Value) -> Option<&Value> {
match (&self.0.repr, arg) {
(FcnRepr::Tuple(e), Value::Int(i)) => i
.checked_sub(1)
.and_then(|i| usize::try_from(i).ok())
.and_then(|i| e.get(i)),
(FcnRepr::Record(f), Value::Str(a)) => f.iter().find(|(n, _)| n == a).map(|(_, v)| v),
(FcnRepr::General(p), _) => match p.domain.checked_index(arg) {
DomainLookup::Found(index) => p.values.get(index),
DomainLookup::Missing => None,
DomainLookup::Unknown => p.iter().find(|(d, _)| *d == arg).map(|(_, v)| v),
},
_ => None,
}
}
pub fn with_value_at(
&self,
i: usize,
new: Value,
ctx: Ctx,
) -> std::result::Result<Self, Value> {
if i >= self.len() {
return Err(new);
}
match &self.0.repr {
FcnRepr::Tuple(values) => {
let mut values = values.to_vec();
values[i] = new;
Ok(Self::tuple_as(values, self.0.metadata.literal()))
}
FcnRepr::Record(fields) => {
if self.order() != ctx.order {
return Err(new);
}
let mut fields = fields.to_vec();
fields[i].1 = new;
Ok(Self::record(
fields,
self.order(),
self.0.metadata.literal(),
))
}
FcnRepr::General(general) => {
if self.order() != ctx.order || !general.domain.canonical() {
return Err(new);
}
let mut values = general.values.to_vec();
values[i] = new;
let hash = fcn_hash(
general
.domain
.keys
.iter()
.zip(&values)
.map(|(d, v)| (d.hash64(), v)),
values.len(),
);
Ok(Self(Arc::new(FcnInner {
hash,
metadata: crate::receiver::FunctionMetadata::new(
self.order(),
self.0.metadata.literal(),
),
fp: crate::fp64::FpCache::new(),
repr: FcnRepr::General(GeneralFcn {
domain: Arc::clone(&general.domain),
values: values.into_boxed_slice(),
}),
})))
}
}
}
pub(crate) fn exact_domain_equals(&self, set: &Set) -> Option<bool> {
match &self.0.repr {
FcnRepr::General(general) => general.domain.matches_set(set),
_ => None,
}
}
#[must_use]
pub fn ptr_eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
#[must_use]
pub fn addr(&self) -> usize {
Arc::as_ptr(&self.0).addr()
}
}
fn queue(out: &mut Vec<Value>, v: Value) {
if frees_compound(&v) {
out.push(v);
}
}
impl SetInner {
fn take_children(&mut self, out: &mut Vec<Value>) {
match std::mem::replace(&mut self.repr, SetRepr::Enum) {
SetRepr::Raw(e) | SetRepr::Product(e) => {
for v in e {
queue(out, v);
}
}
SetRepr::Subset(v) | SetRepr::Seq(v) => queue(out, v),
SetRepr::FcnSet(d, r) => {
queue(out, d);
queue(out, r);
}
SetRepr::RcdSet(fs) => {
for (_, v) in fs {
queue(out, v);
}
}
other => self.repr = other,
}
if let Some(mut e) = self.elems.take()
&& let Some(slice) = Arc::get_mut(&mut e)
{
for v in slice.iter_mut() {
queue(out, std::mem::replace(v, Value::FALSE));
}
}
}
}
impl FcnInner {
fn take_children(&mut self, out: &mut Vec<Value>) {
match std::mem::replace(&mut self.repr, FcnRepr::Tuple(Box::default())) {
FcnRepr::Tuple(e) => {
for v in e {
queue(out, v);
}
}
FcnRepr::Record(fs) => {
for (_, v) in fs {
queue(out, v);
}
}
FcnRepr::General(mut ps) => {
for v in std::mem::take(&mut ps.values) {
queue(out, v);
}
if let Some(domain) = Arc::get_mut(&mut ps.domain) {
domain.take_children(out);
}
}
}
}
}
fn drain(mut stack: Vec<Value>) {
while let Some(v) = stack.pop() {
match v {
Value::Set(mut s) => {
if let Some(inner) = Arc::get_mut(&mut s.0) {
inner.take_children(&mut stack);
}
}
Value::Fcn(mut f) => {
if let Some(inner) = Arc::get_mut(&mut f.0) {
inner.take_children(&mut stack);
}
}
_ => {}
}
}
}
fn frees_compound(v: &Value) -> bool {
match v {
Value::Set(s) => Arc::strong_count(&s.0) == 1,
Value::Fcn(f) => Arc::strong_count(&f.0) == 1,
_ => false,
}
}
impl SetInner {
fn frees_compound_child(&self) -> bool {
let in_repr = match &self.repr {
SetRepr::Raw(e) | SetRepr::Product(e) => e.iter().any(frees_compound),
SetRepr::Subset(v) | SetRepr::Seq(v) => frees_compound(v),
SetRepr::FcnSet(d, r) => frees_compound(d) || frees_compound(r),
SetRepr::RcdSet(fs) => fs.iter().any(|(_, v)| frees_compound(v)),
_ => false,
};
in_repr
|| self
.elems
.get()
.is_some_and(|e| Arc::strong_count(e) == 1 && e.iter().any(frees_compound))
}
}
impl FcnInner {
fn frees_compound_child(&self) -> bool {
match &self.repr {
FcnRepr::Tuple(e) => e.iter().any(frees_compound),
FcnRepr::Record(fs) => fs.iter().any(|(_, v)| frees_compound(v)),
FcnRepr::General(ps) => {
ps.values.iter().any(frees_compound)
|| (Arc::strong_count(&ps.domain) == 1
&& ps.domain.keys.iter().any(frees_compound))
}
}
}
}
const NATIVE_DROP_DEPTH: u32 = 32;
std::thread_local! {
static DROP_DEPTH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
}
struct NativeDrop;
impl NativeDrop {
fn enter() -> Option<Self> {
let depth = DROP_DEPTH.get();
(depth < NATIVE_DROP_DEPTH).then(|| {
DROP_DEPTH.set(depth + 1);
Self
})
}
}
impl Drop for NativeDrop {
fn drop(&mut self) {
DROP_DEPTH.set(DROP_DEPTH.get().saturating_sub(1));
}
}
impl Drop for SetInner {
fn drop(&mut self) {
if !self.frees_compound_child() {
return;
}
if let Some(_level) = NativeDrop::enter() {
drop(std::mem::replace(&mut self.repr, SetRepr::Enum));
drop(self.elems.take());
return;
}
let mut stack = Vec::new();
self.take_children(&mut stack);
drain(stack);
}
}
impl DomainInner {
fn take_children(&mut self, out: &mut Vec<Value>) {
for key in std::mem::take(&mut self.keys) {
queue(out, key);
}
}
}
impl Drop for DomainInner {
fn drop(&mut self) {
if !self.keys.iter().any(frees_compound) {
return;
}
if let Some(_level) = NativeDrop::enter() {
drop(std::mem::take(&mut self.keys));
return;
}
let mut stack = Vec::new();
self.take_children(&mut stack);
drain(stack);
}
}
impl Drop for FcnInner {
fn drop(&mut self) {
if !self.frees_compound_child() {
return;
}
if let Some(_level) = NativeDrop::enter() {
drop(std::mem::replace(
&mut self.repr,
FcnRepr::Tuple(Box::default()),
));
return;
}
let mut stack = Vec::new();
self.take_children(&mut stack);
drain(stack);
}
}
impl Value {
#[must_use]
pub fn string(names: &crate::Interner, text: &str) -> Self {
Self::Str(names.intern(text))
}
#[must_use]
pub fn model(names: &crate::Interner, name: &str) -> Self {
Self::Model(names.intern(name))
}
pub fn set(elems: Vec<Self>, ctx: Ctx) -> Result<Self> {
crate::order::normalize_set(elems, ctx).map(|s| Self::Set(Set::from_sorted(ctx.order, s)))
}
pub fn set_canonical(elems: Vec<Self>, ctx: Ctx) -> Result<Self> {
crate::construction::canonical_set(elems, ctx, &mut || true).map_err(|error| match error {
crate::ConstructionError::Value(error) => error,
other => ValueError::new(ErrorKind::DiveLimit, other.to_string()),
})
}
pub fn require_materialized(&self, ctx: Ctx) -> Result<()> {
crate::construction::require_closed(self, ctx, &mut || true).map_err(|error| match error {
crate::ConstructionError::Value(error) => error,
other => ValueError::new(ErrorKind::DiveLimit, other.to_string()),
})
}
pub fn materialized_for_equality(&self, ctx: Ctx) -> Result<Self> {
let _quiet = quiet::Quiet::enter();
self.materialized_identity(ctx)
}
pub fn materialized_identity(&self, ctx: Ctx) -> Result<Self> {
crate::construction::materialized_identity(self, ctx, &mut || true, 0).map_err(|error| {
match error {
crate::ConstructionError::Value(error) => error,
other => ValueError::new(ErrorKind::DiveLimit, other.to_string()),
}
})
}
pub fn set_controlled(
elems: Vec<Self>,
ctx: Ctx,
proceed: &mut dyn FnMut() -> bool,
) -> Result<Self, crate::ConstructionError> {
for value in &elems {
if !crate::construction::closed(value, ctx, proceed)? {
return Self::set(elems, ctx).map_err(Into::into);
}
}
crate::construction::set(elems, ctx, proceed)
}
#[must_use]
pub fn set_raw(elems: Vec<Self>, ctx: Ctx) -> Self {
if elems.is_empty() {
return Self::Set(Set::from_sorted(ctx.order, elems));
}
Self::Set(Set::new(ctx.order, SetRepr::Raw(elems.into_boxed_slice())))
}
#[must_use]
pub fn empty_set(ctx: Ctx) -> Self {
Self::Set(Set::from_sorted(ctx.order, Vec::new()))
}
#[must_use]
pub fn interval(lo: Int, hi: Int, ctx: Ctx) -> Self {
Self::Set(Set::new(ctx.order, SetRepr::Interval(lo, hi)))
}
#[must_use]
pub fn subset(base: Self, ctx: Ctx) -> Self {
Self::Set(Set::new(ctx.order, SetRepr::Subset(base)))
}
#[must_use]
pub fn fcn_set(domain: Self, range: Self, ctx: Ctx) -> Self {
Self::Set(Set::new(ctx.order, SetRepr::FcnSet(domain, range)))
}
pub fn record_set(fields: Vec<(Atom, Self)>, ctx: Ctx) -> Result<Self> {
let fields = sort_fields(fields, ctx.order)?;
Ok(Self::Set(Set::new(
ctx.order,
SetRepr::RcdSet(fields.into_boxed_slice()),
)))
}
#[must_use]
pub fn product(factors: Vec<Self>, ctx: Ctx) -> Self {
Self::Set(Set::new(
ctx.order,
SetRepr::Product(factors.into_boxed_slice()),
))
}
#[must_use]
pub fn nat(ctx: Ctx) -> Self {
Self::Set(Set::new(ctx.order, SetRepr::Nat))
}
#[must_use]
pub fn int_set(ctx: Ctx) -> Self {
Self::Set(Set::new(ctx.order, SetRepr::Int))
}
#[must_use]
pub fn string_set(ctx: Ctx) -> Self {
Self::Set(Set::new(ctx.order, SetRepr::Strings))
}
#[must_use]
pub fn seq_set(range: Self, ctx: Ctx) -> Self {
Self::Set(Set::new(ctx.order, SetRepr::Seq(range)))
}
#[must_use]
pub fn boolean_set(ctx: Ctx) -> Self {
Self::Set(Set::from_sorted(ctx.order, vec![Self::FALSE, Self::TRUE]))
}
#[must_use]
pub fn deferred(source: Arc<dyn DeferredSet>, ctx: Ctx) -> Self {
Self::Set(Set::new(ctx.order, SetRepr::Deferred(source)))
}
#[must_use]
pub fn tuple(elems: Vec<Self>) -> Self {
Self::Fcn(Fcn::tuple(elems))
}
#[must_use]
pub fn tuple_fcn(elems: Vec<Self>) -> Self {
Self::Fcn(Fcn::tuple_fcn(elems))
}
pub fn record(fields: Vec<(Atom, Self)>, ctx: Ctx) -> Result<Self> {
if fields.is_empty() {
return Ok(Self::tuple(Vec::new()));
}
Ok(Self::Fcn(Fcn::record(
sort_fields(fields, ctx.order)?,
ctx.order,
true,
)))
}
pub fn fcn(pairs: Vec<(Self, Self)>, ctx: Ctx) -> Result<Self> {
crate::order::make_fcn(pairs, ctx)
}
pub fn fcn_controlled(
pairs: Vec<(Self, Self)>,
ctx: Ctx,
proceed: &mut dyn FnMut() -> bool,
) -> Result<Self, crate::ConstructionError> {
for (key, value) in &pairs {
if !crate::construction::closed(key, ctx, proceed)?
|| !crate::construction::closed(value, ctx, proceed)?
{
return Self::fcn(pairs, ctx).map_err(Into::into);
}
}
crate::construction::fcn(pairs, ctx, proceed)
}
pub fn record_controlled(
fields: Vec<(Atom, Self)>,
ctx: Ctx,
proceed: &mut dyn FnMut() -> bool,
) -> Result<Self, crate::ConstructionError> {
crate::construction::record(fields, ctx, proceed)
}
}
pub(crate) fn sort_fields(
mut fields: Vec<(Atom, Value)>,
order: ValueOrder,
) -> Result<Vec<(Atom, Value)>> {
fields.sort_by(|a, b| a.0.cmp_with(&b.0, order));
for w in fields.windows(2) {
if w[0].0 == w[1].0 {
return Err(ValueError::new(
ErrorKind::Duplicate,
format!("Field name {} occurs multiple times in record.", w[1].0),
));
}
}
Ok(fields)
}