NamespaceReference.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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 (ReferenceEquals(typeReference, 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 = _path + "." + property;
  67. return GetPath(newPath);
  68. }
  69. [RequiresUnreferencedCode("Dynamic loading")]
  70. public JsValue GetPath(string path)
  71. {
  72. if (_engine.TypeCache.TryGetValue(path, out var type))
  73. {
  74. if (type == null)
  75. {
  76. return new NamespaceReference(_engine, path);
  77. }
  78. return TypeReference.CreateTypeReference(_engine, type);
  79. }
  80. // in CoreCLR, for example, classes that used to be in
  81. // mscorlib were moved away, and only stubs remained, because
  82. // of that, we do the search on the lookup assemblies first,
  83. // and only then in mscorlib. Probelm usage: System.IO.File.CreateText
  84. // search in loaded assemblies
  85. var lookupAssemblies = new[] { Assembly.GetCallingAssembly(), Assembly.GetExecutingAssembly() };
  86. foreach (var assembly in lookupAssemblies)
  87. {
  88. type = assembly.GetType(path);
  89. if (type != null)
  90. {
  91. _engine.TypeCache.Add(path, type);
  92. return TypeReference.CreateTypeReference(_engine, type);
  93. }
  94. }
  95. // search in lookup assemblies
  96. var comparedPath = path.Replace('+', '.');
  97. foreach (var assembly in _engine.Options.Interop.AllowedAssemblies)
  98. {
  99. type = assembly.GetType(path);
  100. if (type != null)
  101. {
  102. _engine.TypeCache.Add(path, type);
  103. return TypeReference.CreateTypeReference(_engine, type);
  104. }
  105. var lastPeriodPos = path.LastIndexOf('.');
  106. var trimPath = path.Substring(0, lastPeriodPos);
  107. type = GetType(assembly, trimPath);
  108. if (type != null)
  109. {
  110. foreach (Type nType in GetAllNestedTypes(type))
  111. {
  112. if (nType.FullName != null && nType.FullName.Replace('+', '.').Equals(comparedPath, StringComparison.Ordinal))
  113. {
  114. _engine.TypeCache.Add(comparedPath, nType);
  115. return TypeReference.CreateTypeReference(_engine, nType);
  116. }
  117. }
  118. }
  119. }
  120. // search for type in mscorlib
  121. type = System.Type.GetType(path);
  122. if (type != null)
  123. {
  124. _engine.TypeCache.Add(path, type);
  125. return TypeReference.CreateTypeReference(_engine, type);
  126. }
  127. // the new path doesn't represent a known class, thus return a new namespace instance
  128. _engine.TypeCache.Add(path, null);
  129. return new NamespaceReference(_engine, path);
  130. }
  131. /// <summary> Gets a type. </summary>
  132. ///<remarks>Nested type separators are converted to '.' instead of '+' </remarks>
  133. /// <param name="assembly"> The assembly. </param>
  134. /// <param name="typeName"> Name of the type. </param>
  135. ///
  136. /// <returns> The type. </returns>
  137. [RequiresUnreferencedCode("Assembly type loading")]
  138. private static Type? GetType(Assembly assembly, string typeName)
  139. {
  140. var compared = typeName.Replace('+', '.');
  141. foreach (Type t in assembly.GetTypes())
  142. {
  143. if (string.Equals(t.FullName?.Replace('+', '.'), compared, StringComparison.Ordinal))
  144. {
  145. return t;
  146. }
  147. }
  148. return null;
  149. }
  150. private static Type[] GetAllNestedTypes(Type type)
  151. {
  152. var types = new List<Type>();
  153. AddNestedTypesRecursively(types, type);
  154. return types.ToArray();
  155. }
  156. private static void AddNestedTypesRecursively(
  157. List<Type> types,
  158. [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes)] Type type)
  159. {
  160. foreach (var nestedType in type.GetNestedTypes(BindingFlags.Public))
  161. {
  162. types.Add(nestedType);
  163. AddNestedTypesRecursively(types, nestedType);
  164. }
  165. }
  166. public override PropertyDescriptor GetOwnProperty(JsValue property)
  167. {
  168. return PropertyDescriptor.Undefined;
  169. }
  170. public override string ToString()
  171. {
  172. return "[CLR namespace: " + _path + "]";
  173. }
  174. }
  175. }