MerlinVR / UdonSharp

An experimental compiler for compiling C# to Udon assembly
MIT License
678 stars 89 forks source link

Add user property declarations support #85

Closed mika-f closed 3 years ago

mika-f commented 3 years ago

The following property declarations will now be compiled by UdonSharp.

public string Property1 => "Some Value";
public string Property2 { get; }
public string Property3 { get; set; }

// This will cause synchronization to be performed on the auto-generated internal field.
[field: UdonSynced]
public string Property4 { get; private set; }

private string _backingField;
public string Property5
{
    get => _backingField;
    set
    {
        if (_backingField != value)
             NotifiyPropertyChanged(nameof(Property5));
        _backingField = value;
    }
}

In this pull request, the compiler internally converts to UdonAssembly as method declarations and method calls, just like in real C#. For example, public string SomeProperty { get; private set; } will be converted into UdonAssembly as shown below:

.export get_SomeProperty
get_SomeProperty:
    PUSH, __0_const_intnl_SystemUInt32
    PUSH, __0_bf_intnl_kBackingField_String
    PUSH, __0_intnl_returnValSymbol_String
    COPY
    PUSH, __0_intnl_returnTarget_UInt32
    COPY
    JUMP_INDIRECT, __0_intnl_returnTarget_UInt32

set_SomeProperty:
    PUSH, __0_const_intnl_SystemUInt32
    PUSH, __0_mp_value_String
    PUSH, __0_bf_intnl_kBackingField_String
    COPY
    PUSH, __0_intnl_returnTarget_UInt32
    COPY
    JUMP_INDIRECT, __0_intnl_returnTarget_UInt32

Also, property calls (like _instance.SomeProperty) are converted as follows:

PUSH, _instance
PUSH, __1_const_intnl__SystemString
EXTERN, "VRCUdonCommonInterfacesIUdonEventReceiver.__SendCustomEvent__SystemString__SystemVoid"
PUSH, _instance
PUSH, __2_const_intnl__SystemString
PUSH, __1_intnl_SystemObject
EXTERN, "VRCUdonCommonInterfacesIUdonEventReceiver.__GetProgramVariable__SystemString__SystemObject"

The concern is that it is currently a low priority and may reduce the maintainability of the compiler; also, many users can build UdonSharp code without this feature without any problems.

MerlinVR commented 3 years ago

This looks good, thank you! I fixed some edge cases that were mostly due to other systems not handling properties correctly.