FunctionInstance.cs 16 KB

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