FunctionInstance.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.CompilerServices;
  4. using Esprima.Ast;
  5. using Jint.Native.Object;
  6. using Jint.Native.Proxy;
  7. using Jint.Runtime;
  8. using Jint.Runtime.Descriptors;
  9. using Jint.Runtime.Environments;
  10. using Jint.Runtime.Interpreter;
  11. namespace Jint.Native.Function
  12. {
  13. public abstract class FunctionInstance : ObjectInstance, ICallable
  14. {
  15. protected PropertyDescriptor _prototypeDescriptor;
  16. protected internal PropertyDescriptor _length;
  17. private PropertyDescriptor _nameDescriptor;
  18. protected internal EnvironmentRecord _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. private PrivateEnvironmentRecord _privateEnvironment;
  25. protected FunctionInstance(
  26. Engine engine,
  27. Realm realm,
  28. JsString name)
  29. : this(engine, realm, name, FunctionThisMode.Global, ObjectClass.Function)
  30. {
  31. }
  32. internal FunctionInstance(
  33. Engine engine,
  34. Realm realm,
  35. JintFunctionDefinition function,
  36. EnvironmentRecord scope,
  37. FunctionThisMode thisMode)
  38. : this(
  39. engine,
  40. realm,
  41. !string.IsNullOrWhiteSpace(function.Name) ? new JsString(function.Name) : null,
  42. thisMode)
  43. {
  44. _functionDefinition = function;
  45. _environment = scope;
  46. }
  47. internal FunctionInstance(
  48. Engine engine,
  49. Realm realm,
  50. JsString name,
  51. FunctionThisMode thisMode = FunctionThisMode.Global,
  52. ObjectClass objectClass = ObjectClass.Function)
  53. : base(engine, objectClass)
  54. {
  55. if (name is not null)
  56. {
  57. _nameDescriptor = new PropertyDescriptor(name, PropertyFlag.Configurable);
  58. }
  59. _realm = realm;
  60. _thisMode = thisMode;
  61. }
  62. // for example RavenDB wants to inspect this
  63. public IFunction FunctionDeclaration => _functionDefinition.Function;
  64. /// <summary>
  65. /// Executed when a function object is used as a function
  66. /// </summary>
  67. /// <param name="thisObject"></param>
  68. /// <param name="arguments"></param>
  69. /// <returns></returns>
  70. public abstract JsValue Call(JsValue thisObject, JsValue[] arguments);
  71. public bool Strict => _thisMode == FunctionThisMode.Strict;
  72. internal override bool IsConstructor => this is IConstructor;
  73. public override IEnumerable<KeyValuePair<JsValue, PropertyDescriptor>> GetOwnProperties()
  74. {
  75. if (_prototypeDescriptor != null)
  76. {
  77. yield return new KeyValuePair<JsValue, PropertyDescriptor>(CommonProperties.Prototype, _prototypeDescriptor);
  78. }
  79. if (_length != null)
  80. {
  81. yield return new KeyValuePair<JsValue, PropertyDescriptor>(CommonProperties.Length, _length);
  82. }
  83. if (_nameDescriptor != null)
  84. {
  85. yield return new KeyValuePair<JsValue, PropertyDescriptor>(CommonProperties.Name, GetOwnProperty(CommonProperties.Name));
  86. }
  87. foreach (var entry in base.GetOwnProperties())
  88. {
  89. yield return entry;
  90. }
  91. }
  92. public override List<JsValue> GetOwnPropertyKeys(Types types)
  93. {
  94. var keys = base.GetOwnPropertyKeys(types);
  95. // works around a problem where we don't use property for function names and classes should report it last
  96. // as it's the last operation when creating a class constructor
  97. if ((types & Types.String) != 0 && _nameDescriptor != null && this is ScriptFunctionInstance { _isClassConstructor: true })
  98. {
  99. keys.Add(CommonProperties.Name);
  100. }
  101. return keys;
  102. }
  103. internal override IEnumerable<JsValue> GetInitialOwnStringPropertyKeys()
  104. {
  105. if (_length != null)
  106. {
  107. yield return CommonProperties.Length;
  108. }
  109. // works around a problem where we don't use property for function names and classes should report it last
  110. // as it's the last operation when creating a class constructor
  111. if (_nameDescriptor != null && this is not ScriptFunctionInstance { _isClassConstructor: true })
  112. {
  113. yield return CommonProperties.Name;
  114. }
  115. if (_prototypeDescriptor != null)
  116. {
  117. yield return CommonProperties.Prototype;
  118. }
  119. }
  120. public override PropertyDescriptor GetOwnProperty(JsValue property)
  121. {
  122. if (property == CommonProperties.Prototype)
  123. {
  124. return _prototypeDescriptor ?? PropertyDescriptor.Undefined;
  125. }
  126. if (property == CommonProperties.Length)
  127. {
  128. return _length ?? PropertyDescriptor.Undefined;
  129. }
  130. if (property == CommonProperties.Name)
  131. {
  132. return _nameDescriptor ?? PropertyDescriptor.Undefined;
  133. }
  134. return base.GetOwnProperty(property);
  135. }
  136. protected internal override void SetOwnProperty(JsValue property, PropertyDescriptor desc)
  137. {
  138. if (property == CommonProperties.Prototype)
  139. {
  140. _prototypeDescriptor = desc;
  141. }
  142. else if (property == CommonProperties.Length)
  143. {
  144. _length = desc;
  145. }
  146. else if (property == CommonProperties.Name)
  147. {
  148. _nameDescriptor = desc;
  149. }
  150. else
  151. {
  152. base.SetOwnProperty(property, desc);
  153. }
  154. }
  155. public override bool HasOwnProperty(JsValue property)
  156. {
  157. if (property == CommonProperties.Prototype)
  158. {
  159. return _prototypeDescriptor != null;
  160. }
  161. if (property == CommonProperties.Length)
  162. {
  163. return _length != null;
  164. }
  165. if (property == CommonProperties.Name)
  166. {
  167. return _nameDescriptor != null;
  168. }
  169. return base.HasOwnProperty(property);
  170. }
  171. public override void RemoveOwnProperty(JsValue property)
  172. {
  173. if (property == CommonProperties.Prototype)
  174. {
  175. _prototypeDescriptor = null;
  176. }
  177. if (property == CommonProperties.Length)
  178. {
  179. _length = null;
  180. }
  181. if (property == CommonProperties.Name)
  182. {
  183. _nameDescriptor = null;
  184. }
  185. base.RemoveOwnProperty(property);
  186. }
  187. internal void SetFunctionName(JsValue name, string prefix = null, bool force = false)
  188. {
  189. if (!force && _nameDescriptor != null && UnwrapJsValue(_nameDescriptor) != JsString.Empty)
  190. {
  191. return;
  192. }
  193. if (name is JsSymbol symbol)
  194. {
  195. name = symbol._value.IsUndefined()
  196. ? JsString.Empty
  197. : new JsString("[" + symbol._value + "]");
  198. }
  199. if (!string.IsNullOrWhiteSpace(prefix))
  200. {
  201. name = prefix + " " + name;
  202. }
  203. _nameDescriptor = new PropertyDescriptor(name, PropertyFlag.Configurable);
  204. }
  205. /// <summary>
  206. /// https://tc39.es/ecma262/#sec-ordinarycreatefromconstructor
  207. /// </summary>
  208. /// <remarks>
  209. /// Uses separate builder to get correct type with state support to prevent allocations.
  210. /// In spec intrinsicDefaultProto is string pointing to intrinsic, but we do a selector.
  211. /// </remarks>
  212. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  213. internal T OrdinaryCreateFromConstructor<T>(
  214. JsValue constructor,
  215. Func<Intrinsics, ObjectInstance> intrinsicDefaultProto,
  216. Func<Engine, Realm, JsValue, T> objectCreator,
  217. JsValue state = null) where T : ObjectInstance
  218. {
  219. var proto = GetPrototypeFromConstructor(constructor, intrinsicDefaultProto);
  220. var obj = objectCreator(_engine, _realm, state);
  221. obj._prototype = proto;
  222. return obj;
  223. }
  224. /// <summary>
  225. /// https://tc39.es/ecma262/#sec-getprototypefromconstructor
  226. /// </summary>
  227. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  228. internal ObjectInstance GetPrototypeFromConstructor(JsValue constructor, Func<Intrinsics, ObjectInstance> intrinsicDefaultProto)
  229. {
  230. var proto = constructor.Get(CommonProperties.Prototype, constructor) as ObjectInstance;
  231. if (proto is null)
  232. {
  233. var realm = GetFunctionRealm(constructor);
  234. proto = intrinsicDefaultProto(realm.Intrinsics);
  235. }
  236. return proto;
  237. }
  238. /// <summary>
  239. /// https://tc39.es/ecma262/#sec-getfunctionrealm
  240. /// </summary>
  241. internal Realm GetFunctionRealm(JsValue obj)
  242. {
  243. if (obj is FunctionInstance functionInstance && functionInstance._realm is not null)
  244. {
  245. return functionInstance._realm;
  246. }
  247. if (obj is BindFunctionInstance bindFunctionInstance)
  248. {
  249. return GetFunctionRealm(bindFunctionInstance.BoundTargetFunction);
  250. }
  251. if (obj is ProxyInstance proxyInstance)
  252. {
  253. if (proxyInstance._handler is null)
  254. {
  255. ExceptionHelper.ThrowTypeErrorNoEngine();
  256. }
  257. return GetFunctionRealm(proxyInstance._target);
  258. }
  259. return _engine.ExecutionContext.Realm;
  260. }
  261. internal void MakeMethod(ObjectInstance homeObject)
  262. {
  263. _homeObject = homeObject;
  264. }
  265. /// <summary>
  266. /// https://tc39.es/ecma262/#sec-ordinarycallbindthis
  267. /// </summary>
  268. internal void OrdinaryCallBindThis(ExecutionContext calleeContext, JsValue thisArgument)
  269. {
  270. var thisMode = _thisMode;
  271. if (thisMode == FunctionThisMode.Lexical)
  272. {
  273. return;
  274. }
  275. var calleeRealm = _realm;
  276. var localEnv = (FunctionEnvironmentRecord) calleeContext.LexicalEnvironment;
  277. JsValue thisValue;
  278. if (_thisMode == FunctionThisMode.Strict)
  279. {
  280. thisValue = thisArgument;
  281. }
  282. else
  283. {
  284. if (thisArgument.IsNullOrUndefined())
  285. {
  286. var globalEnv = calleeRealm.GlobalEnv;
  287. thisValue = globalEnv.GlobalThisValue;
  288. }
  289. else
  290. {
  291. thisValue = TypeConverter.ToObject(calleeRealm, thisArgument);
  292. }
  293. }
  294. localEnv.BindThisValue(thisValue);
  295. }
  296. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  297. internal Completion OrdinaryCallEvaluateBody(
  298. EvaluationContext context,
  299. JsValue[] arguments,
  300. ExecutionContext calleeContext)
  301. {
  302. var argumentsInstance = _engine.FunctionDeclarationInstantiation(
  303. functionInstance: this,
  304. arguments);
  305. var result = _functionDefinition.Execute(context);
  306. argumentsInstance?.FunctionWasCalled();
  307. return result;
  308. }
  309. /// <summary>
  310. /// https://tc39.es/ecma262/#sec-prepareforordinarycall
  311. /// </summary>
  312. internal ExecutionContext PrepareForOrdinaryCall(JsValue newTarget)
  313. {
  314. var callerContext = _engine.ExecutionContext;
  315. var localEnv = JintEnvironment.NewFunctionEnvironment(_engine, this, newTarget);
  316. var calleeRealm = _realm;
  317. var calleeContext = new ExecutionContext(
  318. localEnv,
  319. localEnv,
  320. _privateEnvironment,
  321. calleeRealm,
  322. this);
  323. // If callerContext is not already suspended, suspend callerContext.
  324. // Push calleeContext onto the execution context stack; calleeContext is now the running execution context.
  325. // NOTE: Any exception objects produced after this point are associated with calleeRealm.
  326. // Return calleeContext.
  327. return _engine.EnterExecutionContext(calleeContext);
  328. }
  329. public override string ToString()
  330. {
  331. // TODO no way to extract SourceText from Esprima at the moment, just returning native code
  332. var nameValue = _nameDescriptor != null ? UnwrapJsValue(_nameDescriptor) : JsString.Empty;
  333. var name = "";
  334. if (!nameValue.IsUndefined())
  335. {
  336. name = TypeConverter.ToString(nameValue);
  337. }
  338. return "function " + name + "() { [native code] }";
  339. }
  340. }
  341. }