FunctionInstance.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. internal 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 void RemoveOwnProperty(JsValue property)
  144. {
  145. if (property == CommonProperties.Prototype)
  146. {
  147. _prototypeDescriptor = null;
  148. }
  149. if (property == CommonProperties.Length)
  150. {
  151. _length = null;
  152. }
  153. if (property == CommonProperties.Name)
  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. if (!string.IsNullOrWhiteSpace(prefix))
  175. {
  176. name = prefix + " " + name;
  177. }
  178. _nameDescriptor = new PropertyDescriptor(name, PropertyFlag.Configurable);
  179. }
  180. /// <summary>
  181. /// https://tc39.es/ecma262/#sec-ordinarycreatefromconstructor
  182. /// </summary>
  183. /// <remarks>
  184. /// Uses separate builder to get correct type with state support to prevent allocations.
  185. /// In spec intrinsicDefaultProto is string pointing to intrinsic, but we do a selector.
  186. /// </remarks>
  187. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  188. internal T OrdinaryCreateFromConstructor<T, TState>(
  189. JsValue constructor,
  190. Func<Intrinsics, ObjectInstance> intrinsicDefaultProto,
  191. Func<Engine, Realm, TState, T> objectCreator,
  192. TState state = default) where T : ObjectInstance
  193. {
  194. var proto = GetPrototypeFromConstructor(constructor, intrinsicDefaultProto);
  195. var obj = objectCreator(_engine, _realm, state);
  196. obj._prototype = proto;
  197. return obj;
  198. }
  199. /// <summary>
  200. /// https://tc39.es/ecma262/#sec-getprototypefromconstructor
  201. /// </summary>
  202. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  203. internal ObjectInstance GetPrototypeFromConstructor(JsValue constructor, Func<Intrinsics, ObjectInstance> intrinsicDefaultProto)
  204. {
  205. var proto = constructor.Get(CommonProperties.Prototype, constructor) as ObjectInstance;
  206. if (proto is null)
  207. {
  208. var realm = GetFunctionRealm(constructor);
  209. proto = intrinsicDefaultProto(realm.Intrinsics);
  210. }
  211. return proto;
  212. }
  213. /// <summary>
  214. /// https://tc39.es/ecma262/#sec-getfunctionrealm
  215. /// </summary>
  216. internal Realm GetFunctionRealm(JsValue obj)
  217. {
  218. if (obj is FunctionInstance functionInstance && functionInstance._realm is not null)
  219. {
  220. return functionInstance._realm;
  221. }
  222. if (obj is BindFunctionInstance bindFunctionInstance)
  223. {
  224. return GetFunctionRealm(bindFunctionInstance.BoundTargetFunction);
  225. }
  226. if (obj is ProxyInstance proxyInstance)
  227. {
  228. if (proxyInstance._handler is null)
  229. {
  230. ExceptionHelper.ThrowTypeErrorNoEngine();
  231. }
  232. return GetFunctionRealm(proxyInstance._target);
  233. }
  234. return _engine.ExecutionContext.Realm;
  235. }
  236. /// <summary>
  237. /// https://tc39.es/ecma262/#sec-makemethod
  238. /// </summary>
  239. internal void MakeMethod(ObjectInstance homeObject)
  240. {
  241. _homeObject = homeObject;
  242. }
  243. /// <summary>
  244. /// https://tc39.es/ecma262/#sec-ordinaryobjectcreate
  245. /// </summary>
  246. internal ObjectInstance OrdinaryObjectCreate(ObjectInstance proto)
  247. {
  248. var prototype = new ObjectInstance(_engine)
  249. {
  250. _prototype = proto
  251. };
  252. return prototype;
  253. }
  254. /// <summary>
  255. /// https://tc39.es/ecma262/#sec-ordinarycallbindthis
  256. /// </summary>
  257. internal void OrdinaryCallBindThis(ExecutionContext calleeContext, JsValue thisArgument)
  258. {
  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. /// <summary>
  285. /// https://tc39.es/ecma262/#sec-ordinarycallevaluatebody
  286. /// </summary>
  287. internal Completion OrdinaryCallEvaluateBody(EvaluationContext context, JsValue[] arguments)
  288. {
  289. return _functionDefinition.EvaluateBody(context, this, arguments);
  290. }
  291. /// <summary>
  292. /// https://tc39.es/ecma262/#sec-prepareforordinarycall
  293. /// </summary>
  294. internal ExecutionContext PrepareForOrdinaryCall(JsValue newTarget)
  295. {
  296. var callerContext = _engine.ExecutionContext;
  297. var localEnv = JintEnvironment.NewFunctionEnvironment(_engine, this, newTarget);
  298. var calleeRealm = _realm;
  299. var calleeContext = new ExecutionContext(
  300. _scriptOrModule,
  301. lexicalEnvironment: localEnv,
  302. variableEnvironment: localEnv,
  303. _privateEnvironment,
  304. calleeRealm,
  305. function: this);
  306. // If callerContext is not already suspended, suspend callerContext.
  307. // Push calleeContext onto the execution context stack; calleeContext is now the running execution context.
  308. // NOTE: Any exception objects produced after this point are associated with calleeRealm.
  309. // Return calleeContext.
  310. return _engine.EnterExecutionContext(calleeContext);
  311. }
  312. internal void MakeConstructor(bool writableProperty = true, ObjectInstance prototype = null)
  313. {
  314. _constructorKind = ConstructorKind.Base;
  315. if (prototype is null)
  316. {
  317. prototype = new ObjectInstanceWithConstructor(_engine, this)
  318. {
  319. _prototype = _realm.Intrinsics.Object.PrototypeObject
  320. };
  321. }
  322. _prototypeDescriptor = new PropertyDescriptor(prototype, writableProperty, enumerable: false, configurable: false);
  323. }
  324. internal void SetFunctionLength(JsNumber length)
  325. {
  326. DefinePropertyOrThrow(CommonProperties.Length, new PropertyDescriptor(length, writable: false, enumerable: false, configurable: true));
  327. }
  328. public override string ToString()
  329. {
  330. // TODO no way to extract SourceText from Esprima at the moment, just returning native code
  331. var nameValue = _nameDescriptor != null ? UnwrapJsValue(_nameDescriptor) : JsString.Empty;
  332. var name = "";
  333. if (!nameValue.IsUndefined())
  334. {
  335. name = TypeConverter.ToString(nameValue);
  336. }
  337. return "function " + name + "() { [native code] }";
  338. }
  339. private sealed class ObjectInstanceWithConstructor : ObjectInstance
  340. {
  341. private PropertyDescriptor _constructor;
  342. public ObjectInstanceWithConstructor(Engine engine, ObjectInstance thisObj) : base(engine)
  343. {
  344. _constructor = new PropertyDescriptor(thisObj, PropertyFlag.NonEnumerable);
  345. }
  346. public override IEnumerable<KeyValuePair<JsValue, PropertyDescriptor>> GetOwnProperties()
  347. {
  348. if (_constructor != null)
  349. {
  350. yield return new KeyValuePair<JsValue, PropertyDescriptor>(CommonProperties.Constructor, _constructor);
  351. }
  352. foreach (var entry in base.GetOwnProperties())
  353. {
  354. yield return entry;
  355. }
  356. }
  357. public override PropertyDescriptor GetOwnProperty(JsValue property)
  358. {
  359. if (property == CommonProperties.Constructor)
  360. {
  361. return _constructor ?? PropertyDescriptor.Undefined;
  362. }
  363. return base.GetOwnProperty(property);
  364. }
  365. protected internal override void SetOwnProperty(JsValue property, PropertyDescriptor desc)
  366. {
  367. if (property == CommonProperties.Constructor)
  368. {
  369. _constructor = desc;
  370. }
  371. else
  372. {
  373. base.SetOwnProperty(property, desc);
  374. }
  375. }
  376. public override void RemoveOwnProperty(JsValue property)
  377. {
  378. if (property == CommonProperties.Constructor)
  379. {
  380. _constructor = null;
  381. }
  382. else
  383. {
  384. base.RemoveOwnProperty(property);
  385. }
  386. }
  387. }
  388. }
  389. }