Function.cs 15 KB

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