NamespaceReference.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. using System.Diagnostics.CodeAnalysis;
  2. using System.Globalization;
  3. using System.Reflection;
  4. using Jint.Native;
  5. using Jint.Native.Object;
  6. using Jint.Runtime.Descriptors;
  7. #pragma warning disable IL3050
  8. namespace Jint.Runtime.Interop;
  9. /// <summary>
  10. /// Any instance on this class represents a reference to a CLR namespace.
  11. /// Accessing its properties will look for a class of the full name, or instantiate
  12. /// a new <see cref="NamespaceReference"/> as it assumes that the property is a deeper
  13. /// level of the current namespace
  14. /// </summary>
  15. [RequiresUnreferencedCode("Dynamic loading")]
  16. public class NamespaceReference : ObjectInstance, ICallable
  17. {
  18. private readonly string? _path;
  19. public NamespaceReference(Engine engine, string? path) : base(engine)
  20. {
  21. _path = path;
  22. }
  23. public override bool DefineOwnProperty(JsValue property, PropertyDescriptor desc)
  24. {
  25. return false;
  26. }
  27. public override bool Delete(JsValue property)
  28. {
  29. return false;
  30. }
  31. JsValue ICallable.Call(JsValue thisObject, params JsCallArguments arguments)
  32. {
  33. // direct calls on a NamespaceReference constructor object is creating a generic type
  34. var genericTypes = new Type[arguments.Length];
  35. for (int i = 0; i < arguments.Length; i++)
  36. {
  37. var genericTypeReference = arguments[i];
  38. if (genericTypeReference.IsUndefined()
  39. || !genericTypeReference.IsObject()
  40. || genericTypeReference.AsObject() is not TypeReference tr)
  41. {
  42. Throw.TypeError(_engine.Realm, "Invalid generic type parameter on " + _path + ", if this is not a generic type / method, are you missing a lookup assembly?");
  43. return default;
  44. }
  45. genericTypes[i] = tr.ReferenceType;
  46. }
  47. var typeReference = GetPath(_path + "`" + arguments.Length.ToString(CultureInfo.InvariantCulture)).As<TypeReference>();
  48. if (typeReference is null)
  49. {
  50. return Undefined;
  51. }
  52. try
  53. {
  54. var genericType = typeReference.ReferenceType.MakeGenericType(genericTypes);
  55. return TypeReference.CreateTypeReference(Engine, genericType);
  56. }
  57. catch (Exception e)
  58. {
  59. Throw.InvalidOperationException($"Invalid generic type parameter on {_path}, if this is not a generic type / method, are you missing a lookup assembly?", e);
  60. return null;
  61. }
  62. }
  63. public override JsValue Get(JsValue property, JsValue receiver)
  64. {
  65. var newPath = string.IsNullOrEmpty(_path)
  66. ? property.ToString()
  67. : $"{_path}.{property}";
  68. return GetPath(newPath);
  69. }
  70. [RequiresUnreferencedCode("Dynamic loading")]
  71. public JsValue GetPath(string path)
  72. {
  73. if (_engine.TypeCache.TryGetValue(path, out var type))
  74. {
  75. if (type == null)
  76. {
  77. return new NamespaceReference(_engine, path);
  78. }
  79. return TypeReference.CreateTypeReference(_engine, type);
  80. }
  81. // in CoreCLR, for example, classes that used to be in
  82. // mscorlib were moved away, and only stubs remained, because
  83. // of that, we do the search on the lookup assemblies first,
  84. // and only then in mscorlib. Probelm usage: System.IO.File.CreateText
  85. // search in loaded assemblies
  86. var lookupAssemblies = new[] { Assembly.GetCallingAssembly(), Assembly.GetExecutingAssembly() };
  87. foreach (var assembly in lookupAssemblies)
  88. {
  89. type = assembly.GetType(path);
  90. if (type != null)
  91. {
  92. _engine.TypeCache.Add(path, type);
  93. return TypeReference.CreateTypeReference(_engine, type);
  94. }
  95. }
  96. // search in lookup assemblies
  97. var comparedPath = path.Replace('+', '.');
  98. foreach (var assembly in _engine.Options.Interop.AllowedAssemblies)
  99. {
  100. type = assembly.GetType(path);
  101. if (type != null)
  102. {
  103. _engine.TypeCache.Add(path, type);
  104. return TypeReference.CreateTypeReference(_engine, type);
  105. }
  106. var lastPeriodPos = path.LastIndexOf('.');
  107. if (lastPeriodPos != -1)
  108. {
  109. var trimPath = path.Substring(0, lastPeriodPos);
  110. type = GetType(assembly, trimPath);
  111. }
  112. if (type != null)
  113. {
  114. foreach (Type nType in GetAllNestedTypes(type))
  115. {
  116. if (nType.FullName != null && nType.FullName.Replace('+', '.').Equals(comparedPath, StringComparison.Ordinal))
  117. {
  118. _engine.TypeCache.Add(comparedPath, nType);
  119. return TypeReference.CreateTypeReference(_engine, nType);
  120. }
  121. }
  122. }
  123. }
  124. // search for type in mscorlib
  125. type = System.Type.GetType(path);
  126. if (type != null)
  127. {
  128. _engine.TypeCache.Add(path, type);
  129. return TypeReference.CreateTypeReference(_engine, type);
  130. }
  131. // the new path doesn't represent a known class, thus return a new namespace instance
  132. _engine.TypeCache.Add(path, null);
  133. return new NamespaceReference(_engine, path);
  134. }
  135. /// <summary> Gets a type. </summary>
  136. ///<remarks>Nested type separators are converted to '.' instead of '+' </remarks>
  137. /// <param name="assembly"> The assembly. </param>
  138. /// <param name="typeName"> Name of the type. </param>
  139. ///
  140. /// <returns> The type. </returns>
  141. [RequiresUnreferencedCode("Assembly type loading")]
  142. private static Type? GetType(Assembly assembly, string typeName)
  143. {
  144. var compared = typeName.Replace('+', '.');
  145. foreach (Type t in assembly.GetTypes())
  146. {
  147. if (string.Equals(t.FullName?.Replace('+', '.'), compared, StringComparison.Ordinal))
  148. {
  149. return t;
  150. }
  151. }
  152. return null;
  153. }
  154. private static Type[] GetAllNestedTypes(Type type)
  155. {
  156. var types = new List<Type>();
  157. AddNestedTypesRecursively(types, type);
  158. return types.ToArray();
  159. }
  160. private static void AddNestedTypesRecursively(
  161. List<Type> types,
  162. [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes)] Type type)
  163. {
  164. foreach (var nestedType in type.GetNestedTypes(BindingFlags.Public))
  165. {
  166. types.Add(nestedType);
  167. AddNestedTypesRecursively(types, nestedType);
  168. }
  169. }
  170. public override PropertyDescriptor GetOwnProperty(JsValue property)
  171. {
  172. return PropertyDescriptor.Undefined;
  173. }
  174. public override string ToString()
  175. {
  176. return "[CLR namespace: " + _path + "]";
  177. }
  178. }