Skip to content

Commit f694de3

Browse files
committed
feat: Cleanup Display of types and arguments
1 parent d348f60 commit f694de3

File tree

8 files changed

+59
-38
lines changed

8 files changed

+59
-38
lines changed

hugr-core/src/hugr/views/snapshots/hugr_core__hugr__views__tests__dot_func.snap

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ source: hugr-core/src/hugr/views/tests.rs
33
expression: h.dot_string()
44
---
55
digraph {
6-
0 [shape=plain label=<<table border="1"><tr><td align="text" border="0" colspan="1">(0) FuncDefn: "test"</td></tr><tr><td port="out0" align="text" colspan="1" cellpadding="1" >0: [Bool] -&gt; [[]][Bool]</td></tr></table>>]
6+
0 [shape=plain label=<<table border="1"><tr><td align="text" border="0" colspan="1">(0) FuncDefn: "test"</td></tr><tr><td port="out0" align="text" colspan="1" cellpadding="1" >0: [Bool] -&gt; [Bool]</td></tr></table>>]
77
1 [shape=plain label=<<table border="1"><tr><td align="text" border="0" colspan="1">(1) Input</td></tr><tr><td port="out0" align="text" colspan="1" cellpadding="1" >0: Bool</td></tr></table>>]
88
1:out0 -> 2:in0 [style=""]
99
2 [shape=plain label=<<table border="1"><tr><td port="in0" align="text" colspan="1" cellpadding="1" >0: Bool</td></tr><tr><td align="text" border="0" colspan="1">(2) Output</td></tr></table>>]

hugr-core/src/hugr/views/snapshots/hugr_core__hugr__views__tests__dot_module.snap

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ expression: h.dot_string()
44
---
55
digraph {
66
0 [shape=plain label=<<table border="1"><tr><td align="text" border="0" colspan="1">(0) Module</td></tr></table>>]
7-
1 [shape=plain label=<<table border="1"><tr><td align="text" border="0" colspan="1">(1) FuncDecl: "test"</td></tr><tr><td port="out0" align="text" colspan="1" cellpadding="1" >0: [Bool] -&gt; [[]][Bool]</td></tr></table>>]
7+
1 [shape=plain label=<<table border="1"><tr><td align="text" border="0" colspan="1">(1) FuncDecl: "test"</td></tr><tr><td port="out0" align="text" colspan="1" cellpadding="1" >0: [Bool] -&gt; [Bool]</td></tr></table>>]
88
hier0 [shape=plain label="0"]
99
hier0 -> hier1 [style = "dashed"]
1010
hier1 [shape=plain label="1"]

hugr-core/src/types.rs

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -265,24 +265,27 @@ impl<RV: MaybeRV> From<SumType> for TypeBase<RV> {
265265
#[derive(Clone, Debug, Eq, Hash, derive_more::Display)]
266266
/// Core types
267267
pub enum TypeEnum<RV: MaybeRV> {
268-
// TODO optimise with Box<CustomType> ?
268+
/// An extension type.
269+
//
270+
// TODO optimise with `Box<CustomType>`?
269271
// or some static version of this?
270-
#[allow(missing_docs)]
271272
Extension(CustomType),
272-
#[allow(missing_docs)]
273+
/// An alias of a type.
273274
#[display("Alias({})", _0.name())]
274275
Alias(AliasDecl),
275-
#[allow(missing_docs)]
276-
#[display("Function({_0})")]
276+
/// A function type.
277+
#[display("{_0}")]
277278
Function(Box<FuncValueType>),
278-
// Index into TypeParams, and cache of TypeBound (checked in validation)
279-
#[allow(missing_docs)]
280-
#[display("Variable({_0})")]
279+
/// A type variable, defined by an index into a list of type parameters.
280+
//
281+
// We cache the TypeBound here (checked in validation)
282+
#[display("var#{_0}")]
281283
Variable(usize, TypeBound),
282284
/// RowVariable. Of course, this requires that `RV` has instances, [NoRV] doesn't.
283285
#[display("RowVar({_0})")]
284286
RowVar(RV),
285-
#[allow(missing_docs)]
287+
/// Sum of types.
288+
#[display("{_0}")]
286289
Sum(SumType),
287290
}
288291

@@ -688,7 +691,7 @@ pub(crate) mod test {
688691
]);
689692
assert_eq!(
690693
&t.to_string(),
691-
"[usize, Function([[]][]), my_custom, Alias(my_alias)]"
694+
"[usize, [] -> [], my_custom, Alias(my_alias)]"
692695
);
693696
}
694697

hugr-core/src/types/custom.rs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -155,11 +155,13 @@ impl CustomType {
155155

156156
impl Display for CustomType {
157157
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
158-
if self.args.is_empty() {
159-
write!(f, "{}", self.id)
160-
} else {
161-
write!(f, "{}({:?})", self.id, self.args)
158+
write!(f, "{}", self.id)?;
159+
if !self.args.is_empty() {
160+
write!(f, "(")?;
161+
crate::utils::display_list(&self.args, f)?;
162+
write!(f, ")")?;
162163
}
164+
Ok(())
163165
}
164166
}
165167

hugr-core/src/types/poly_func.rs

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
//! Polymorphic Function Types
22
3+
use std::borrow::Cow;
4+
35
use itertools::Itertools;
46

57
use crate::extension::SignatureError;
@@ -131,14 +133,17 @@ impl<RV: MaybeRV> PolyFuncTypeBase<RV> {
131133
}
132134

133135
/// Helper function for the Display implementation
134-
fn display_params(&self) -> String {
136+
fn display_params(&self) -> Cow<'static, str> {
135137
if self.params.is_empty() {
136-
return String::new();
138+
return Cow::Borrowed("");
137139
}
138-
format!(
139-
"forall {}. ",
140-
self.params.iter().map(ToString::to_string).join(" ")
141-
)
140+
let params_list = self
141+
.params
142+
.iter()
143+
.enumerate()
144+
.map(|(i, param)| format!("(var#{i} : {param})"))
145+
.join(" ");
146+
Cow::Owned(format!("∀ {params_list}. ",))
142147
}
143148

144149
/// Returns a mutable reference to the body of the function type.

hugr-core/src/types/signature.rs

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
use itertools::Either;
44

55
use std::borrow::Cow;
6-
use std::fmt::{self, Display, Write};
6+
use std::fmt::{self, Display};
77

88
use super::type_param::TypeParam;
99
use super::type_row::TypeRowBase;
@@ -279,13 +279,11 @@ impl Signature {
279279

280280
impl<RV: MaybeRV> Display for FuncTypeBase<RV> {
281281
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
282-
if !self.input.is_empty() {
283-
self.input.fmt(f)?;
284-
f.write_str(" -> ")?;
282+
self.input.fmt(f)?;
283+
f.write_str(" -> ")?;
284+
if !self.runtime_reqs.is_empty() {
285+
self.runtime_reqs.fmt(f)?;
285286
}
286-
f.write_char('[')?;
287-
self.runtime_reqs.fmt(f)?;
288-
f.write_char(']')?;
289287
self.output.fmt(f)
290288
}
291289
}

hugr-core/src/types/type_param.rs

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
//!
55
//! [`TypeDef`]: crate::extension::TypeDef
66
7+
use itertools::Itertools;
78
#[cfg(test)]
89
use proptest_derive::Arbitrary;
910
use std::num::NonZeroU64;
@@ -19,7 +20,7 @@ use crate::extension::SignatureError;
1920
#[derive(
2021
Clone, Debug, PartialEq, Eq, Hash, derive_more::Display, serde::Deserialize, serde::Serialize,
2122
)]
22-
#[display("{}", "_0.map(|i|i.to_string()).unwrap_or(\"-\".to_string())")]
23+
#[display("{}", _0.map(|i|i.to_string()).unwrap_or("-".to_string()))]
2324
#[cfg_attr(test, derive(Arbitrary))]
2425
pub struct UpperBound(Option<NonZeroU64>);
2526
impl UpperBound {
@@ -56,11 +57,19 @@ impl UpperBound {
5657
#[serde(tag = "tp")]
5758
pub enum TypeParam {
5859
/// Argument is a [TypeArg::Type].
60+
#[display("Type{}", match b {
61+
TypeBound::Any => "".to_string(),
62+
_ => format!("[{b}]")
63+
})]
5964
Type {
6065
/// Bound for the type parameter.
6166
b: TypeBound,
6267
},
6368
/// Argument is a [TypeArg::BoundedNat] that is less than the upper bound.
69+
#[display("{}", match bound.value() {
70+
Some(v) => format!("BoundedNat[{v}]"),
71+
None => "Nat".to_string()
72+
})]
6473
BoundedNat {
6574
/// Upper bound for the Nat parameter.
6675
bound: UpperBound,
@@ -69,12 +78,13 @@ pub enum TypeParam {
6978
String,
7079
/// Argument is a [TypeArg::Sequence]. A list of indeterminate size containing
7180
/// parameters all of the (same) specified element type.
81+
#[display("List[{param}]")]
7282
List {
7383
/// The [TypeParam] describing each element of the list.
7484
param: Box<TypeParam>,
7585
},
7686
/// Argument is a [TypeArg::Sequence]. A tuple of parameters.
77-
#[display("Tuple({})", "params.iter().map(|t|t.to_string()).join(\", \")")]
87+
#[display("Tuple[{}]", params.iter().map(|t|t.to_string()).join(", "))]
7888
Tuple {
7989
/// The [TypeParam]s contained in the tuple.
8090
params: Vec<TypeParam>,
@@ -144,29 +154,31 @@ impl From<UpperBound> for TypeParam {
144154
#[serde(tag = "tya")]
145155
pub enum TypeArg {
146156
/// Where the (Type/Op)Def declares that an argument is a [TypeParam::Type]
157+
#[display("Type({ty})")]
147158
Type {
148-
#[allow(missing_docs)]
159+
/// The concrete type for the parameter.
149160
ty: Type,
150161
},
151162
/// Instance of [TypeParam::BoundedNat]. 64-bit unsigned integer.
163+
#[display("{n}")]
152164
BoundedNat {
153-
#[allow(missing_docs)]
165+
/// The integer value for the parameter.
154166
n: u64,
155167
},
156168
///Instance of [TypeParam::String]. UTF-8 encoded string argument.
157169
#[display("\"{arg}\"")]
158170
String {
159-
#[allow(missing_docs)]
171+
/// The string value for the parameter.
160172
arg: String,
161173
},
162174
/// Instance of [TypeParam::List] or [TypeParam::Tuple], defined by a
163175
/// sequence of elements.
164-
#[display("Sequence({})", {
176+
#[display("({})", {
165177
use itertools::Itertools as _;
166178
elems.iter().map(|t|t.to_string()).join(",")
167179
})]
168180
Sequence {
169-
#[allow(missing_docs)]
181+
/// List of element types
170182
elems: Vec<TypeArg>,
171183
},
172184
/// Instance of [TypeParam::Extensions], providing the extension ids.
@@ -181,6 +193,7 @@ pub enum TypeArg {
181193
/// Variable (used in type schemes or inside polymorphic functions),
182194
/// but not a [TypeArg::Type] (not even a row variable i.e. [TypeParam::List] of type)
183195
/// nor [TypeArg::Extensions] - see [TypeArg::new_var_use]
196+
#[display("{}", v)]
184197
Variable {
185198
#[allow(missing_docs)]
186199
#[serde(flatten)]
@@ -235,7 +248,7 @@ impl From<ExtensionSet> for TypeArg {
235248
#[derive(
236249
Clone, Debug, PartialEq, Eq, Hash, serde::Deserialize, serde::Serialize, derive_more::Display,
237250
)]
238-
#[display("TypeArgVariable({idx})")]
251+
#[display("var#{idx}")]
239252
pub struct TypeArgVariable {
240253
idx: usize,
241254
cached_decl: TypeParam,

hugr-passes/src/monomorphize.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -654,7 +654,7 @@ mod test {
654654
#[rstest]
655655
#[case::bounded_nat(vec![0.into()], "$foo$$n(0)")]
656656
#[case::type_unit(vec![Type::UNIT.into()], "$foo$$t(Unit)")]
657-
#[case::type_int(vec![INT_TYPES[2].to_owned().into()], "$foo$$t(int([BoundedNat { n: 2 }]))")]
657+
#[case::type_int(vec![INT_TYPES[2].to_owned().into()], "$foo$$t(int(2))")]
658658
#[case::string(vec!["arg".into()], "$foo$$s(arg)")]
659659
#[case::dollar_string(vec!["$arg".into()], "$foo$$s(\\$arg)")]
660660
#[case::sequence(vec![vec![0.into(), Type::UNIT.into()].into()], "$foo$$seq($n(0)$t(Unit))")]

0 commit comments

Comments
 (0)