using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace OpenTap
{
///
/// Representation of a C#/dotnet type including its inheritance hierarchy. Part of the object model used in the PluginManager
///
[DebuggerDisplay("{Name}")]
public class TypeData : ITypeData
{
// Used to mark when no display attribute is present.
static readonly DisplayAttribute noDisplayAttribute = new DisplayAttribute("<>");
// Used to mark when no helplink attribute is present.
static readonly HelpLinkAttribute noHelpLinkAttribute = new HelpLinkAttribute(null);
///
/// Gets the fully qualified name of the type, including its namespace but not its assembly.
///
public string Name { get;}
///
/// Gets the TypeAttributes for this type. This can be used to check if the type is abstract, nested, an interface, etc.
///
public TypeAttributes TypeAttributes { get; internal set; }
///
/// Gets the Assembly that defines this type.
///
public AssemblyData Assembly { get; internal set; }
///
/// Clone this typedata instance. Note that it is only partially cloned.
/// In particular, derived types and base types are not populated.
///
///
internal TypeData Clone()
{
return new TypeData(Name)
{
IsBrowsable = IsBrowsable,
display = display,
helpLink = helpLink,
canCreateInstance = canCreateInstance,
Assembly = Assembly,
TypeAttributes = TypeAttributes,
};
}
///
/// Gets.the DisplayAttribute for this type. Null if the type does not have a DisplayAttribute
///
public DisplayAttribute Display
{
get
{
if (display is null && attributes != null)
{
display = noDisplayAttribute;
foreach (var attr in attributes)
{
if (attr is DisplayAttribute displayAttr)
{
display = displayAttr;
break;
}
}
}
if (ReferenceEquals(display, noDisplayAttribute))
return null;
return display;
}
internal set => display = value;
}
///
/// Gets.the HelpLinkAttribute for this type. Null if the type does not have a HelpLinkAttribute
///
public HelpLinkAttribute HelpLink
{
get
{
if (helpLink is null && attributes != null)
{
helpLink = noHelpLinkAttribute;
foreach (var attr in attributes)
{
if (attr is HelpLinkAttribute helpLinkAttr)
{
helpLink = helpLinkAttr;
break;
}
}
}
if (ReferenceEquals(helpLink, noHelpLinkAttribute))
return null;
return helpLink;
}
internal set => helpLink = value;
}
/// Gets a list of base types (including interfaces)
internal ICollection BaseTypes => baseTypes;
///
/// Gets a list of plugin types (i.e. types that directly implement ITapPlugin) that this type inherits from/implements
///
public IEnumerable PluginTypes => pluginTypes;
///
/// Gets a list of types that has this type as a base type (including interfaces)
///
public IEnumerable DerivedTypes => derivedTypes ?? Array.Empty();
///
/// False if the type has a System.ComponentModel.BrowsableAttribute with Browsable = false.
///
public bool IsBrowsable { get; internal set; }
///
/// The attributes of this type.
/// Accessing this property causes the underlying Assembly to be loaded if it is not already.
///
public IEnumerable Attributes =>
attributes ?? (attributes = Load()?.GetAllCustomAttributes(false)) ?? Array.Empty();
///
/// Gets the System.Type that this represents. Same as calling .
/// Accessing this property causes the underlying Assembly to be loaded if it is not already.
///
public Type Type => Load();
/// gets if the type is a value-type. (see Type.IsValueType)
public bool IsValueType
{
get
{
PostLoad();
return isValueType;
}
}
/// Check if the assembly defining the type is loaded.
public bool IsAssemblyLoaded() => Assembly?.IsLoaded() ?? false;
internal TypeCode TypeCode => typeCode;
internal bool IsNumeric
{
get
{
PostLoad();
if (type.IsEnum)
return false;
switch (typeCode)
{
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Single:
return true;
default:
return false;
}
}
}
/// The base type of this type. Will return null if there is no base type. If there is no direct base, but instead an interface, that will be returned.
public ITypeData BaseType
{
get
{
if (baseTypeCache != null)
return ReferenceEquals(baseTypeCache, NullTypeData.Instance) ? null : baseTypeCache;
baseTypeCache = BaseTypes?.ElementAtOrDefault(0);
if (baseTypeCache != null) return baseTypeCache;
var result2 = Load()?.BaseType;
if (result2 != null)
{
baseTypeCache = FromType(result2);
return baseTypeCache;
}
baseTypeCache = NullTypeData.Instance;
return baseTypeCache;
}
}
/// If this is a collection type, then this is the element type. Otherwise null.
internal TypeData ElementType
{
get
{
PostLoad();
return elementType;
}
}
///
/// returns true if an instance possibly can be created.
/// Accessing this property causes the underlying Assembly to be loaded if it is not already.
///
public bool CanCreateInstance
{
get
{
if (failedLoad) return false;
if (canCreateInstance.HasValue) return canCreateInstance.Value;
if (Load() is Type t)
{
type = t;
canCreateInstance = type.IsValueType ||
type.IsAbstract == false && type.IsInterface == false &&
type.ContainsGenericParameters == false &&
type.GetConstructor(Array.Empty()) != null;
return canCreateInstance.Value;
}
return false; // failed to load
}
internal set => canCreateInstance = value;
}
internal string AssemblyQualifiedName
{
get
{
if (failedLoad) return "";
return assemblyQualifiedName ?? (assemblyQualifiedName = Load().AssemblyQualifiedName);
}
}
/// The loaded state of the type.
internal LoadStatus Status =>
type != null ? LoadStatus.Loaded : (failedLoad ? LoadStatus.FailedToLoad : LoadStatus.NotLoaded);
internal bool createInstanceSet => canCreateInstance.HasValue;
internal bool IsString
{
get
{
PostLoad();
return typeCode == TypeCode.String;
}
}
/// Invoked when new types has been discovered in an asynchronous fashion.
public static event EventHandler TypeCacheInvalidated;
static readonly TraceSource log = Log.CreateSource("PluginManager");
static ImmutableArray searchers = ImmutableArray.Empty;
static readonly ConcurrentDictionary derivedTypesCache =
new ConcurrentDictionary();
static readonly object lockSearchers = new object();
static int lastCount;
static readonly HashSet warningLogged = new HashSet();
static ConditionalWeakTable typeToTypeDataCache = new ConditionalWeakTable();
// add assembly is not thread safe.
static readonly object loadTypeDictLock = new object();
Type type;
bool? canCreateInstance;
ICollection baseTypes;
ICollection derivedTypes;
ICollection pluginTypes;
IMemberData[] members;
bool hasFlags;
DisplayAttribute display;
HelpLinkAttribute helpLink;
string assemblyQualifiedName;
bool failedLoad;
TypeData elementType;
ITypeData baseTypeCache;
// this value is used to mark a type code that has not been loaded
// all the normal values of TypeCode means something specifically
// so this value is used as something that does not have other meaning.
const int UnloadedTypeCode = 100;
TypeCode typeCode = (TypeCode)(UnloadedTypeCode);
object[] attributes = null;
bool postLoaded = false;
readonly object loadLock = new object();
bool isValueType;
internal void FinalizeCreation()
{
baseTypes = baseTypes?.ToArray();
pluginTypes = pluginTypes?.ToArray();
}
internal void AddBaseType(TypeData typename)
{
if (baseTypes == null)
baseTypes = new HashSet();
baseTypes.Add(typename);
}
internal void AddPluginType(TypeData typename)
{
if (typename == null)
return;
if (pluginTypes == null)
pluginTypes = new HashSet();
pluginTypes.Add(typename);
}
internal void AddPluginTypes(IEnumerable types)
{
if (types == null)
return;
if (pluginTypes == null)
pluginTypes = new HashSet();
foreach (var t in types)
pluginTypes.Add(t);
}
internal void AddDerivedType(TypeData typename)
{
if (derivedTypes == null)
derivedTypes = new HashSet();
else if (derivedTypes.Contains(typename))
return;
derivedTypes.Add(typename);
if (BaseTypes != null)
{
foreach (TypeData b in BaseTypes)
b.AddDerivedType(typename);
}
}
internal void RemoveDerivedType(TypeData typename)
{
if (derivedTypes != null && derivedTypes.Contains(typename))
derivedTypes.Remove(typename);
}
internal TypeData(string typeName)
{
Name = typeName;
IsBrowsable = true;
}
TypeData(Type type, PluginSearcher searcher): this(type.FullName)
{
this.type = type;
if(type.Assembly.IsDynamic == false)
this.Assembly = searcher.GetAssemblyData(type.Assembly);
else
{
this.Assembly = new AssemblyData(null, type.Assembly);
}
PostLoad();
IsBrowsable = this.GetAttribute()?.Browsable ?? true;
}
///
/// Returns the System.Type corresponding to this.
/// If the assembly in which this type is defined has not yet been loaded, this call will load it.
///
public Type Load()
{
if (failedLoad) return null;
if (type != null && UnloadedTypeCode != (int)typeCode)
{
return type;
}
// if UnloadedTypeCode == typeCode, it means it has not been fully loaded.
try
{
var asm = Assembly?.Load();
if (asm == null)
{
failedLoad = true;
return null;
}
type = asm.GetType(this.Name, true);
typeCode = Type.GetTypeCode(type);
typeToTypeDataCache.GetValue(type, t => this);
}
catch (Exception ex)
{
failedLoad = true;
var reason = ex.Message;
// Create a special-case error message when the load error is due to a dotnet runtime mismatch.
// FileName is a qualified assembly name, e.g. System.Runtime, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
const string versionPrefix = "System.Runtime, Version=";
if (ex is FileNotFoundException notFound && notFound.FileName.StartsWith(versionPrefix, StringComparison.OrdinalIgnoreCase))
{
// Build the reason string. I don't know if it's possible for the assembly to not be strong-named,
// but let's handle that just in case.
var filename = notFound.FileName;
var versionEnd = filename.IndexOf(',', versionPrefix.Length);
if (versionEnd == -1)
{
// no comma, so it ends with "Version=X.Y.Z.W"
versionEnd = filename.Length;
}
var versionString = filename.Substring(versionPrefix.Length, versionEnd - versionPrefix.Length);
reason =
$"This type depends on .NET {versionString}, but the current process is running {System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription}";
}
log.Error("Unable to load type '{0}' from '{1}'. Reason: '{2}'.", Name, Assembly.Location, reason);
log.Debug(ex);
}
return type;
}
///
/// Returns the DisplayAttribute.Name if the type has a DisplayAttribute, otherwise the FullName without namespace
///
///
public string GetBestName()
{
return Display != null ? Display.Name : Name.Split('.', '+').Last();
}
/// Creates a string value of this.
public override string ToString() => Name;
void PostLoad()
{
if (postLoaded) return;
lock (loadLock)
{
if (postLoaded) return;
Load();
if (type != typeof(string))
{
var elementType = type.GetEnumerableElementType();
if (elementType != null)
this.elementType = FromType(elementType);
}
typeCode = Type.GetTypeCode(type);
hasFlags = this.HasAttribute();
isValueType = type.IsValueType;
postLoaded = true;
}
}
///
/// Creates a new object instance of this type.
/// Accessing this property causes the underlying Assembly to be loaded if it is not already.
///
public object CreateInstance(object[] arguments)
{
if (!(Load() is Type t))
throw new InvalidOperationException(
$"Failed to instantiate object of type '{this.Name}'. The assembly failed to load.");
return Activator.CreateInstance(t, arguments);
}
///
/// Gets a member by name.
/// Causes the underlying Assembly to be loaded if it is not already.
///
public IMemberData GetMember(string name)
{
var members = (IMemberData[])GetMembers();
foreach (var member in members)
{
if (member.Name == name)
return member;
}
return null;
}
///
/// Gets all the members of this type.
/// Causes the underlying Assembly to be loaded if it is not already.
///
public IEnumerable GetMembers()
{
if (members != null) return members;
if (Load() is Type t)
{
var props = t.GetPropertiesTap();
List m = new List(props.Length);
foreach (var mem in props)
{
try
{
if (mem.GetMethod != null && mem.GetMethod.GetParameters().Length > 0)
continue;
if (mem.SetMethod != null && mem.SetMethod.GetParameters().Length != 1)
continue;
}
catch
{
continue;
}
m.Add(MemberData.Create(mem));
}
foreach (var mem in t.GetMethodsTap())
{
if (mem.GetAttribute()?.Browsable ?? false)
{
var member = MemberData.Create(mem);
m.Add(member);
}
}
members = m.ToArray();
}
else
{
// The members list cannot be populated because the type could not be loaded.
members = Array.Empty();
}
return members;
}
internal bool HasFlags()
{
PostLoad();
return hasFlags;
}
/// Compares two TypeDatas by comparing their inner Type instances.
/// Should be a TypeData
/// true if the two Type properties are equals.
public override bool Equals(object obj)
{
if (obj is TypeData td && td.type != null && type != null)
return td.type == type;
return ReferenceEquals(this, obj);
}
/// Calculates the hash code based on the .NET Type instance.
///
public override int GetHashCode()
{
var asm = Assembly?.GetHashCode() ?? 0;
return (asm + 586093897) * 759429795 +
(Name.GetHashCode() + 836431542) * 678129773;
}
/// Get the type info of an object.
public static ITypeData GetTypeData(object obj)
{
if (obj == null) return NullTypeData.Instance;
var cache = TypeDataCache.Current;
if (cache != null && cache.TryGetValue(obj, out var cachedValue))
return cachedValue;
var resolver = new TypeDataProviderStack();
var result = resolver.GetTypeData(obj);
if (result == null)
// this should never be possible since even GetTypeData(null) returns type of object.
throw new Exception($"GetTypeData returned null for an object if type {obj.GetType()}");
if (cache == null)
return result;
cache[obj] = result;
return result;
}
/// Get all known types that derive from a given type.
/// Base type that all returned types descends to.
/// All known types that descends to the given base type.
public static IEnumerable GetDerivedTypes(ITypeData baseType)
{
bool invalidated = false;
int count = 0;
foreach (var s in searchers)
{
var items = s.Types;
if (items is null)
invalidated = true;
else
count += items.Count();
}
if (lastCount == count && invalidated == false && derivedTypesCache.TryGetValue(baseType, out var result2))
return result2;
lock (lockSearchers)
{
if (lastCount != count || invalidated)
{
derivedTypesCache.Clear();
lastCount = count;
}
else if (derivedTypesCache.TryGetValue(baseType, out var result3))
{
return result3;
}
var searchTasks = new List();
foreach (var s in searchers)
{
if (s != null && s.Types == null)
{
searchTasks.Add(TapThread.StartAwaitable(s.Search));
}
}
var searcherTypes = FromType(typeof(ITypeDataSearcher)).DerivedTypes
.Where(x => x.CanCreateInstance)
.ToArray();
if (searchers.Length != searcherTypes.Length)
{
var existing = searchers.Select(GetTypeData).ToHashSet();
foreach (var searcherType in searcherTypes)
{
if (existing.Contains(searcherType)) continue;
bool error = false;
try
{
if (searcherType.CreateInstance(Array.Empty()) is ITypeDataSearcher searcher)
{
// make sure that ITypeDataSearchers with cache invalidation are activated.
if (searcher is ITypeDataSearcherCacheInvalidated cacheInvalidated)
cacheInvalidated.CacheInvalidated += CacheInvalidatedOnCacheInvalidated;
searchTasks.Add(TapThread.StartAwaitable(searcher.Search));
searchers = searchers.Add(searcher);
}
else error = true;
}
catch
{
error = true;
}
if (error)
WarnOnce($"Failed to instantiate {nameof(ITypeDataSearcher)} {searcherType}", searcherType);
}
}
try
{
Task.WaitAll(searchTasks.ToArray());
}
catch (Exception ex)
{
Log.CreateSource("TypeData").Debug(ex);
}
searchers = searchers.Sort(PluginOrderAttribute.Comparer);
var derivedTypes = new List();
foreach (var searcher in searchers)
{
if (searcher is DotNetTypeDataSearcher && baseType is TypeData td)
{
// This is a performance shortcut.
derivedTypes.AddRange(td.DerivedTypes);
continue;
}
if (searcher?.Types is IEnumerable types)
{
foreach (var type in types)
{
if (type.DescendsTo(baseType))
derivedTypes.Add(type);
}
}
}
var result = derivedTypes.ToArray();
derivedTypesCache[baseType] = result;
return result;
}
}
static readonly ConditionalWeakTable typeDataSourceLookup =
new ConditionalWeakTable();
///
/// Gets the type data source for an ITypeData. For most types this will return the AssemblyData, but for types for which
/// an ITypeDataSourceProvider exists it will return that instead. The base AssemblyData will often be associated to one
/// of the typedatas base classes.
///
///
///
public static ITypeDataSource GetTypeDataSource(ITypeData typeData)
{
if (typeDataSourceLookup.TryGetValue(typeData, out var src))
return src;
var typeData0 = typeData;
lock (lockSearchers)
{
// if 'lock' actually caused a lock and it was that same typeData, we want to use it instead
// of calculating it again.
if (typeDataSourceLookup.TryGetValue(typeData, out var src2))
return src2;
GetDerivedTypes(); // update cache.
while (typeData != null)
{
foreach (var searcher in searchers)
{
if (searcher is ITypeDataSourceProvider sp)
{
var source = sp.GetSource(typeData);
if (source != null)
return typeDataSourceLookup.GetValue(typeData0, td => source);
}
}
typeData = typeData.BaseType;
}
}
return typeDataSourceLookup.GetValue(typeData0, td => null);
}
static void OnSearcherCacheInvalidated(TypeDataCacheInvalidatedEventArgs args)
{
lastCount = 0;
TypeCacheInvalidated?.Invoke(null, args);
}
/// Get all known types that derive from a given type.
/// Base type that all returned types descends to.
/// All known types that descends to the given base type.
public static IEnumerable GetDerivedTypes()
{
return GetDerivedTypes(FromType(typeof(BaseType)));
}
static TypeData()
{
PluginManager.CacheState.Updated += (s, e) =>
{
foreach (var searcher in searchers.OfType())
searcher.CacheInvalidated -= CacheInvalidatedOnCacheInvalidated;
searchers = searchers.Clear();
MemberData.InvalidateCache();
derivedTypesCache.Clear();
typeToTypeDataCache = new ConditionalWeakTable();
};
}
static void WarnOnce(string message, ITypeData t)
{
if (warningLogged.Add(t))
log.Warning(message);
}
static void CacheInvalidatedOnCacheInvalidated(object sender, TypeDataCacheInvalidatedEventArgs e)
{
OnSearcherCacheInvalidated(e);
}
/// Creates a type data cache. Note this should be used with 'using{}' so that it gets removed afterwards.
/// A disposable object removing the cache.
[EditorBrowsable(EditorBrowsableState.Never)]
public static IDisposable WithTypeDataCache() => new TypeDataCache();
/// Gets the type info from a string.
public static ITypeData GetTypeData(string name) => new TypeDataProviderStack().GetTypeData(name);
///
/// This throws an exception due to the ambiguousness of TypeData.FromType vs TypeData.GetTypeData. To get TypeData representing a type use TypeData.FromType.
/// Otherwise cast 'type' to an 'object' first.
///
[Obsolete(
"This overload of GetTypeData should not be used: To get TypeData representing a type use TypeData.FromType. Otherwise cast 'type' to an 'object' first.",
true)]
[EditorBrowsable(EditorBrowsableState.Never)]
static public ITypeData GetTypeData(Type _)
{
throw new NotSupportedException(
@"Ambiguous call to GetTypeData: To get TypeData representing a type use TypeData.FromType."
+ "Otherwise cast 'type' to an 'object' first.");
}
/// Creates a new TypeData object to represent a dotnet type.
public static TypeData FromType(Type type)
{
if (typeToTypeDataCache.TryGetValue(type, out var i))
return i;
TypeData td = null;
lock (loadTypeDictLock)
{
var searcher = PluginManager.GetSearcher();
searcher?.AllTypes.TryGetValue(type.FullName, out td);
if (td == null && searcher != null)
{
// This can occur for some types inside mscorlib such as System.Net.IPAddress.
try
{
if (type.Assembly != null && type.Assembly.IsDynamic == false &&
type.Assembly.Location != null)
{
searcher.AddAssembly(type.Assembly.Location, type.Assembly);
if (searcher.AllTypes.TryGetValue(type.FullName, out td))
return td;
}
}
catch
{
}
td = new TypeData(type, searcher);
}
else
{
// This can occur when using shared projects because the same type is defined in multiple different assemblies with the same fully qualified
// name (namespace+typename). In this case, it is possible for the PluginSearcher to resolve an instance of this typedata from a different
// type than the input type to this method, which will cause all sorts of reflection errors. We detect this edge case here, and if there
// is a type mismatch, we instantiate a new typedata from the correct type.
if (td == null || td.Type != type)
{
td = new TypeData(type, searcher);
}
}
}
return typeToTypeDataCache.GetValue(type, x => td);
}
class TypeDataCache : IDisposable
{
static ThreadField> cache =
new ThreadField>();
public static IDictionary Current => cache.Value;
ICacheOptimizer[] caches;
public TypeDataCache()
{
var types = GetDerivedTypes().Where(x => x.CanCreateInstance)
.Select(x => x.AsTypeData().Type).ToArray();
caches = types.Select(t => t.CreateInstance()).OfType().ToArray();
foreach (var type in caches)
type.LoadCache();
cache.Value = new ConcurrentDictionary();
}
public void Dispose()
{
cache.Value = null;
foreach (var cache in caches)
cache.UnloadCache();
}
}
}
}