parrotcode: Untitled | |
Contents | Language Implementations | .Net |
This document discusses .NET's value types and how their semantics can be realised on the Parrot platform.
All value types derive directly from System.ValueType and be sealed. They can have instance and static fields and methods. They can exist in two forms - an unboxed form where they have value semantics and a boxed form where they become an object. When calling an instance method on the unboxed form, a managed pointer to it is passed. When calling an instance method on the boxed form, the reference is passed.
There is a special cases of value types, System.Enum, where there is only a single instance field that must be of an integral or number type. These can be treated as integers or numbers on the stack as appropriate. This allows the .NET platform to implement them efficiently (and will allow for the same to be achieved in the Parrot translation).
There needs to be a way to differentiate between the boxed and unboxed forms, even though in the Parrot translation they are essentially the same thing at a data structure level. Therefore, a PMC property is used to mark an object as "boxed". This is optimized for the common case - that the unboxed form will be being used.
Note that value types will also have to implement __clone. This is because when a value type "references" another value type, then it is really a flat data structure, but in Parrot's view it's a reference to another PMC that will also need to be cloned.
Boxing (through the box instruction) requires that the attributes are copied when the boxing takes place. This can be done with the clone Parrot instruction, and then the "boxed" property needs to be set. The box instruction will update the stack type state so reflect that the object on the stack is now an object.
Unboxing does not require any copying of the attributes, the operation simply needs to unset the boxed property and update the stack type state. However, the unbox instruction has an additional subtlety - it places onto the stack not the unboxed value itself, but rather a managed pointer to it. This is not really a problem, just some extra instructions to emit when translating the unbox operation.
|