NamespaceReference.cs 7.6 KB

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