using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Reflection;
namespace ComputeSharp.Shaders.Translation.Models
{
///
/// A that wraps a readable member of another and provides access to it
///
internal sealed class ReadableMember
{
///
/// The object wrapped by the current instance
///
private readonly MemberInfo Member;
///
/// Creates a new instance with the given parameters
///
/// The target object wrapped by the current instance
private ReadableMember(MemberInfo memberInfo)
{
// General properties
Member = memberInfo;
Name = memberInfo.Name;
DeclaringType = memberInfo.DeclaringType;
// Type specific properties
if (memberInfo is FieldInfo fieldInfo)
{
Member = fieldInfo;
IsStatic = fieldInfo.IsStatic;
MemberType = fieldInfo.FieldType;
}
else if (memberInfo is PropertyInfo propertyInfo)
{
Member = propertyInfo;
IsStatic = propertyInfo.GetMethod.IsStatic;
MemberType = propertyInfo.PropertyType;
}
else throw new InvalidOperationException("Field and property can't both be null at the same time");
}
///
/// Gets the name of the wrapped member for the current instance
///
public string Name { get; }
///
/// Gets whether or not the current member is not an instance member
///
public bool IsStatic { get; }
///
/// Gets the where the current member is declared in
///
public Type DeclaringType { get; }
///
/// Gets the of the wrapped member for the current instance
///
public Type MemberType { get; }
///
/// Gets or sets the list of parent members to access the current one from the root instance
///
public IReadOnlyList? Parents { get; set; }
///
/// Returns the value of the wrapped member for the current instance
///
/// The target instance to use to read the value from
[Pure]
public object GetValue(object? instance)
{
return Member switch
{
FieldInfo field => field.GetValue(instance),
PropertyInfo property => property.GetValue(instance),
_ => throw new InvalidOperationException("Field and property can't both be null at the same time")
};
}
///
/// Converts a object into a instance
///
/// The input object to wrap
public static implicit operator ReadableMember(FieldInfo field) => new ReadableMember(field);
///
/// Converts a object into a instance
///
/// The input object to wrap
public static implicit operator ReadableMember(PropertyInfo property) => new ReadableMember(property);
///
/// Converts a object into a instance
///
/// The input object to unwrap
public static implicit operator MemberInfo(ReadableMember member) => member.Member;
///
/// Converts a object into a instance
///
/// The input object to unwrap
public static implicit operator FieldInfo(ReadableMember member) => (FieldInfo)member.Member;
///
/// Converts a object into a instance
///
/// The input object to unwrap
public static implicit operator PropertyInfo(ReadableMember member) => (PropertyInfo)member.Member;
}
}