Function.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. using System.Diagnostics;
  2. using System.Runtime.CompilerServices;
  3. using Jint.Native.Object;
  4. using Jint.Runtime;
  5. using Jint.Runtime.Descriptors;
  6. using Jint.Runtime.Environments;
  7. using Jint.Runtime.Interpreter;
  8. using Environment = Jint.Runtime.Environments.Environment;
  9. namespace Jint.Native.Function;
  10. [DebuggerDisplay("{ToString(),nq}")]
  11. #pragma warning disable MA0049
  12. public abstract partial class Function : ObjectInstance, ICallable
  13. #pragma warning restore MA0049
  14. {
  15. protected PropertyDescriptor? _prototypeDescriptor;
  16. protected internal PropertyDescriptor? _length;
  17. internal PropertyDescriptor? _nameDescriptor;
  18. internal Environment? _environment;
  19. internal readonly JintFunctionDefinition? _functionDefinition;
  20. internal readonly FunctionThisMode _thisMode;
  21. internal JsValue _homeObject = Undefined;
  22. internal ConstructorKind _constructorKind = ConstructorKind.Base;
  23. internal Realm _realm;
  24. internal PrivateEnvironment? _privateEnvironment;
  25. private readonly IScriptOrModule? _scriptOrModule;
  26. protected Function(
  27. Engine engine,
  28. Realm realm,
  29. JsString? name)
  30. : this(engine, realm, name, FunctionThisMode.Global)
  31. {
  32. }
  33. internal Function(
  34. Engine engine,
  35. Realm realm,
  36. JintFunctionDefinition function,
  37. Environment env,
  38. FunctionThisMode thisMode)
  39. : this(
  40. engine,
  41. realm,
  42. !string.IsNullOrWhiteSpace(function.Name) ? new JsString(function.Name!) : null,
  43. thisMode)
  44. {
  45. _functionDefinition = function;
  46. _environment = env;
  47. }
  48. internal Function(
  49. Engine engine,
  50. Realm realm,
  51. JsString? name,
  52. FunctionThisMode thisMode = FunctionThisMode.Global,
  53. ObjectClass objectClass = ObjectClass.Function)
  54. : base(engine, objectClass)
  55. {
  56. if (name is not null)
  57. {
  58. _nameDescriptor = new PropertyDescriptor(name, PropertyFlag.Configurable);
  59. }
  60. _realm = realm;
  61. _thisMode = thisMode;
  62. _scriptOrModule = _engine.GetActiveScriptOrModule();
  63. }
  64. // for example RavenDB wants to inspect this
  65. public IFunction? FunctionDeclaration => _functionDefinition?.Function;
  66. internal override bool IsCallable => true;
  67. JsValue ICallable.Call(JsValue thisObject, params JsCallArguments arguments) => Call(thisObject, arguments);
  68. /// <summary>
  69. /// Executed when a function object is used as a function
  70. /// </summary>
  71. protected internal abstract JsValue Call(JsValue thisObject, JsCallArguments arguments);
  72. public bool Strict => _thisMode == FunctionThisMode.Strict;
  73. internal override bool IsConstructor => this is IConstructor;
  74. public override IEnumerable<KeyValuePair<JsValue, PropertyDescriptor>> GetOwnProperties()
  75. {
  76. if (_prototypeDescriptor != null)
  77. {
  78. yield return new KeyValuePair<JsValue, PropertyDescriptor>(CommonProperties.Prototype, _prototypeDescriptor);
  79. }
  80. if (_length != null)
  81. {
  82. yield return new KeyValuePair<JsValue, PropertyDescriptor>(CommonProperties.Length, _length);
  83. }
  84. if (_nameDescriptor != null)
  85. {
  86. yield return new KeyValuePair<JsValue, PropertyDescriptor>(CommonProperties.Name, GetOwnProperty(CommonProperties.Name));
  87. }
  88. foreach (var entry in base.GetOwnProperties())
  89. {
  90. yield return entry;
  91. }
  92. }
  93. internal sealed override IEnumerable<JsValue> GetInitialOwnStringPropertyKeys()
  94. {
  95. if (_length != null)
  96. {
  97. yield return CommonProperties.Length;
  98. }
  99. if (_nameDescriptor != null)
  100. {
  101. yield return CommonProperties.Name;
  102. }
  103. if (_prototypeDescriptor != null)
  104. {
  105. yield return CommonProperties.Prototype;
  106. }
  107. }
  108. public override PropertyDescriptor GetOwnProperty(JsValue property)
  109. {
  110. if (CommonProperties.Prototype.Equals(property))
  111. {
  112. return _prototypeDescriptor ?? PropertyDescriptor.Undefined;
  113. }
  114. if (CommonProperties.Length.Equals(property))
  115. {
  116. return _length ?? PropertyDescriptor.Undefined;
  117. }
  118. if (CommonProperties.Name.Equals(property))
  119. {
  120. return _nameDescriptor ?? PropertyDescriptor.Undefined;
  121. }
  122. return base.GetOwnProperty(property);
  123. }
  124. protected internal override void SetOwnProperty(JsValue property, PropertyDescriptor desc)
  125. {
  126. if (CommonProperties.Prototype.Equals(property))
  127. {
  128. _prototypeDescriptor = desc;
  129. }
  130. else if (CommonProperties.Length.Equals(property))
  131. {
  132. _length = desc;
  133. }
  134. else if (CommonProperties.Name.Equals(property))
  135. {
  136. _nameDescriptor = desc;
  137. }
  138. else
  139. {
  140. base.SetOwnProperty(property, desc);
  141. }
  142. }
  143. public override void RemoveOwnProperty(JsValue property)
  144. {
  145. if (CommonProperties.Prototype.Equals(property))
  146. {
  147. _prototypeDescriptor = null;
  148. }
  149. if (CommonProperties.Length.Equals(property))
  150. {
  151. _length = null;
  152. }
  153. if (CommonProperties.Name.Equals(property))
  154. {
  155. _nameDescriptor = null;
  156. }
  157. base.RemoveOwnProperty(property);
  158. }
  159. /// <summary>
  160. /// https://tc39.es/ecma262/#sec-setfunctionname
  161. /// </summary>
  162. internal void SetFunctionName(JsValue name, string? prefix = null, bool force = false)
  163. {
  164. if (!force && _nameDescriptor != null && UnwrapJsValue(_nameDescriptor) != JsString.Empty)
  165. {
  166. return;
  167. }
  168. if (name is JsSymbol symbol)
  169. {
  170. name = symbol._value.IsUndefined()
  171. ? JsString.Empty
  172. : new JsString("[" + symbol._value + "]");
  173. }
  174. else if (name is PrivateName privateName)
  175. {
  176. name = "#" + privateName.Description;
  177. }
  178. if (!string.IsNullOrWhiteSpace(prefix))
  179. {
  180. name = prefix + " " + name;
  181. }
  182. _nameDescriptor = new PropertyDescriptor(name, PropertyFlag.Configurable);
  183. }
  184. /// <summary>
  185. /// https://tc39.es/ecma262/#sec-ordinarycreatefromconstructor
  186. /// </summary>
  187. /// <remarks>
  188. /// Uses separate builder to get correct type with state support to prevent allocations.
  189. /// In spec intrinsicDefaultProto is string pointing to intrinsic, but we do a selector.
  190. /// </remarks>
  191. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  192. internal T OrdinaryCreateFromConstructor<T, TState>(
  193. JsValue constructor,
  194. Func<Intrinsics, ObjectInstance> intrinsicDefaultProto,
  195. Func<Engine, Realm, TState?, T> objectCreator,
  196. TState? state = default) where T : ObjectInstance
  197. {
  198. var proto = GetPrototypeFromConstructor(constructor, intrinsicDefaultProto);
  199. var obj = objectCreator(_engine, _realm, state);
  200. obj._prototype = proto;
  201. return obj;
  202. }
  203. /// <summary>
  204. /// https://tc39.es/ecma262/#sec-getprototypefromconstructor
  205. /// </summary>
  206. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  207. internal ObjectInstance GetPrototypeFromConstructor(JsValue constructor, Func<Intrinsics, ObjectInstance> intrinsicDefaultProto)
  208. {
  209. if (constructor.Get(CommonProperties.Prototype) is not ObjectInstance proto)
  210. {
  211. var realm = GetFunctionRealm(constructor);
  212. proto = intrinsicDefaultProto(realm.Intrinsics);
  213. }
  214. return proto;
  215. }
  216. /// <summary>
  217. /// https://tc39.es/ecma262/#sec-getfunctionrealm
  218. /// </summary>
  219. internal Realm GetFunctionRealm(JsValue obj)
  220. {
  221. if (obj is Function functionInstance && functionInstance._realm is not null)
  222. {
  223. return functionInstance._realm;
  224. }
  225. if (obj is BindFunction bindFunctionInstance)
  226. {
  227. return GetFunctionRealm(bindFunctionInstance.BoundTargetFunction);
  228. }
  229. if (obj is JsProxy proxyInstance)
  230. {
  231. if (proxyInstance._handler is null)
  232. {
  233. ExceptionHelper.ThrowTypeErrorNoEngine();
  234. }
  235. return GetFunctionRealm(proxyInstance._target);
  236. }
  237. return _engine.ExecutionContext.Realm;
  238. }
  239. /// <summary>
  240. /// https://tc39.es/ecma262/#sec-makemethod
  241. /// </summary>
  242. internal void MakeMethod(ObjectInstance homeObject)
  243. {
  244. _homeObject = homeObject;
  245. }
  246. /// <summary>
  247. /// https://tc39.es/ecma262/#sec-ordinarycallbindthis
  248. /// </summary>
  249. internal void OrdinaryCallBindThis(in ExecutionContext calleeContext, JsValue thisArgument)
  250. {
  251. if (_thisMode == FunctionThisMode.Lexical)
  252. {
  253. return;
  254. }
  255. var calleeRealm = _realm;
  256. var localEnv = (FunctionEnvironment) calleeContext.LexicalEnvironment;
  257. JsValue thisValue;
  258. if (_thisMode == FunctionThisMode.Strict)
  259. {
  260. thisValue = thisArgument;
  261. }
  262. else
  263. {
  264. if (thisArgument is null || thisArgument.IsNullOrUndefined())
  265. {
  266. var globalEnv = calleeRealm.GlobalEnv;
  267. thisValue = globalEnv.GlobalThisValue;
  268. }
  269. else
  270. {
  271. thisValue = TypeConverter.ToObject(calleeRealm, thisArgument);
  272. }
  273. }
  274. localEnv.BindThisValue(thisValue);
  275. }
  276. /// <summary>
  277. /// https://tc39.es/ecma262/#sec-prepareforordinarycall
  278. /// </summary>
  279. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  280. internal ref readonly ExecutionContext PrepareForOrdinaryCall(JsValue newTarget)
  281. {
  282. var callerContext = _engine.ExecutionContext;
  283. var localEnv = JintEnvironment.NewFunctionEnvironment(_engine, this, newTarget);
  284. var calleeRealm = _realm;
  285. var calleeContext = new ExecutionContext(
  286. _scriptOrModule,
  287. lexicalEnvironment: localEnv,
  288. variableEnvironment: localEnv,
  289. _privateEnvironment,
  290. calleeRealm,
  291. generator: null,
  292. function: this);
  293. // If callerContext is not already suspended, suspend callerContext.
  294. // Push calleeContext onto the execution context stack; calleeContext is now the running execution context.
  295. // NOTE: Any exception objects produced after this point are associated with calleeRealm.
  296. // Return calleeContext.
  297. _engine.EnterExecutionContext(calleeContext);
  298. return ref _engine.ExecutionContext;
  299. }
  300. internal void MakeConstructor(bool writableProperty = true, ObjectInstance? prototype = null)
  301. {
  302. _constructorKind = ConstructorKind.Base;
  303. if (prototype is null)
  304. {
  305. prototype = new ObjectInstanceWithConstructor(_engine, this)
  306. {
  307. _prototype = _realm.Intrinsics.Object.PrototypeObject
  308. };
  309. }
  310. _prototypeDescriptor = new PropertyDescriptor(prototype, writableProperty, enumerable: false, configurable: false);
  311. }
  312. internal void SetFunctionLength(JsNumber length)
  313. {
  314. DefinePropertyOrThrow(CommonProperties.Length, new PropertyDescriptor(length, writable: false, enumerable: false, configurable: true));
  315. }
  316. // native syntax doesn't expect to have private identifier indicator
  317. private static readonly char[] _functionNameTrimStartChars = ['#'];
  318. public override string ToString()
  319. {
  320. if (_functionDefinition?.Function is Node node && _engine.Options.Host.FunctionToStringHandler(this, node) is { } s)
  321. {
  322. return s;
  323. }
  324. var nameValue = _nameDescriptor != null ? UnwrapJsValue(_nameDescriptor) : JsString.Empty;
  325. var name = "";
  326. if (!nameValue.IsUndefined())
  327. {
  328. name = TypeConverter.ToString(nameValue);
  329. }
  330. name = name.TrimStart(_functionNameTrimStartChars);
  331. return $"function {name}() {{ [native code] }}";
  332. }
  333. private sealed class ObjectInstanceWithConstructor : ObjectInstance
  334. {
  335. private PropertyDescriptor? _constructor;
  336. public ObjectInstanceWithConstructor(Engine engine, ObjectInstance thisObj) : base(engine)
  337. {
  338. _constructor = new PropertyDescriptor(thisObj, PropertyFlag.NonEnumerable);
  339. }
  340. public override IEnumerable<KeyValuePair<JsValue, PropertyDescriptor>> GetOwnProperties()
  341. {
  342. if (_constructor != null)
  343. {
  344. yield return new KeyValuePair<JsValue, PropertyDescriptor>(CommonProperties.Constructor, _constructor);
  345. }
  346. foreach (var entry in base.GetOwnProperties())
  347. {
  348. yield return entry;
  349. }
  350. }
  351. public override PropertyDescriptor GetOwnProperty(JsValue property)
  352. {
  353. if (CommonProperties.Constructor.Equals(property))
  354. {
  355. return _constructor ?? PropertyDescriptor.Undefined;
  356. }
  357. return base.GetOwnProperty(property);
  358. }
  359. protected internal override void SetOwnProperty(JsValue property, PropertyDescriptor desc)
  360. {
  361. if (CommonProperties.Constructor.Equals(property))
  362. {
  363. _constructor = desc;
  364. }
  365. else
  366. {
  367. base.SetOwnProperty(property, desc);
  368. }
  369. }
  370. public override void RemoveOwnProperty(JsValue property)
  371. {
  372. if (CommonProperties.Constructor.Equals(property))
  373. {
  374. _constructor = null;
  375. }
  376. else
  377. {
  378. base.RemoveOwnProperty(property);
  379. }
  380. }
  381. }
  382. }