31 / GodotOnReady

A C# Source Generator that adds convenient onready-like features to your C# scripts in Godot Mono (3.x) without any reflection.
https://www.nuget.org/packages/GodotOnReady
MIT License
123 stars 13 forks source link

Converting Roslyn attributes to C# attributes #47

Open Atlinx opened 2 years ago

Atlinx commented 2 years ago

I haven't found a way to get references working yet, so I've just copied the attributes file over to the code generator csproj. Here's the extension method I use to convert Rosyln source code attributes to instances of regular C# attributes.

        public static T MapToType<T>(this AttributeData attributeData) where T : Attribute
        {
            T attribute;
            if (attributeData.AttributeConstructor != null && attributeData.ConstructorArguments.Length > 0)
            {
                attribute = (T)Activator.CreateInstance(typeof(T), attributeData.GetActualConstuctorParams().ToArray());
            }
            else
            {
                attribute = (T)Activator.CreateInstance(typeof(T));
            }
            foreach (var p in attributeData.NamedArguments)
            {
                var field = typeof(T).GetField(p.Key);
                if (field != null)
                    field.SetValue(attribute, p.Value.Value);
                else
                    typeof(T).GetProperty(p.Key).SetValue(attribute, p.Value.Value);
            }
            return attribute;
        }