Function.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. using System.Diagnostics;
  2. using System.Runtime.CompilerServices;
  3. using Esprima.Ast;
  4. using Jint.Native.Object;
  5. using Jint.Native.Proxy;
  6. using Jint.Runtime;
  7. using Jint.Runtime.Descriptors;
  8. using Jint.Runtime.Environments;
  9. using Jint.Runtime.Interpreter;
  10. using Environment = Jint.Runtime.Environments.Environment;
  11. namespace Jint.Native.Function
  12. {
  13. [DebuggerDisplay("{ToString(),nq}")]
  14. #pragma warning disable MA0049
  15. public abstract partial class Function : ObjectInstance, ICallable
  16. #pragma warning restore MA0049
  17. {
  18. protected PropertyDescriptor? _prototypeDescriptor;
  19. protected internal PropertyDescriptor? _length;
  20. internal PropertyDescriptor? _nameDescriptor;
  21. internal Environment? _environment;
  22. internal readonly JintFunctionDefinition _functionDefinition = null!;
  23. internal readonly FunctionThisMode _thisMode;
  24. internal JsValue _homeObject = Undefined;
  25. internal ConstructorKind _constructorKind = ConstructorKind.Base;
  26. internal Realm _realm;
  27. internal PrivateEnvironment? _privateEnvironment;
  28. private readonly IScriptOrModule? _scriptOrModule;
  29. protected Function(
  30. Engine engine,
  31. Realm realm,
  32. JsString? name)
  33. : this(engine, realm, name, FunctionThisMode.Global)
  34. {
  35. }
  36. internal Function(
  37. Engine engine,
  38. Realm realm,
  39. JintFunctionDefinition function,
  40. Environment env,
  41. FunctionThisMode thisMode)
  42. : this(
  43. engine,
  44. realm,
  45. !string.IsNullOrWhiteSpace(function.Name) ? new JsString(function.Name!) : null,
  46. thisMode)
  47. {
  48. _functionDefinition = function;
  49. _environment = env;
  50. }
  51. internal Function(
  52. Engine engine,
  53. Realm realm,
  54. JsString? name,
  55. FunctionThisMode thisMode = FunctionThisMode.Global,
  56. ObjectClass objectClass = ObjectClass.Function)
  57. : base(engine, objectClass)
  58. {
  59. if (name is not null)
  60. {
  61. _nameDescriptor = new PropertyDescriptor(name, PropertyFlag.Configurable);
  62. }
  63. _realm = realm;
  64. _thisMode = thisMode;
  65. _scriptOrModule = _engine.GetActiveScriptOrModule();
  66. }
  67. // for example RavenDB wants to inspect this
  68. public IFunction FunctionDeclaration => _functionDefinition.Function;
  69. internal override bool IsCallable => true;
  70. JsValue ICallable.Call(JsValue thisObject, JsValue[] arguments) => Call(thisObject, arguments);
  71. /// <summary>
  72. /// Executed when a function object is used as a function
  73. /// </summary>
  74. protected internal abstract JsValue Call(JsValue thisObject, JsValue[] arguments);
  75. public bool Strict => _thisMode == FunctionThisMode.Strict;
  76. internal override bool IsConstructor => this is IConstructor;
  77. public override IEnumerable<KeyValuePair<JsValue, PropertyDescriptor>> GetOwnProperties()
  78. {
  79. if (_prototypeDescriptor != null)
  80. {
  81. yield return new KeyValuePair<JsValue, PropertyDescriptor>(CommonProperties.Prototype, _prototypeDescriptor);
  82. }
  83. if (_length != null)
  84. {
  85. yield return new KeyValuePair<JsValue, PropertyDescriptor>(CommonProperties.Length, _length);
  86. }
  87. if (_nameDescriptor != null)
  88. {
  89. yield return new KeyValuePair<JsValue, PropertyDescriptor>(CommonProperties.Name, GetOwnProperty(CommonProperties.Name));
  90. }
  91. foreach (var entry in base.GetOwnProperties())
  92. {
  93. yield return entry;
  94. }
  95. }
  96. internal sealed override IEnumerable<JsValue> GetInitialOwnStringPropertyKeys()
  97. {
  98. if (_length != null)
  99. {
  100. yield return CommonProperties.Length;
  101. }
  102. if (_nameDescriptor != null)
  103. {
  104. yield return CommonProperties.Name;
  105. }
  106. if (_prototypeDescriptor != null)
  107. {
  108. yield return CommonProperties.Prototype;
  109. }
  110. }
  111. public override PropertyDescriptor GetOwnProperty(JsValue property)
  112. {
  113. if (CommonProperties.Prototype.Equals(property))
  114. {
  115. return _prototypeDescriptor ?? PropertyDescriptor.Undefined;
  116. }
  117. if (CommonProperties.Length.Equals(property))
  118. {
  119. return _length ?? PropertyDescriptor.Undefined;
  120. }
  121. if (CommonProperties.Name.Equals(property))
  122. {
  123. return _nameDescriptor ?? PropertyDescriptor.Undefined;
  124. }
  125. return base.GetOwnProperty(property);
  126. }
  127. protected internal override void SetOwnProperty(JsValue property, PropertyDescriptor desc)
  128. {
  129. if (CommonProperties.Prototype.Equals(property))
  130. {
  131. _prototypeDescriptor = desc;
  132. }
  133. else if (CommonProperties.Length.Equals(property))
  134. {
  135. _length = desc;
  136. }
  137. else if (CommonProperties.Name.Equals(property))
  138. {
  139. _nameDescriptor = desc;
  140. }
  141. else
  142. {
  143. base.SetOwnProperty(property, desc);
  144. }
  145. }
  146. public override void RemoveOwnProperty(JsValue property)
  147. {
  148. if (CommonProperties.Prototype.Equals(property))
  149. {
  150. _prototypeDescriptor = null;
  151. }
  152. if (CommonProperties.Length.Equals(property))
  153. {
  154. _length = null;
  155. }
  156. if (CommonProperties.Name.Equals(property))
  157. {
  158. _nameDescriptor = null;
  159. }
  160. base.RemoveOwnProperty(property);
  161. }
  162. /// <summary>
  163. /// https://tc39.es/ecma262/#sec-setfunctionname
  164. /// </summary>
  165. internal void SetFunctionName(JsValue name, string? prefix = null, bool force = false)
  166. {
  167. if (!force && _nameDescriptor != null && UnwrapJsValue(_nameDescriptor) != JsString.Empty)
  168. {
  169. return;
  170. }
  171. if (name is JsSymbol symbol)
  172. {
  173. name = symbol._value.IsUndefined()
  174. ? JsString.Empty
  175. : new JsString("[" + symbol._value + "]");
  176. }
  177. else if (name is PrivateName privateName)
  178. {
  179. name = "#" + privateName.Description;
  180. }
  181. if (!string.IsNullOrWhiteSpace(prefix))
  182. {
  183. name = prefix + " " + name;
  184. }
  185. _nameDescriptor = new PropertyDescriptor(name, PropertyFlag.Configurable);
  186. }
  187. /// <summary>
  188. /// https://tc39.es/ecma262/#sec-ordinarycreatefromconstructor
  189. /// </summary>
  190. /// <remarks>
  191. /// Uses separate builder to get correct type with state support to prevent allocations.
  192. /// In spec intrinsicDefaultProto is string pointing to intrinsic, but we do a selector.
  193. /// </remarks>
  194. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  195. internal T OrdinaryCreateFromConstructor<T, TState>(
  196. JsValue constructor,
  197. Func<Intrinsics, ObjectInstance> intrinsicDefaultProto,
  198. Func<Engine, Realm, TState?, T> objectCreator,
  199. TState? state = default) where T : ObjectInstance
  200. {
  201. var proto = GetPrototypeFromConstructor(constructor, intrinsicDefaultProto);
  202. var obj = objectCreator(_engine, _realm, state);
  203. obj._prototype = proto;
  204. return obj;
  205. }
  206. /// <summary>
  207. /// https://tc39.es/ecma262/#sec-getprototypefromconstructor
  208. /// </summary>
  209. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  210. internal ObjectInstance GetPrototypeFromConstructor(JsValue constructor, Func<Intrinsics, ObjectInstance> intrinsicDefaultProto)
  211. {
  212. if (constructor.Get(CommonProperties.Prototype) is not ObjectInstance proto)
  213. {
  214. var realm = GetFunctionRealm(constructor);
  215. proto = intrinsicDefaultProto(realm.Intrinsics);
  216. }
  217. return proto;
  218. }
  219. /// <summary>
  220. /// https://tc39.es/ecma262/#sec-getfunctionrealm
  221. /// </summary>
  222. internal Realm GetFunctionRealm(JsValue obj)
  223. {
  224. if (obj is Function functionInstance && functionInstance._realm is not null)
  225. {
  226. return functionInstance._realm;
  227. }
  228. if (obj is BindFunction bindFunctionInstance)
  229. {
  230. return GetFunctionRealm(bindFunctionInstance.BoundTargetFunction);
  231. }
  232. if (obj is JsProxy proxyInstance)
  233. {
  234. if (proxyInstance._handler is null)
  235. {
  236. ExceptionHelper.ThrowTypeErrorNoEngine();
  237. }
  238. return GetFunctionRealm(proxyInstance._target);
  239. }
  240. return _engine.ExecutionContext.Realm;
  241. }
  242. /// <summary>
  243. /// https://tc39.es/ecma262/#sec-makemethod
  244. /// </summary>
  245. internal void MakeMethod(ObjectInstance homeObject)
  246. {
  247. _homeObject = homeObject;
  248. }
  249. /// <summary>
  250. /// https://tc39.es/ecma262/#sec-ordinarycallbindthis
  251. /// </summary>
  252. internal void OrdinaryCallBindThis(ExecutionContext calleeContext, JsValue thisArgument)
  253. {
  254. if (_thisMode == FunctionThisMode.Lexical)
  255. {
  256. return;
  257. }
  258. var calleeRealm = _realm;
  259. var localEnv = (FunctionEnvironment) calleeContext.LexicalEnvironment;
  260. JsValue thisValue;
  261. if (_thisMode == FunctionThisMode.Strict)
  262. {
  263. thisValue = thisArgument;
  264. }
  265. else
  266. {
  267. if (thisArgument is null || thisArgument.IsNullOrUndefined())
  268. {
  269. var globalEnv = calleeRealm.GlobalEnv;
  270. thisValue = globalEnv.GlobalThisValue;
  271. }
  272. else
  273. {
  274. thisValue = TypeConverter.ToObject(calleeRealm, thisArgument);
  275. }
  276. }
  277. localEnv.BindThisValue(thisValue);
  278. }
  279. /// <summary>
  280. /// https://tc39.es/ecma262/#sec-prepareforordinarycall
  281. /// </summary>
  282. internal ExecutionContext PrepareForOrdinaryCall(JsValue newTarget)
  283. {
  284. var callerContext = _engine.ExecutionContext;
  285. var localEnv = JintEnvironment.NewFunctionEnvironment(_engine, this, newTarget);
  286. var calleeRealm = _realm;
  287. var calleeContext = new ExecutionContext(
  288. _scriptOrModule,
  289. lexicalEnvironment: localEnv,
  290. variableEnvironment: localEnv,
  291. _privateEnvironment,
  292. calleeRealm,
  293. function: this);
  294. // If callerContext is not already suspended, suspend callerContext.
  295. // Push calleeContext onto the execution context stack; calleeContext is now the running execution context.
  296. // NOTE: Any exception objects produced after this point are associated with calleeRealm.
  297. // Return calleeContext.
  298. return _engine.EnterExecutionContext(calleeContext);
  299. }
  300. internal void MakeConstructor(bool writableProperty = true, ObjectInstance? prototype = null)
  301. {
  302. _constructorKind = ConstructorKind.Base;
  303. if (prototype is null)
  304. {
  305. prototype = new ObjectInstanceWithConstructor(_engine, this)
  306. {
  307. _prototype = _realm.Intrinsics.Object.PrototypeObject
  308. };
  309. }
  310. _prototypeDescriptor = new PropertyDescriptor(prototype, writableProperty, enumerable: false, configurable: false);
  311. }
  312. internal void SetFunctionLength(JsNumber length)
  313. {
  314. DefinePropertyOrThrow(CommonProperties.Length, new PropertyDescriptor(length, writable: false, enumerable: false, configurable: true));
  315. }
  316. // native syntax doesn't expect to have private identifier indicator
  317. private static readonly char[] _functionNameTrimStartChars = { '#' };
  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. name = name.TrimStart(_functionNameTrimStartChars);
  328. return "function " + name + "() { [native code] }";
  329. }
  330. private sealed class ObjectInstanceWithConstructor : ObjectInstance
  331. {
  332. private PropertyDescriptor? _constructor;
  333. public ObjectInstanceWithConstructor(Engine engine, ObjectInstance thisObj) : base(engine)
  334. {
  335. _constructor = new PropertyDescriptor(thisObj, PropertyFlag.NonEnumerable);
  336. }
  337. public override IEnumerable<KeyValuePair<JsValue, PropertyDescriptor>> GetOwnProperties()
  338. {
  339. if (_constructor != null)
  340. {
  341. yield return new KeyValuePair<JsValue, PropertyDescriptor>(CommonProperties.Constructor, _constructor);
  342. }
  343. foreach (var entry in base.GetOwnProperties())
  344. {
  345. yield return entry;
  346. }
  347. }
  348. public override PropertyDescriptor GetOwnProperty(JsValue property)
  349. {
  350. if (CommonProperties.Constructor.Equals(property))
  351. {
  352. return _constructor ?? PropertyDescriptor.Undefined;
  353. }
  354. return base.GetOwnProperty(property);
  355. }
  356. protected internal override void SetOwnProperty(JsValue property, PropertyDescriptor desc)
  357. {
  358. if (CommonProperties.Constructor.Equals(property))
  359. {
  360. _constructor = desc;
  361. }
  362. else
  363. {
  364. base.SetOwnProperty(property, desc);
  365. }
  366. }
  367. public override void RemoveOwnProperty(JsValue property)
  368. {
  369. if (CommonProperties.Constructor.Equals(property))
  370. {
  371. _constructor = null;
  372. }
  373. else
  374. {
  375. base.RemoveOwnProperty(property);
  376. }
  377. }
  378. }
  379. }
  380. }