Skip to content

Commit

Permalink
Remove KnownTypeConst, add ListValue::new_empty, address comments
Browse files Browse the repository at this point in the history
  • Loading branch information
doug-q committed Feb 2, 2024
1 parent 28fa94d commit 271acec
Show file tree
Hide file tree
Showing 8 changed files with 37 additions and 84 deletions.
4 changes: 2 additions & 2 deletions src/algorithm/const_fold.rs
Original file line number Diff line number Diff line change
Expand Up @@ -335,15 +335,15 @@ mod test {
#[cfg(not(feature = "extension_inference"))] // inference fails for test graph, shouldn't
#[test]
fn test_list_ops() -> Result<(), Box<dyn std::error::Error>> {
use crate::std_extensions::collections::{self, make_list_const, ListOp, ListValue};
use crate::std_extensions::collections::{self, ListOp, ListValue};

let reg = ExtensionRegistry::try_new([
PRELUDE.to_owned(),
logic::EXTENSION.to_owned(),
collections::EXTENSION.to_owned(),
])
.unwrap();
let list = make_list_const(ListValue::new(BOOL_T, vec![Value::unit_sum(1)]));
let list: Const = ListValue::new(BOOL_T, vec![Value::unit_sum(1)]).into();
let mut build = DFGBuilder::new(FunctionType::new(
type_row![],
vec![list.const_type().clone()],
Expand Down
20 changes: 2 additions & 18 deletions src/extension/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ use crate::{
type_row,
types::{
type_param::{TypeArg, TypeParam},
CustomCheckFailure, CustomType, FunctionType, PolyFuncType, Type, TypeBound,
CustomType, FunctionType, PolyFuncType, Type, TypeBound,
},
values::{CustomConst, KnownTypeConst},
values::CustomConst,
Extension,
};

Expand Down Expand Up @@ -183,10 +183,6 @@ impl CustomConst for ConstUsize {
format!("ConstUsize({:?})", self.0).into()
}

fn check_custom_type(&self, typ: &CustomType) -> Result<(), CustomCheckFailure> {
self.check_known_type(typ)
}

fn equal_consts(&self, other: &dyn CustomConst) -> bool {
crate::values::downcast_equal_consts(self, other)
}
Expand All @@ -200,10 +196,6 @@ impl CustomConst for ConstUsize {
}
}

impl KnownTypeConst for ConstUsize {
const TYPE: CustomType = USIZE_CUSTOM_T;
}

#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
/// Structure for holding constant usize values.
pub struct ConstError {
Expand All @@ -229,10 +221,6 @@ impl CustomConst for ConstError {
format!("ConstError({:?}, {:?})", self.signal, self.message).into()
}

fn check_custom_type(&self, typ: &CustomType) -> Result<(), CustomCheckFailure> {
self.check_known_type(typ)
}

fn equal_consts(&self, other: &dyn CustomConst) -> bool {
crate::values::downcast_equal_consts(self, other)
}
Expand All @@ -245,10 +233,6 @@ impl CustomConst for ConstError {
}
}

impl KnownTypeConst for ConstError {
const TYPE: CustomType = ERROR_CUSTOM_TYPE;
}

#[cfg(test)]
mod test {
use crate::{
Expand Down
3 changes: 1 addition & 2 deletions src/hugr/validate/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -542,9 +542,8 @@ fn no_polymorphic_consts() -> Result<(), Box<dyn std::error::Error>> {
),
)?;
let empty_list = Value::Extension {
c: (Box::new(collections::ListValue::new(
c: (Box::new(collections::ListValue::new_empty(
Type::new_var_use(0, TypeBound::Copyable),
vec![],
)),),
};
let cst = def.add_load_const(Const::new(empty_list, list_of_var)?)?;
Expand Down
7 changes: 4 additions & 3 deletions src/ops/constant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use crate::{
extension::ExtensionSet,
types::{ConstTypeError, EdgeKind, Type, TypeRow},
values::{CustomConst, KnownTypeConst, Value},
values::{CustomConst, Value},
};

use smol_str::SmolStr;
Expand Down Expand Up @@ -124,12 +124,13 @@ impl OpTrait for Const {
// without initial type check.
impl<T> From<T> for Const
where
T: KnownTypeConst + CustomConst,
T: CustomConst,
{
fn from(value: T) -> Self {
let typ = Type::new_extension(value.typ());
Const {
value: Value::custom(value),
typ: Type::new_extension(T::TYPE),
typ,
}
}
}
Expand Down
14 changes: 3 additions & 11 deletions src/std_extensions/arithmetic/float_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use smol_str::SmolStr;

use crate::{
extension::{ExtensionId, ExtensionSet},
types::{CustomCheckFailure, CustomType, Type, TypeBound},
values::{CustomConst, KnownTypeConst},
types::{CustomType, Type, TypeBound},
values::CustomConst,
Extension,
};
use lazy_static::lazy_static;
Expand Down Expand Up @@ -50,22 +50,14 @@ impl ConstF64 {
}
}

impl KnownTypeConst for ConstF64 {
const TYPE: CustomType = FLOAT64_CUSTOM_TYPE;
}

#[typetag::serde]
impl CustomConst for ConstF64 {
fn name(&self) -> SmolStr {
format!("f64({})", self.value).into()
}

fn check_custom_type(&self, typ: &CustomType) -> Result<(), CustomCheckFailure> {
self.check_known_type(typ)
}

fn typ(&self) -> CustomType {
Self::TYPE
FLOAT64_CUSTOM_TYPE
}

fn equal_consts(&self, other: &dyn CustomConst) -> bool {
Expand Down
4 changes: 2 additions & 2 deletions src/std_extensions/arithmetic/int_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ impl CustomConst for ConstIntU {
format!("u{}({})", self.log_width, self.value).into()
}
fn check_custom_type(&self, typ: &CustomType) -> Result<(), CustomCheckFailure> {
if typ.clone() == int_custom_type(type_arg(self.log_width)) {
if typ == &int_custom_type(type_arg(self.log_width)) {
Ok(())
} else {
Err(CustomCheckFailure::Message(
Expand Down Expand Up @@ -179,7 +179,7 @@ impl CustomConst for ConstIntS {
format!("i{}({})", self.log_width, self.value).into()
}
fn check_custom_type(&self, typ: &CustomType) -> Result<(), CustomCheckFailure> {
if typ.clone() == int_custom_type(type_arg(self.log_width)) {
if typ == &int_custom_type(type_arg(self.log_width)) {
Ok(())
} else {
Err(CustomCheckFailure::Message(
Expand Down
24 changes: 11 additions & 13 deletions src/std_extensions/collections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,15 @@ pub const EXTENSION_NAME: ExtensionId = ExtensionId::new_unchecked("Collections"
pub struct ListValue(Vec<Value>, Type);

impl ListValue {
/// Create a new [CustomConst] for a list of values.
/// (The caller will need these to all be of the same type, but that is not checked here.)
pub fn new(t: Type, contents: Vec<Value>) -> Self {
Self(contents, t)
/// Create a new [CustomConst] for a list of values of type `typ`.
/// That all values ore of type `typ` is not checked here.
pub fn new(typ: Type, contents: Vec<Value>) -> Self {
Self(contents, typ)
}

/// Create a new [CustomConst] for an empty list of values of type `typ`.
pub fn new_empty(typ: Type) -> Self {
Self(vec![], typ)
}
}

Expand Down Expand Up @@ -103,18 +108,12 @@ impl ConstFold for PopFold {
let list: &ListValue = list.get_custom_value().expect("Should be list value.");
let mut list = list.clone();
let elem = list.0.pop()?; // empty list fails to evaluate "pop"
let list = make_list_const(list);
let elem = ops::Const::new(elem, ty.clone()).unwrap();

Some(vec![(0.into(), list), (1.into(), elem)])
Some(vec![(0.into(), list.into()), (1.into(), elem)])
}
}

pub(crate) fn make_list_const(list: ListValue) -> ops::Const {
let t = list.typ();
ops::Const::new(list.into(), Type::new_extension(t)).unwrap()
}

struct PushFold;

impl ConstFold for PushFold {
Expand All @@ -127,9 +126,8 @@ impl ConstFold for PushFold {
let list: &ListValue = list.get_custom_value().expect("Should be list value.");
let mut list = list.clone();
list.0.push(elem.value().clone());
let list = make_list_const(list);

Some(vec![(0.into(), list)])
Some(vec![(0.into(), list.into())])
}
}
const TP: TypeParam = TypeParam::Type { b: TypeBound::Any };
Expand Down
45 changes: 12 additions & 33 deletions src/values.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,17 @@ pub trait CustomConst:
fn extension_reqs(&self) -> ExtensionSet;

/// Check the value is a valid instance of the provided type.
fn check_custom_type(&self, typ: &CustomType) -> Result<(), CustomCheckFailure>;
fn check_custom_type(&self, typ: &CustomType) -> Result<(), CustomCheckFailure> {
let expected = self.typ();
if typ == &expected {
Ok(())
} else {
Err(CustomCheckFailure::TypeMismatch {
expected,
found: typ.clone(),
})
}
}

/// Compare two constants for equality, using downcasting and comparing the definitions.
// Can't derive PartialEq for trait objects
Expand All @@ -179,25 +189,6 @@ pub fn downcast_equal_consts<T: CustomConst + PartialEq>(
}
}

/// Simpler trait for constant structs that have a known custom type to check against.
pub trait KnownTypeConst {
/// The type of the constants.
const TYPE: CustomType;

/// Fixed implementation of [CustomConst::check_custom_type] that checks
/// against known correct type.
fn check_known_type(&self, typ: &CustomType) -> Result<(), CustomCheckFailure> {
if typ == &Self::TYPE {
Ok(())
} else {
Err(CustomCheckFailure::TypeMismatch {
expected: Self::TYPE,
found: typ.clone(),
})
}
}
}

impl_downcast!(CustomConst);
impl_box_clone!(CustomConst, CustomConstBoxClone);

Expand Down Expand Up @@ -226,17 +217,6 @@ impl CustomConst for CustomSerialized {
format!("yaml:{:?}", self.value).into()
}

fn check_custom_type(&self, typ: &CustomType) -> Result<(), CustomCheckFailure> {
if &self.typ == typ {
Ok(())
} else {
Err(CustomCheckFailure::TypeMismatch {
expected: typ.clone(),
found: self.typ.clone(),
})
}
}

fn equal_consts(&self, other: &dyn CustomConst) -> bool {
Some(self) == other.downcast_ref()
}
Expand Down Expand Up @@ -267,8 +247,7 @@ pub(crate) mod test {

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]

/// A custom constant value used in testing that purports to be an instance
/// of a custom type with a specific type bound.
/// A custom constant value used in testing
pub(crate) struct CustomTestValue(pub CustomType);
#[typetag::serde]
impl CustomConst for CustomTestValue {
Expand Down

0 comments on commit 271acec

Please sign in to comment.