2
0

Options.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Dynamic;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Reflection;
  7. using Jint.Native;
  8. using Jint.Native.Object;
  9. using Jint.Runtime;
  10. using Jint.Runtime.Interop;
  11. using Jint.Runtime.Debugger;
  12. using Jint.Runtime.Descriptors;
  13. using Jint.Runtime.Interop.Reflection;
  14. using Jint.Runtime.References;
  15. namespace Jint
  16. {
  17. public delegate JsValue MemberAccessorDelegate(Engine engine, object target, string member);
  18. public sealed class Options
  19. {
  20. private readonly List<IConstraint> _constraints = new();
  21. private bool _strict;
  22. private DebuggerStatementHandling _debuggerStatementHandling;
  23. private bool _allowClr;
  24. private bool _allowClrWrite = true;
  25. private bool _allowOperatorOverloading;
  26. private readonly List<IObjectConverter> _objectConverters = new();
  27. private Func<Engine, object, ObjectInstance> _wrapObjectHandler;
  28. private MemberAccessorDelegate _memberAccessor;
  29. private int _maxRecursionDepth = -1;
  30. private TimeSpan _regexTimeoutInterval = TimeSpan.FromSeconds(10);
  31. private CultureInfo _culture = CultureInfo.CurrentCulture;
  32. private TimeZoneInfo _localTimeZone = TimeZoneInfo.Local;
  33. private List<Assembly> _lookupAssemblies = new();
  34. private Predicate<Exception> _clrExceptionsHandler;
  35. private IReferenceResolver _referenceResolver = DefaultReferenceResolver.Instance;
  36. private readonly List<Action<Engine>> _configurations = new();
  37. private readonly List<Type> _extensionMethodClassTypes = new();
  38. internal ExtensionMethodCache _extensionMethods = ExtensionMethodCache.Empty;
  39. /// <summary>
  40. /// Run the script in strict mode.
  41. /// </summary>
  42. public Options Strict(bool strict = true)
  43. {
  44. _strict = strict;
  45. return this;
  46. }
  47. /// <summary>
  48. /// Selects the handling for script <code>debugger</code> statements.
  49. /// </summary>
  50. /// <remarks>
  51. /// The <c>debugger</c> statement can either be ignored (default) trigger debugging at CLR level (e.g. Visual Studio),
  52. /// or trigger a break in Jint's DebugHandler.
  53. /// </remarks>
  54. public Options DebuggerStatementHandling(DebuggerStatementHandling debuggerStatementHandling)
  55. {
  56. _debuggerStatementHandling = debuggerStatementHandling;
  57. return this;
  58. }
  59. /// <summary>
  60. /// Allow to run the script in debug mode.
  61. /// </summary>
  62. public Options DebugMode(bool debugMode = true)
  63. {
  64. IsDebugMode = debugMode;
  65. return this;
  66. }
  67. /// <summary>
  68. /// Adds a <see cref="IObjectConverter"/> instance to convert CLR types to <see cref="JsValue"/>
  69. /// </summary>
  70. public Options AddObjectConverter<T>() where T : IObjectConverter, new()
  71. {
  72. return AddObjectConverter(new T());
  73. }
  74. /// <summary>
  75. /// Adds a <see cref="IObjectConverter"/> instance to convert CLR types to <see cref="JsValue"/>
  76. /// </summary>
  77. public Options AddObjectConverter(IObjectConverter objectConverter)
  78. {
  79. _objectConverters.Add(objectConverter);
  80. return this;
  81. }
  82. public Options AddExtensionMethods(params Type[] types)
  83. {
  84. _extensionMethodClassTypes.AddRange(types);
  85. _extensionMethods = ExtensionMethodCache.Build(_extensionMethodClassTypes);
  86. return this;
  87. }
  88. private void AttachExtensionMethodsToPrototypes(Engine engine)
  89. {
  90. AttachExtensionMethodsToPrototype(engine, engine.Array.PrototypeObject, typeof(Array));
  91. AttachExtensionMethodsToPrototype(engine, engine.Boolean.PrototypeObject, typeof(bool));
  92. AttachExtensionMethodsToPrototype(engine, engine.Date.PrototypeObject, typeof(DateTime));
  93. AttachExtensionMethodsToPrototype(engine, engine.Number.PrototypeObject, typeof(double));
  94. AttachExtensionMethodsToPrototype(engine, engine.Object.PrototypeObject, typeof(ExpandoObject));
  95. AttachExtensionMethodsToPrototype(engine, engine.RegExp.PrototypeObject, typeof(System.Text.RegularExpressions.Regex));
  96. AttachExtensionMethodsToPrototype(engine, engine.String.PrototypeObject, typeof(string));
  97. }
  98. private void AttachExtensionMethodsToPrototype(Engine engine, ObjectInstance prototype, Type objectType)
  99. {
  100. if (!_extensionMethods.TryGetExtensionMethods(objectType, out var methods))
  101. {
  102. return;
  103. }
  104. foreach (var overloads in methods.GroupBy(x => x.Name))
  105. {
  106. PropertyDescriptor CreateMethodInstancePropertyDescriptor(ClrFunctionInstance clrFunctionInstance)
  107. {
  108. var instance = clrFunctionInstance == null
  109. ? new MethodInfoFunctionInstance(engine, MethodDescriptor.Build(overloads.ToList()))
  110. : new MethodInfoFunctionInstance(engine, MethodDescriptor.Build(overloads.ToList()), clrFunctionInstance);
  111. return new PropertyDescriptor(instance, PropertyFlag.NonConfigurable);
  112. }
  113. JsValue key = overloads.Key;
  114. PropertyDescriptor descriptorWithFallback = null;
  115. PropertyDescriptor descriptorWithoutFallback = null;
  116. if (prototype.HasOwnProperty(key) && prototype.GetOwnProperty(key).Value is ClrFunctionInstance clrFunctionInstance)
  117. {
  118. descriptorWithFallback = CreateMethodInstancePropertyDescriptor(clrFunctionInstance);
  119. prototype.SetOwnProperty(key, descriptorWithFallback);
  120. }
  121. else
  122. {
  123. descriptorWithoutFallback = CreateMethodInstancePropertyDescriptor(null);
  124. prototype.SetOwnProperty(key, descriptorWithoutFallback);
  125. }
  126. // make sure we register both lower case and upper case
  127. if (char.IsUpper(overloads.Key[0]))
  128. {
  129. key = char.ToLower(overloads.Key[0]) + overloads.Key.Substring(1);
  130. if (prototype.HasOwnProperty(key) && prototype.GetOwnProperty(key).Value is ClrFunctionInstance lowerclrFunctionInstance)
  131. {
  132. descriptorWithFallback = descriptorWithFallback ?? CreateMethodInstancePropertyDescriptor(lowerclrFunctionInstance);
  133. prototype.SetOwnProperty(key, descriptorWithFallback);
  134. }
  135. else
  136. {
  137. descriptorWithoutFallback = descriptorWithoutFallback ?? CreateMethodInstancePropertyDescriptor(null);
  138. prototype.SetOwnProperty(key, descriptorWithoutFallback);
  139. }
  140. }
  141. }
  142. }
  143. /// <summary>
  144. /// If no known type could be guessed, objects are normally wrapped as an
  145. /// ObjectInstance using class ObjectWrapper. This function can be used to
  146. /// register a handler for a customized handling.
  147. /// </summary>
  148. public Options SetWrapObjectHandler(Func<Engine, object, ObjectInstance> wrapObjectHandler)
  149. {
  150. _wrapObjectHandler = wrapObjectHandler;
  151. return this;
  152. }
  153. /// <summary>
  154. /// Sets the type converter to use.
  155. /// </summary>
  156. public Options SetTypeConverter(Func<Engine, ITypeConverter> typeConverterFactory)
  157. {
  158. _configurations.Add(engine => engine.ClrTypeConverter = typeConverterFactory(engine));
  159. return this;
  160. }
  161. /// <summary>
  162. /// Registers a delegate that is called when CLR members are invoked. This allows
  163. /// to change what values are returned for specific CLR objects, or if any value
  164. /// is returned at all.
  165. /// </summary>
  166. /// <param name="accessor">
  167. /// The delegate to invoke for each CLR member. If the delegate
  168. /// returns <c>null</c>, the standard evaluation is performed.
  169. /// </param>
  170. public Options SetMemberAccessor(MemberAccessorDelegate accessor)
  171. {
  172. _memberAccessor = accessor;
  173. return this;
  174. }
  175. /// <summary>
  176. /// Allows scripts to call CLR types directly like <example>System.IO.File</example>
  177. /// </summary>
  178. public Options AllowClr(params Assembly[] assemblies)
  179. {
  180. _allowClr = true;
  181. _lookupAssemblies.AddRange(assemblies);
  182. _lookupAssemblies = _lookupAssemblies.Distinct().ToList();
  183. return this;
  184. }
  185. public Options AllowClrWrite(bool allow = true)
  186. {
  187. _allowClrWrite = allow;
  188. return this;
  189. }
  190. public Options AllowOperatorOverloading(bool allow = true)
  191. {
  192. _allowOperatorOverloading = allow;
  193. return this;
  194. }
  195. /// <summary>
  196. /// Exceptions thrown from CLR code are converted to JavaScript errors and
  197. /// can be used in at try/catch statement. By default these exceptions are bubbled
  198. /// to the CLR host and interrupt the script execution.
  199. /// </summary>
  200. public Options CatchClrExceptions()
  201. {
  202. CatchClrExceptions(_ => true);
  203. return this;
  204. }
  205. /// <summary>
  206. /// Exceptions that thrown from CLR code are converted to JavaScript errors and
  207. /// can be used in at try/catch statement. By default these exceptions are bubbled
  208. /// to the CLR host and interrupt the script execution.
  209. /// </summary>
  210. public Options CatchClrExceptions(Predicate<Exception> handler)
  211. {
  212. _clrExceptionsHandler = handler;
  213. return this;
  214. }
  215. public Options Constraint(IConstraint constraint)
  216. {
  217. if (constraint != null)
  218. {
  219. _constraints.Add(constraint);
  220. }
  221. return this;
  222. }
  223. public Options WithoutConstraint(Predicate<IConstraint> predicate)
  224. {
  225. _constraints.RemoveAll(predicate);
  226. return this;
  227. }
  228. public Options RegexTimeoutInterval(TimeSpan regexTimeoutInterval)
  229. {
  230. _regexTimeoutInterval = regexTimeoutInterval;
  231. return this;
  232. }
  233. /// <summary>
  234. /// Sets maximum allowed depth of recursion.
  235. /// </summary>
  236. /// <param name="maxRecursionDepth">
  237. /// The allowed depth.
  238. /// a) In case max depth is zero no recursion is allowed.
  239. /// b) In case max depth is equal to n it means that in one scope function can be called no more than n times.
  240. /// </param>
  241. /// <returns>Options instance for fluent syntax</returns>
  242. public Options LimitRecursion(int maxRecursionDepth = 0)
  243. {
  244. _maxRecursionDepth = maxRecursionDepth;
  245. return this;
  246. }
  247. public Options Culture(CultureInfo cultureInfo)
  248. {
  249. _culture = cultureInfo;
  250. return this;
  251. }
  252. public Options LocalTimeZone(TimeZoneInfo timeZoneInfo)
  253. {
  254. _localTimeZone = timeZoneInfo;
  255. return this;
  256. }
  257. public Options SetReferencesResolver(IReferenceResolver resolver)
  258. {
  259. _referenceResolver = resolver;
  260. return this;
  261. }
  262. /// <summary>
  263. /// Registers some custom logic to apply on an <see cref="Engine"/> instance when the options
  264. /// are loaded.
  265. /// </summary>
  266. /// <param name="configuration">The action to register.</param>
  267. public Options Configure(Action<Engine> configuration)
  268. {
  269. _configurations.Add(configuration);
  270. return this;
  271. }
  272. /// <summary>
  273. /// Called by the <see cref="Engine"/> instance that loads this <see cref="Options" />
  274. /// once it is loaded.
  275. /// </summary>
  276. internal void Apply(Engine engine)
  277. {
  278. foreach (var configuration in _configurations)
  279. {
  280. configuration?.Invoke(engine);
  281. }
  282. // add missing bits if needed
  283. if (_allowClr)
  284. {
  285. engine.Global.SetProperty("System", new PropertyDescriptor(new NamespaceReference(engine, "System"), PropertyFlag.AllForbidden));
  286. engine.Global.SetProperty("importNamespace", new PropertyDescriptor(new ClrFunctionInstance(
  287. engine,
  288. "importNamespace",
  289. func: (thisObj, arguments) => new NamespaceReference(engine, TypeConverter.ToString(arguments.At(0)))), PropertyFlag.AllForbidden));
  290. }
  291. if (_extensionMethodClassTypes.Count > 0)
  292. {
  293. AttachExtensionMethodsToPrototypes(engine);
  294. }
  295. // ensure defaults
  296. engine.ClrTypeConverter ??= new DefaultTypeConverter(engine);
  297. }
  298. internal bool IsStrict => _strict;
  299. internal DebuggerStatementHandling _DebuggerStatementHandling => _debuggerStatementHandling;
  300. internal bool IsDebugMode { get; private set; }
  301. internal bool _IsClrWriteAllowed => _allowClrWrite;
  302. internal bool _IsOperatorOverloadingAllowed => _allowOperatorOverloading;
  303. internal Predicate<Exception> _ClrExceptionsHandler => _clrExceptionsHandler;
  304. internal List<Assembly> _LookupAssemblies => _lookupAssemblies;
  305. internal List<IObjectConverter> _ObjectConverters => _objectConverters;
  306. internal List<IConstraint> _Constraints => _constraints;
  307. internal Func<Engine, object, ObjectInstance> _WrapObjectHandler => _wrapObjectHandler;
  308. internal MemberAccessorDelegate _MemberAccessor => _memberAccessor;
  309. internal int MaxRecursionDepth => _maxRecursionDepth;
  310. internal TimeSpan _RegexTimeoutInterval => _regexTimeoutInterval;
  311. internal CultureInfo _Culture => _culture;
  312. internal TimeZoneInfo _LocalTimeZone => _localTimeZone;
  313. internal IReferenceResolver ReferenceResolver => _referenceResolver;
  314. private sealed class DefaultReferenceResolver : IReferenceResolver
  315. {
  316. public static readonly DefaultReferenceResolver Instance = new DefaultReferenceResolver();
  317. private DefaultReferenceResolver()
  318. {
  319. }
  320. public bool TryUnresolvableReference(Engine engine, Reference reference, out JsValue value)
  321. {
  322. value = JsValue.Undefined;
  323. return false;
  324. }
  325. public bool TryPropertyReference(Engine engine, Reference reference, ref JsValue value)
  326. {
  327. return false;
  328. }
  329. public bool TryGetCallable(Engine engine, object callee, out JsValue value)
  330. {
  331. value = JsValue.Undefined;
  332. return false;
  333. }
  334. public bool CheckCoercible(JsValue value)
  335. {
  336. return false;
  337. }
  338. }
  339. }
  340. }