Open phase opened 7 years ago
@copy
class P
let x : Int
;
I think this could be a good idea. I've always liked the idea of annotations, but making the language annotation heavy might not make it super intuative.
I think classes should be value-based by default and should have to explicitly request reference schematics (forcing heap-allocation). If this is done, the compiler is free to stack-allocate and copy immutable objects, allowing boxing to be deferred indefinitely.
If we're moving large objects, copying would be quite slow.
Think about this:
LargeObject largeObj = new LargeObject();
largeObj.a = 7;
largeObj.b = true;
// etc.
LargeObjectContainer box = new LargeObjectContainer(largeObj);
If we have to copy largeObj
, then it'll be slower than just passing the reference.
Objects will be stack allocated once there's a pass implemented to detect that they can be.
You only need to do the optimization for small immutable objects, which are the most common.
With 0b6cf3749bf5ff765c0de0d9f2ef137a496fdb53, I introduced a very primitive ownership implementation into the Semantic Analysis pass. The biggest caveat of this is that it will error when moving primitive types, such as
int
s.In Rust, you can't use a struct once you've moved it.
This code will result in the following error:
This behavior has been implemented:
However, Rust handles primitives differently...
This code is perfectly allowed in Rust, since
a
is being copied tob
when it is moved.This will currently error with the following:
If we look at the above Rust error, we can see that our struct didn't implement the
Copy
trait. Integers in Rust implement this trait, and thus can be copied. It would be easy to create a special case for our defined primitive types, but having something like "traits" would be beneficial to users who want their classes to be copyable. Maybe an annotation?