type system with attributes

Status
Not open for further replies.
I'm wondering why it isn't common for type systems to allow attributes representing properties of objects, and to allow variables to specify attributes in addition to regular types, and thus demand that certain properties hold for values assigned to them. This system would be a generalization of the @Nullable/@NotNull annotations that have become popular in Java, and an integration of them into the type system. It's such an obvious idea that I assume that the reason I haven't seen it in practice is that I'm ignorant and I'm hoping that someone can point out an example of it in the real world.

Note the type system of Haskell, where you'd specify something like:
Code:
square :: (Integral a, Integral b, Square b) => a -> b
sqrt :: (Integral a, Square a, Integral b) => a -> b
Except that you'd run into trouble when implementing square, as in order to construct an instance of b, we must create a new data type (or retrofit an existing type) implementing Integral and Square. Java can do this as well:
Code:
<N extends Integer & Square> int sqrt(N x);
But this doesn't really help because we need to create classes satisfying all possible combinations of attributes and functionality to convert between them.

For fun, I've thought up how I think such a type system would work and look. I'm imagining the notation E<@attr1, ..., @attrM>, where E is a regular type and each @attrI is an attribute, not a type parameter. Thus this feature doesn't work like templates in C++ or generics in Java - E knows nothing about the attributes or the number of attributes. We have the rule that E<@attr1, ..., @attrM> ≤ F<@attr'1, ..., @attr'N> iff E ≤ F and {@attr'1, ..., @attr'N} ⊆ {@attr1, ..., @attrM}. Or if we allow "sub-attributes", such as for numbers, @square extends @nonnegative, we would require that E ≤ F and there is a function f mapping {@attr'1, ..., @attr'N} to {@attr1, ..., @attrM} such that each f(@attr'I) ≤ @attr'I. So an int<@square> could be assigned to an int<@nonnegative>. Note that such a system breaks down for mutable objects, and thus there would need to be some language support for immutability or to guarantee that no mutation occurs.

For example:
Code:
int x = 3;
int<@square> xSquared = square(x);
int y = sqrt(xSquared); // y is an int because it's the square root of a square

int<@square> square(int x) {
	if (x >= 0x10000 || x <= -0x10000)
		throw new IllegalArgumentException(x + " is out of bounds");
	return @square(x * x); // add the @square attribute - see below
}

int sqrt(int<@square> x) {
	return (int)Math.sqrt(x);
}

@square(x * x) converts an int (more generally, an int<@attr1, ..., @attrM>) to an int<@square> (more generally, an int<@attr1, ..., @attrM, @square>). This notation suggests that a method is called, and in fact @square would be able validate its input to ensure that it is a valid square and that validation could be invoked at runtime:
Code:
typeAttribute @square extends @nonnegative {
	boolean validate(int x) {
		int sqrt = (int)Math.sqrt(x);
		return x == sqrt * sqrt;
	}
}
In general there could be one or more validate methods with parameters of different types and an attribute can only be attached to a type that it can validate. On construction, the runtime validates the value against the attribute and any attributes that it extends. In some cases, validation could be slow, so perhaps it could be turned off, as with assertions. Alternately, certain attributes could "fake" validation by always returning true (or just rejecting obviously wrong values) and rely on the developer to assign attributes correctly.

Note that unfortunately, validation occurs at runtime, not compile time, meaning that some errors survive compilation. Nonetheless, the type system allows developers to express their intentions about what properties of objects hold and allows the compiler to ensure correctness assuming that the intentions are correct, which would be a significant step forward from having no such system.

A final missing piece, which I admit could ruin the whole thing, would be a way of marking which attributes a function preserves. For example, the square function would preserve @even and @odd. Without being able to specify preservation of attributes, passing a value through a function would strip off all attributes not explicitly assigned in the function. I'm not sure how such a system would work.
 

Apteris

Ars Tribunus Angusticlavius
9,593
Subscriptor
Solomonoff's Secret":27ih6nlb said:
the @Nullable/@NotNull annotations that have become popular in Java
Oh good, I've been meaning to ask someone what these things do. Isn't @Nullable a synonym for, well, Object? And is @NotNull anything more than a fancy way of avoiding writing
Code:
if (o != null)
? I guess I'm just not sure where it makes sense to use these annotations.

-----

I find your general line of thought intriguing, but I would object to several points.

This notation suggests that a method is called, and in fact @square would be able validate its input to ensure that it is a valid square and that validation could be invoked at runtime [..]

On construction, the runtime validates the value against the attribute and any attributes that it extends.
So essentially, the @square and co. annotations would be so much syntactic sugar, right? You would simply write @square above the variable (or constant) instead of writing isSquare(int foo). This may or may not be useful, but I'd argue it's not a very good extension of the type system.

And when you say:

Alternately, certain attributes could "fake" validation by always returning true (or just rejecting obviously wrong values) and rely on the developer to assign attributes correctly.
Isn't this kind of going against the whole point of the type system?

To my mind--and I'm no expert so I'll welcome any and all corrections--a proper type system should allow compile-time, quick verification that a variable belongs to the type it says it does. We want something more than just a new way to run isSquare() or isPrime(), right? You alluded to this yourself when you wrote

unfortunately, validation occurs at runtime, not compile time [..]

A final missing piece, which I admit could ruin the whole thing, would be a way of marking which attributes a function preserves. For example, the square function would preserve @even and @odd. Without being able to specify preservation of attributes, passing a value through a function would strip off all attributes not explicitly assigned in the function. I'm not sure how such a system would work.
I wish I were an expert on the topic, but the best I can do is a few links I searched for. With that in mind.

In mathematical jargon the property you're looking for is closure. A set--such as the integers--is closed under an operation if applying that operation on members of the set always yields another member of the same set. Ideally, what you would want is a way for your type system to specify both sets and the operations under which those sets are closed, or in other words you want to define closures in your type system. (Not to be confused with function closures.)

This is tricky at both ends. All the "simple" sets like integers and reals are already handled by the JVM, as are their common operations. When you define your own set, you need to tell the compiler how to verify that your variables are actually of the type you claim they are. This can range from the trivial (@odd) through the expensive (@square) to the computationally infeasible (@prime).

What's more interesting is defining operations on your sets. Option 1 is you define operations you know are closed on your set and you're done. Both odd and even numbers are closed under multiplication. Evens are also closed under addition and subtraction, unlike odds. The positive reals are closed under square root (or any even root), but not under odd roots. And so on.

Option 2a, the manly computer scientist option, is defining your operation as well as the proof that your set is closed under that operation. Your compiler now needs more than a simple type checker, it has to include a proof verifier. This sounds involved, but apparently you can prove the commutativity of addition on natural numbers in 11 lines of code, so who knows.

Option 2b, the tenured researcher option, is defining your set and operation and having the compiler automatically determine whether your set is closed under that operation. In other words, your compiler now needs an automated theorem prover. Let's set this aside for now. (I believe there have recently been some articles on this in the CACM, but I can't remember them offhand.)

As far as I know the correspondence between mathematical proofs and computer programs was first considered by Haskell Curry, so it's only appropriate that I here link to the article on the Curry-Howard correspondence. I also link to Coq, the theorem prover used for the aforementioned proof of commutativity. If research into type systems is what you're looking for, these are two good starting points.

That's all I got. Hope it was at least a little helpful.
 
Apteris":2m2uhh8k said:
Oh good, I've been meaning to ask someone what these things do. Isn't @Nullable a synonym for, well, Object? And is @NotNull anything more than a fancy way of avoiding writing
Code:
if (o != null)
? I guess I'm just not sure where it makes sense to use these annotations.
Technically, @Nullable and @NotNull fall outside of the system I described but are similar in principle. They apply to references whereas the system I described applies to objects (although I suppose it could apply to references).

In summary, a reference marked @Nullable can be null whereas a reference marked @NotNull can't. At build time, a tool (such as the compiler) can ensure that any assignment to a reference marked @NotNull is from a reference marked @NotNull, is from any other reference after checking for non-nullity, or is the result of constructing an object right there (and thus can't be null). Furthermore, tools can tell you whether you ever access a non-@NotNull reference without checking it for null. Thus you can completely avoid all (non-explicitly thrown) NullPointerExceptions.

-----

I find your general line of thought intriguing, but I would object to several points.
…
So essentially, the @square and co. annotations would be so much syntactic sugar, right? You would simply write @square above the variable (or constant) instead of writing isSquare(int foo). This may or may not be useful, but I'd argue it's not a very good extension of the type system.
They aren't syntactic sugar. The type system would ensure that any variable requesting that its values be @squares actually are @squares (and if implemented properly, are mathematical squares). While you can call isSquare() everywhere, the type system wouldn't ensure that you've called that before assigning to a method accepting a square, and thus every method must validate its inputs or run the risk of taking a bad input.

And when you say:
…
To my mind--and I'm no expert so I'll welcome any and all corrections--a proper type system should allow compile-time, quick verification that a variable belongs to the type it says it does. We want something more than just a new way to run isSquare() or isPrime(), right? You alluded to this yourself when you wrote:
…
The system would do more than just call the verification methods: it would ensure that any time the code expects a value with a certain property, at the very least, the developer believes that that property holds; at the most, it ensures that the property does hold. Both levels of verification provide value: the former pushes the point at which objects are expected to have certain properties as close to their construction as possible, and thus allows the developer to more easily mentally ensure that the claimed properties hold (thus the type system isn't ensuring correctness but is doing tedious bookkeeping).

I wish I were an expert on the topic, but the best I can do is a few links I searched for. With that in mind.

In mathematical jargon the property you're looking for is closure. A set--such as the integers--is closed under an operation if applying that operation on members of the set always yields another member of the same set. Ideally, what you would want is a way for your type system to specify both sets and the operations under which those sets are closed, or in other words you want to define closures in your type system. (Not to be confused with function closures.)

This is tricky at both ends. All the "simple" sets like integers and reals are already handled by the JVM, as are their common operations. When you define your own set, you need to tell the compiler how to verify that your variables are actually of the type you claim they are. This can range from the trivial (@odd) through the expensive (@square) to the computationally infeasible (@prime).
The biggest problem is that an attribute (@square) applying to a certain type (int) may be decoupled from methods that operate on the type, and thus those methods don't even know what attributes exist.

What's more interesting is defining operations on your sets. Option 1 is you define operations you know are closed on your set and you're done. Both odd and even numbers are closed under multiplication. Evens are also closed under addition and subtraction, unlike odds. The positive reals are closed under square root (or any even root), but not under odd roots. And so on.
Correction: the positive reals contain exactly 1 copy of every integral root, even or odd. The reals contain exactly 2 copies of every even root of a positive real and exactly 1 copy of every odd root of a positive real. But I get your point. Still, the difficulty I mentioned above applies.

Option 2a, the manly computer scientist option, is defining your operation as well as the proof that your set is closed under that operation. Your compiler now needs more than a simple type checker, it has to include a proof verifier. This sounds involved, but apparently you can prove the commutativity of addition on natural numbers in 11 lines of code, so who knows.
I'm aware of Coq, as well as ATS. But proving correctness isn't really the point: I just want the compiler to do some simple verification for me.

Option 2b, the tenured researcher option, is defining your set and operation and having the compiler automatically determine whether your set is closed under that operation. In other words, your compiler now needs an automated theorem prover. Let's set this aside for now. (I believe there have recently been some articles on this in the CACM, but I can't remember them offhand.)
Sounds like Gödel would disapprove.

As far as I know the correspondence between mathematical proofs and computer programs was first considered by Haskell Curry, so it's only appropriate that I here link to the article on the Curry-Howard correspondence. I also link to Coq, the theorem prover used for the aforementioned proof of commutativity. If research into type systems is what you're looking for, these are two good starting points.
These are interesting topics but they aren't related to what I was getting at.

That's all I got. Hope it was at least a little helpful.
Thanks.
 

EtherealGoddess

Ars Tribunus Militum
2,782
Subscriptor++
Solomonoff's Secret":3w0oe2k4 said:
I'm aware of Coq, as well as ATS. But proving correctness isn't really the point: I just want the compiler to do some simple verification for me.
I'm not understanding how these systems don't address your specification of

... type systems to allow attributes representing properties of objects, and to allow variables to specify attributes in addition to regular types, and thus demand that certain properties hold for values assigned to them
This sounds exactly like dependent typing to me. Reading further, is it correct to say that you don't want to write a constructive proof that such a type has at least one member, but rather you'd prefer to provide an oracle that answers the decision problem of type membership?
 
EtherealGoddess":2gc07v5v said:
Solomonoff's Secret":2gc07v5v said:
I'm aware of Coq, as well as ATS. But proving correctness isn't really the point: I just want the compiler to do some simple verification for me.
I'm not understanding how these systems don't address your specification of

... type systems to allow attributes representing properties of objects, and to allow variables to specify attributes in addition to regular types, and thus demand that certain properties hold for values assigned to them
This sounds exactly like dependent typing to me.
It is but it's also much more than I want. I don't want to have to prove everything.

Reading further, is it correct to say that you don't want to write a constructive proof that such a type has at least one member, but rather you'd prefer to provide an oracle that answers the decision problem of type membership?
I don't want a constructive (or any sort of) proof. Furthermore, the oracle is just an implementation detail that I think provides at least some correctness benefits and is more convenient than a proof but that isn't fundamentally what I want. The key thing I want is to be able to specify supposed properties of objects, even if they aren't verified, and specify requirements of variables, and have the compiler check that values assigned to variables supposedly have the properties that the variables require.
 
Status
Not open for further replies.