FunctionInstance.cs 13 KB

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