-
Is it possible to attach a constraint on a struct type definition?
For example, an Sv32 VA has 2 VPNs of bits(10) type and 1 offset of bits(12) type, and PTEs (Page Table Entries) are 4 bytes (2^2). An Sv39 VA has 3 VPNs of bits(9) type and 1 offset of bits(12) type, and PTEs are 8 bytes (2^3). In general, I'd like to add the constraint that the only legal parameter combinations are
One can of course place these constraints on the signature of any function that uses this type, but that would replicate it in every such function. |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 4 replies
-
Technically yes, but I think it works the other way to how you are thinking. You can do:
but this would make it a type error to use If you have a complex constraint you can add a synonym like:
|
Beta Was this translation helpful? Give feedback.
-
I don't understand some of the comments:
But isn't this exactly what we want? I.e., a type error if 'levels < 0?
But doesn't this replicate the constraint? I can see your ‘synonym' solution alleviates this, but it's still replication? In particular, I see this constraint as a fundamental property of the |
Beta Was this translation helpful? Give feedback.
-
If the declaration of a type has a constraint, then this constraint must be true for the type to be well-formed wherever it appears. Because Tdef1 has a constraint, when
As I mentioned these constraints are not very useful, which is why I suggest just ignoring them in favour of constraints on functions. |
Beta Was this translation helpful? Give feedback.
-
More concretely for the Haskell example I mentioned earlier, the constraints on types in Sail work like {-# LANGUAGE DatatypeContexts, ExistentialQuantification #-}
data Eq a => Foo a = Foo (Maybe a)
{- Fails to type check!
bar :: Foo a -> Maybe a
bar (Foo x) = x
-}
data Baz a = Eq a => Baz (Maybe a)
quux :: Baz a -> Maybe a
quux (Baz x) = x |
Beta Was this translation helpful? Give feedback.
-
Ah, ok. This example helps a lot. I think it identifies exactly what was confusing me. Thanks! |
Beta Was this translation helpful? Give feedback.
Technically yes, but I think it works the other way to how you are thinking. You can do:
but this would make it a type error to use
VA_struct
anywhere'levels < 0
, rather than implicitly adding the constraint when the type appears. I would avoid adding constraints to types in general, and add them to functions using the types (as you would for typeclasses in Haskell for example).If you have a complex constraint you can add a synonym like: