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