FunctionInstance.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. using System.Runtime.CompilerServices;
  2. using Esprima.Ast;
  3. using Jint.Native.Object;
  4. using Jint.Native.Proxy;
  5. using Jint.Runtime;
  6. using Jint.Runtime.Descriptors;
  7. using Jint.Runtime.Environments;
  8. using Jint.Runtime.Interpreter;
  9. namespace Jint.Native.Function
  10. {
  11. public abstract class FunctionInstance : ObjectInstance, ICallable
  12. {
  13. protected PropertyDescriptor? _prototypeDescriptor;
  14. protected internal PropertyDescriptor? _length;
  15. internal PropertyDescriptor? _nameDescriptor;
  16. protected internal EnvironmentRecord? _environment;
  17. internal readonly JintFunctionDefinition _functionDefinition = null!;
  18. internal readonly FunctionThisMode _thisMode;
  19. internal JsValue _homeObject = Undefined;
  20. internal ConstructorKind _constructorKind = ConstructorKind.Base;
  21. internal Realm _realm;
  22. internal PrivateEnvironmentRecord? _privateEnvironment;
  23. private readonly IScriptOrModule? _scriptOrModule;
  24. protected FunctionInstance(
  25. Engine engine,
  26. Realm realm,
  27. JsString? name)
  28. : this(engine, realm, name, FunctionThisMode.Global)
  29. {
  30. }
  31. internal FunctionInstance(
  32. Engine engine,
  33. Realm realm,
  34. JintFunctionDefinition function,
  35. EnvironmentRecord scope,
  36. FunctionThisMode thisMode)
  37. : this(
  38. engine,
  39. realm,
  40. !string.IsNullOrWhiteSpace(function.Name) ? new JsString(function.Name!) : null,
  41. thisMode)
  42. {
  43. _functionDefinition = function;
  44. _environment = scope;
  45. }
  46. internal FunctionInstance(
  47. Engine engine,
  48. Realm realm,
  49. JsString? name,
  50. FunctionThisMode thisMode = FunctionThisMode.Global,
  51. ObjectClass objectClass = ObjectClass.Function)
  52. : base(engine, objectClass)
  53. {
  54. if (name is not null)
  55. {
  56. _nameDescriptor = new PropertyDescriptor(name, PropertyFlag.Configurable);
  57. }
  58. _realm = realm;
  59. _thisMode = thisMode;
  60. _scriptOrModule = _engine.GetActiveScriptOrModule();
  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 void RemoveOwnProperty(JsValue property)
  142. {
  143. if (property == CommonProperties.Prototype)
  144. {
  145. _prototypeDescriptor = null;
  146. }
  147. if (property == CommonProperties.Length)
  148. {
  149. _length = null;
  150. }
  151. if (property == CommonProperties.Name)
  152. {
  153. _nameDescriptor = null;
  154. }
  155. base.RemoveOwnProperty(property);
  156. }
  157. /// <summary>
  158. /// https://tc39.es/ecma262/#sec-setfunctionname
  159. /// </summary>
  160. internal void SetFunctionName(JsValue name, string? prefix = null, bool force = false)
  161. {
  162. if (!force && _nameDescriptor != null && UnwrapJsValue(_nameDescriptor) != JsString.Empty)
  163. {
  164. return;
  165. }
  166. if (name is JsSymbol symbol)
  167. {
  168. name = symbol._value.IsUndefined()
  169. ? JsString.Empty
  170. : new JsString("[" + symbol._value + "]");
  171. }
  172. if (!string.IsNullOrWhiteSpace(prefix))
  173. {
  174. name = prefix + " " + name;
  175. }
  176. _nameDescriptor = new PropertyDescriptor(name, PropertyFlag.Configurable);
  177. }
  178. /// <summary>
  179. /// https://tc39.es/ecma262/#sec-ordinarycreatefromconstructor
  180. /// </summary>
  181. /// <remarks>
  182. /// Uses separate builder to get correct type with state support to prevent allocations.
  183. /// In spec intrinsicDefaultProto is string pointing to intrinsic, but we do a selector.
  184. /// </remarks>
  185. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  186. internal T OrdinaryCreateFromConstructor<T, TState>(
  187. JsValue constructor,
  188. Func<Intrinsics, ObjectInstance> intrinsicDefaultProto,
  189. Func<Engine, Realm, TState?, T> objectCreator,
  190. TState? state = default) where T : ObjectInstance
  191. {
  192. var proto = GetPrototypeFromConstructor(constructor, intrinsicDefaultProto);
  193. var obj = objectCreator(_engine, _realm, state);
  194. obj._prototype = proto;
  195. return obj;
  196. }
  197. /// <summary>
  198. /// https://tc39.es/ecma262/#sec-getprototypefromconstructor
  199. /// </summary>
  200. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  201. internal ObjectInstance GetPrototypeFromConstructor(JsValue constructor, Func<Intrinsics, ObjectInstance> intrinsicDefaultProto)
  202. {
  203. if (constructor.Get(CommonProperties.Prototype, constructor) is not ObjectInstance proto)
  204. {
  205. var realm = GetFunctionRealm(constructor);
  206. proto = intrinsicDefaultProto(realm.Intrinsics);
  207. }
  208. return proto;
  209. }
  210. /// <summary>
  211. /// https://tc39.es/ecma262/#sec-getfunctionrealm
  212. /// </summary>
  213. internal Realm GetFunctionRealm(JsValue obj)
  214. {
  215. if (obj is FunctionInstance functionInstance && functionInstance._realm is not null)
  216. {
  217. return functionInstance._realm;
  218. }
  219. if (obj is BindFunctionInstance bindFunctionInstance)
  220. {
  221. return GetFunctionRealm(bindFunctionInstance.BoundTargetFunction);
  222. }
  223. if (obj is ProxyInstance proxyInstance)
  224. {
  225. if (proxyInstance._handler is null)
  226. {
  227. ExceptionHelper.ThrowTypeErrorNoEngine();
  228. }
  229. return GetFunctionRealm(proxyInstance._target);
  230. }
  231. return _engine.ExecutionContext.Realm;
  232. }
  233. /// <summary>
  234. /// https://tc39.es/ecma262/#sec-makemethod
  235. /// </summary>
  236. internal void MakeMethod(ObjectInstance homeObject)
  237. {
  238. _homeObject = homeObject;
  239. }
  240. /// <summary>
  241. /// https://tc39.es/ecma262/#sec-ordinaryobjectcreate
  242. /// </summary>
  243. internal ObjectInstance OrdinaryObjectCreate(ObjectInstance proto)
  244. {
  245. var prototype = new ObjectInstance(_engine)
  246. {
  247. _prototype = proto
  248. };
  249. return prototype;
  250. }
  251. /// <summary>
  252. /// https://tc39.es/ecma262/#sec-ordinarycallbindthis
  253. /// </summary>
  254. internal void OrdinaryCallBindThis(ExecutionContext calleeContext, JsValue thisArgument)
  255. {
  256. if (_thisMode == FunctionThisMode.Lexical)
  257. {
  258. return;
  259. }
  260. var calleeRealm = _realm;
  261. var localEnv = (FunctionEnvironmentRecord) calleeContext.LexicalEnvironment;
  262. JsValue thisValue;
  263. if (_thisMode == FunctionThisMode.Strict)
  264. {
  265. thisValue = thisArgument;
  266. }
  267. else
  268. {
  269. if (thisArgument is null || thisArgument.IsNullOrUndefined())
  270. {
  271. var globalEnv = calleeRealm.GlobalEnv;
  272. thisValue = globalEnv.GlobalThisValue;
  273. }
  274. else
  275. {
  276. thisValue = TypeConverter.ToObject(calleeRealm, thisArgument);
  277. }
  278. }
  279. localEnv.BindThisValue(thisValue);
  280. }
  281. /// <summary>
  282. /// https://tc39.es/ecma262/#sec-prepareforordinarycall
  283. /// </summary>
  284. internal ExecutionContext PrepareForOrdinaryCall(JsValue newTarget)
  285. {
  286. var callerContext = _engine.ExecutionContext;
  287. var localEnv = JintEnvironment.NewFunctionEnvironment(_engine, this, newTarget);
  288. var calleeRealm = _realm;
  289. var calleeContext = new ExecutionContext(
  290. _scriptOrModule,
  291. lexicalEnvironment: localEnv,
  292. variableEnvironment: localEnv,
  293. _privateEnvironment,
  294. calleeRealm,
  295. function: this);
  296. // If callerContext is not already suspended, suspend callerContext.
  297. // Push calleeContext onto the execution context stack; calleeContext is now the running execution context.
  298. // NOTE: Any exception objects produced after this point are associated with calleeRealm.
  299. // Return calleeContext.
  300. return _engine.EnterExecutionContext(calleeContext);
  301. }
  302. internal void MakeConstructor(bool writableProperty = true, ObjectInstance? prototype = null)
  303. {
  304. _constructorKind = ConstructorKind.Base;
  305. if (prototype is null)
  306. {
  307. prototype = new ObjectInstanceWithConstructor(_engine, this)
  308. {
  309. _prototype = _realm.Intrinsics.Object.PrototypeObject
  310. };
  311. }
  312. _prototypeDescriptor = new PropertyDescriptor(prototype, writableProperty, enumerable: false, configurable: false);
  313. }
  314. internal void SetFunctionLength(JsNumber length)
  315. {
  316. DefinePropertyOrThrow(CommonProperties.Length, new PropertyDescriptor(length, writable: false, enumerable: false, configurable: true));
  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. private sealed class ObjectInstanceWithConstructor : ObjectInstance
  330. {
  331. private PropertyDescriptor? _constructor;
  332. public ObjectInstanceWithConstructor(Engine engine, ObjectInstance thisObj) : base(engine)
  333. {
  334. _constructor = new PropertyDescriptor(thisObj, PropertyFlag.NonEnumerable);
  335. }
  336. public override IEnumerable<KeyValuePair<JsValue, PropertyDescriptor>> GetOwnProperties()
  337. {
  338. if (_constructor != null)
  339. {
  340. yield return new KeyValuePair<JsValue, PropertyDescriptor>(CommonProperties.Constructor, _constructor);
  341. }
  342. foreach (var entry in base.GetOwnProperties())
  343. {
  344. yield return entry;
  345. }
  346. }
  347. public override PropertyDescriptor GetOwnProperty(JsValue property)
  348. {
  349. if (property == CommonProperties.Constructor)
  350. {
  351. return _constructor ?? PropertyDescriptor.Undefined;
  352. }
  353. return base.GetOwnProperty(property);
  354. }
  355. protected internal override void SetOwnProperty(JsValue property, PropertyDescriptor desc)
  356. {
  357. if (property == CommonProperties.Constructor)
  358. {
  359. _constructor = desc;
  360. }
  361. else
  362. {
  363. base.SetOwnProperty(property, desc);
  364. }
  365. }
  366. public override void RemoveOwnProperty(JsValue property)
  367. {
  368. if (property == CommonProperties.Constructor)
  369. {
  370. _constructor = null;
  371. }
  372. else
  373. {
  374. base.RemoveOwnProperty(property);
  375. }
  376. }
  377. }
  378. }
  379. }