Function.cs 15 KB

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