2
0

FunctionInstance.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. internal 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. internal override bool IsCallable => true;
  65. JsValue ICallable.Call(JsValue thisObject, JsValue[] arguments) => Call(thisObject, arguments);
  66. /// <summary>
  67. /// Executed when a function object is used as a function
  68. /// </summary>
  69. protected internal abstract JsValue Call(JsValue thisObject, JsValue[] arguments);
  70. public bool Strict => _thisMode == FunctionThisMode.Strict;
  71. internal override bool IsConstructor => this is IConstructor;
  72. public override IEnumerable<KeyValuePair<JsValue, PropertyDescriptor>> GetOwnProperties()
  73. {
  74. if (_prototypeDescriptor != null)
  75. {
  76. yield return new KeyValuePair<JsValue, PropertyDescriptor>(CommonProperties.Prototype, _prototypeDescriptor);
  77. }
  78. if (_length != null)
  79. {
  80. yield return new KeyValuePair<JsValue, PropertyDescriptor>(CommonProperties.Length, _length);
  81. }
  82. if (_nameDescriptor != null)
  83. {
  84. yield return new KeyValuePair<JsValue, PropertyDescriptor>(CommonProperties.Name, GetOwnProperty(CommonProperties.Name));
  85. }
  86. foreach (var entry in base.GetOwnProperties())
  87. {
  88. yield return entry;
  89. }
  90. }
  91. internal override IEnumerable<JsValue> GetInitialOwnStringPropertyKeys()
  92. {
  93. if (_length != null)
  94. {
  95. yield return CommonProperties.Length;
  96. }
  97. if (_nameDescriptor != null)
  98. {
  99. yield return CommonProperties.Name;
  100. }
  101. if (_prototypeDescriptor != null)
  102. {
  103. yield return CommonProperties.Prototype;
  104. }
  105. }
  106. public override PropertyDescriptor GetOwnProperty(JsValue property)
  107. {
  108. if (property == CommonProperties.Prototype)
  109. {
  110. return _prototypeDescriptor ?? PropertyDescriptor.Undefined;
  111. }
  112. if (property == CommonProperties.Length)
  113. {
  114. return _length ?? PropertyDescriptor.Undefined;
  115. }
  116. if (property == CommonProperties.Name)
  117. {
  118. return _nameDescriptor ?? PropertyDescriptor.Undefined;
  119. }
  120. return base.GetOwnProperty(property);
  121. }
  122. protected internal override void SetOwnProperty(JsValue property, PropertyDescriptor desc)
  123. {
  124. if (property == CommonProperties.Prototype)
  125. {
  126. _prototypeDescriptor = desc;
  127. }
  128. else if (property == CommonProperties.Length)
  129. {
  130. _length = desc;
  131. }
  132. else if (property == CommonProperties.Name)
  133. {
  134. _nameDescriptor = desc;
  135. }
  136. else
  137. {
  138. base.SetOwnProperty(property, desc);
  139. }
  140. }
  141. public override bool HasOwnProperty(JsValue property)
  142. {
  143. if (property == CommonProperties.Prototype)
  144. {
  145. return _prototypeDescriptor != null;
  146. }
  147. if (property == CommonProperties.Length)
  148. {
  149. return _length != null;
  150. }
  151. if (property == CommonProperties.Name)
  152. {
  153. return _nameDescriptor != null;
  154. }
  155. return base.HasOwnProperty(property);
  156. }
  157. public override void RemoveOwnProperty(JsValue property)
  158. {
  159. if (property == CommonProperties.Prototype)
  160. {
  161. _prototypeDescriptor = null;
  162. }
  163. if (property == CommonProperties.Length)
  164. {
  165. _length = null;
  166. }
  167. if (property == CommonProperties.Name)
  168. {
  169. _nameDescriptor = null;
  170. }
  171. base.RemoveOwnProperty(property);
  172. }
  173. internal void SetFunctionName(JsValue name, string prefix = null, bool force = false)
  174. {
  175. if (!force && _nameDescriptor != null && UnwrapJsValue(_nameDescriptor) != JsString.Empty)
  176. {
  177. return;
  178. }
  179. if (name is JsSymbol symbol)
  180. {
  181. name = symbol._value.IsUndefined()
  182. ? JsString.Empty
  183. : new JsString("[" + symbol._value + "]");
  184. }
  185. if (!string.IsNullOrWhiteSpace(prefix))
  186. {
  187. name = prefix + " " + name;
  188. }
  189. _nameDescriptor = new PropertyDescriptor(name, PropertyFlag.Configurable);
  190. }
  191. /// <summary>
  192. /// https://tc39.es/ecma262/#sec-ordinarycreatefromconstructor
  193. /// </summary>
  194. /// <remarks>
  195. /// Uses separate builder to get correct type with state support to prevent allocations.
  196. /// In spec intrinsicDefaultProto is string pointing to intrinsic, but we do a selector.
  197. /// </remarks>
  198. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  199. internal T OrdinaryCreateFromConstructor<T>(
  200. JsValue constructor,
  201. Func<Intrinsics, ObjectInstance> intrinsicDefaultProto,
  202. Func<Engine, Realm, JsValue, T> objectCreator,
  203. JsValue state = null) where T : ObjectInstance
  204. {
  205. var proto = GetPrototypeFromConstructor(constructor, intrinsicDefaultProto);
  206. var obj = objectCreator(_engine, _realm, state);
  207. obj._prototype = proto;
  208. return obj;
  209. }
  210. /// <summary>
  211. /// https://tc39.es/ecma262/#sec-getprototypefromconstructor
  212. /// </summary>
  213. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  214. internal ObjectInstance GetPrototypeFromConstructor(JsValue constructor, Func<Intrinsics, ObjectInstance> intrinsicDefaultProto)
  215. {
  216. var proto = constructor.Get(CommonProperties.Prototype, constructor) as ObjectInstance;
  217. if (proto is null)
  218. {
  219. var realm = GetFunctionRealm(constructor);
  220. proto = intrinsicDefaultProto(realm.Intrinsics);
  221. }
  222. return proto;
  223. }
  224. /// <summary>
  225. /// https://tc39.es/ecma262/#sec-getfunctionrealm
  226. /// </summary>
  227. internal Realm GetFunctionRealm(JsValue obj)
  228. {
  229. if (obj is FunctionInstance functionInstance && functionInstance._realm is not null)
  230. {
  231. return functionInstance._realm;
  232. }
  233. if (obj is BindFunctionInstance bindFunctionInstance)
  234. {
  235. return GetFunctionRealm(bindFunctionInstance.BoundTargetFunction);
  236. }
  237. if (obj is ProxyInstance proxyInstance)
  238. {
  239. if (proxyInstance._handler is null)
  240. {
  241. ExceptionHelper.ThrowTypeErrorNoEngine();
  242. }
  243. return GetFunctionRealm(proxyInstance._target);
  244. }
  245. return _engine.ExecutionContext.Realm;
  246. }
  247. internal void MakeMethod(ObjectInstance homeObject)
  248. {
  249. _homeObject = homeObject;
  250. }
  251. /// <summary>
  252. /// https://tc39.es/ecma262/#sec-ordinarycallbindthis
  253. /// </summary>
  254. internal void OrdinaryCallBindThis(ExecutionContext calleeContext, JsValue thisArgument)
  255. {
  256. var thisMode = _thisMode;
  257. if (thisMode == FunctionThisMode.Lexical)
  258. {
  259. return;
  260. }
  261. var calleeRealm = _realm;
  262. var localEnv = (FunctionEnvironmentRecord) calleeContext.LexicalEnvironment;
  263. JsValue thisValue;
  264. if (_thisMode == FunctionThisMode.Strict)
  265. {
  266. thisValue = thisArgument;
  267. }
  268. else
  269. {
  270. if (thisArgument is null || thisArgument.IsNullOrUndefined())
  271. {
  272. var globalEnv = calleeRealm.GlobalEnv;
  273. thisValue = globalEnv.GlobalThisValue;
  274. }
  275. else
  276. {
  277. thisValue = TypeConverter.ToObject(calleeRealm, thisArgument);
  278. }
  279. }
  280. localEnv.BindThisValue(thisValue);
  281. }
  282. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  283. internal Completion OrdinaryCallEvaluateBody(
  284. EvaluationContext context,
  285. JsValue[] arguments,
  286. ExecutionContext calleeContext)
  287. {
  288. var argumentsInstance = _engine.FunctionDeclarationInstantiation(
  289. functionInstance: this,
  290. arguments);
  291. var result = _functionDefinition.Execute(context);
  292. argumentsInstance?.FunctionWasCalled();
  293. return result;
  294. }
  295. /// <summary>
  296. /// https://tc39.es/ecma262/#sec-prepareforordinarycall
  297. /// </summary>
  298. internal ExecutionContext PrepareForOrdinaryCall(JsValue newTarget)
  299. {
  300. var callerContext = _engine.ExecutionContext;
  301. var localEnv = JintEnvironment.NewFunctionEnvironment(_engine, this, newTarget);
  302. var calleeRealm = _realm;
  303. var calleeContext = new ExecutionContext(
  304. null,
  305. localEnv,
  306. localEnv,
  307. _privateEnvironment,
  308. calleeRealm,
  309. this);
  310. // If callerContext is not already suspended, suspend callerContext.
  311. // Push calleeContext onto the execution context stack; calleeContext is now the running execution context.
  312. // NOTE: Any exception objects produced after this point are associated with calleeRealm.
  313. // Return calleeContext.
  314. return _engine.EnterExecutionContext(calleeContext);
  315. }
  316. public override string ToString()
  317. {
  318. // TODO no way to extract SourceText from Esprima at the moment, just returning native code
  319. var nameValue = _nameDescriptor != null ? UnwrapJsValue(_nameDescriptor) : JsString.Empty;
  320. var name = "";
  321. if (!nameValue.IsUndefined())
  322. {
  323. name = TypeConverter.ToString(nameValue);
  324. }
  325. return "function " + name + "() { [native code] }";
  326. }
  327. }
  328. }