FunctionEnvironment.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. using System.Runtime.CompilerServices;
  2. using Jint.Collections;
  3. using Jint.Native;
  4. using Jint.Native.Function;
  5. using Jint.Native.Iterator;
  6. using Jint.Native.Object;
  7. using Jint.Runtime.Interpreter;
  8. using Jint.Runtime.Interpreter.Expressions;
  9. namespace Jint.Runtime.Environments;
  10. /// <summary>
  11. /// https://tc39.es/ecma262/#sec-function-environment-records
  12. /// </summary>
  13. internal sealed class FunctionEnvironment : DeclarativeEnvironment
  14. {
  15. private enum ThisBindingStatus
  16. {
  17. Lexical,
  18. Initialized,
  19. Uninitialized
  20. }
  21. private JsValue? _thisValue;
  22. private ThisBindingStatus _thisBindingStatus;
  23. internal readonly Function _functionObject;
  24. public FunctionEnvironment(
  25. Engine engine,
  26. Function functionObject,
  27. JsValue newTarget) : base(engine)
  28. {
  29. _functionObject = functionObject;
  30. NewTarget = newTarget;
  31. if (functionObject._functionDefinition?.Function.Type is NodeType.ArrowFunctionExpression)
  32. {
  33. _thisBindingStatus = ThisBindingStatus.Lexical;
  34. }
  35. else
  36. {
  37. _thisBindingStatus = ThisBindingStatus.Uninitialized;
  38. }
  39. }
  40. internal override bool HasThisBinding() => _thisBindingStatus != ThisBindingStatus.Lexical;
  41. internal override bool HasSuperBinding() =>
  42. _thisBindingStatus != ThisBindingStatus.Lexical && !_functionObject._homeObject.IsUndefined();
  43. public JsValue BindThisValue(JsValue value)
  44. {
  45. if (_thisBindingStatus != ThisBindingStatus.Initialized)
  46. {
  47. _thisValue = value;
  48. _thisBindingStatus = ThisBindingStatus.Initialized;
  49. return value;
  50. }
  51. Throw.ReferenceError(_functionObject._realm, "'this' has already been bound");
  52. return null!;
  53. }
  54. internal override JsValue GetThisBinding()
  55. {
  56. if (_thisBindingStatus != ThisBindingStatus.Uninitialized)
  57. {
  58. return _thisValue!;
  59. }
  60. ThrowUninitializedThis();
  61. return null!;
  62. }
  63. [MethodImpl(MethodImplOptions.NoInlining)]
  64. private void ThrowUninitializedThis()
  65. {
  66. var message = "Cannot access uninitialized 'this'";
  67. if (NewTarget is ScriptFunction { _isClassConstructor: true, _constructorKind: ConstructorKind.Derived })
  68. {
  69. // help with better error message
  70. message = "Must call super constructor in derived class before accessing 'this' or returning from derived constructor";
  71. }
  72. Throw.ReferenceError(_engine.ExecutionContext.Realm, message);
  73. }
  74. public JsValue GetSuperBase()
  75. {
  76. var home = _functionObject._homeObject;
  77. return home.IsUndefined()
  78. ? Undefined
  79. : ((ObjectInstance) home).GetPrototypeOf() ?? Null;
  80. }
  81. // optimization to have logic near record internal structures.
  82. internal void InitializeParameters(
  83. Key[] parameterNames,
  84. bool hasDuplicates,
  85. JsCallArguments? arguments)
  86. {
  87. if (parameterNames.Length == 0)
  88. {
  89. return;
  90. }
  91. var value = hasDuplicates ? Undefined : null;
  92. var directSet = !hasDuplicates && (_dictionary is null || _dictionary.Count == 0);
  93. _dictionary ??= new HybridDictionary<Binding>(parameterNames.Length, checkExistingKeys: !directSet);
  94. for (uint i = 0; i < (uint) parameterNames.Length; i++)
  95. {
  96. var paramName = parameterNames[i];
  97. ref var binding = ref _dictionary.GetValueRefOrAddDefault(paramName, out var exists);
  98. if (directSet || !exists)
  99. {
  100. var parameterValue = arguments?.At((int) i, Undefined) ?? value;
  101. binding = new Binding(parameterValue!, canBeDeleted: false, mutable: true, strict: false);
  102. }
  103. }
  104. _dictionary.CheckExistingKeys = true;
  105. }
  106. internal void AddFunctionParameters(EvaluationContext context, IFunction functionDeclaration, JsCallArguments arguments)
  107. {
  108. var empty = _dictionary is null || _dictionary.Count == 0;
  109. ref readonly var parameters = ref functionDeclaration.Params;
  110. var count = parameters.Count;
  111. for (var i = 0; i < count; i++)
  112. {
  113. SetFunctionParameter(context, parameters[i], arguments, i, empty);
  114. }
  115. }
  116. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  117. private void SetFunctionParameter(
  118. EvaluationContext context,
  119. Node? parameter,
  120. JsCallArguments arguments,
  121. int index,
  122. bool initiallyEmpty)
  123. {
  124. if (parameter is Identifier identifier)
  125. {
  126. var argument = arguments.At(index);
  127. SetItemSafely(identifier.Name, argument, initiallyEmpty);
  128. }
  129. else
  130. {
  131. SetFunctionParameterUnlikely(context, parameter, arguments, index, initiallyEmpty);
  132. }
  133. }
  134. private void SetFunctionParameterUnlikely(
  135. EvaluationContext context,
  136. Node? parameter,
  137. JsCallArguments arguments,
  138. int index,
  139. bool initiallyEmpty)
  140. {
  141. var argument = arguments.At(index);
  142. if (parameter is RestElement restElement)
  143. {
  144. HandleRestElementArray(context, restElement, arguments, index, initiallyEmpty);
  145. }
  146. else if (parameter is ArrayPattern arrayPattern)
  147. {
  148. HandleArrayPattern(context, initiallyEmpty, argument, arrayPattern);
  149. }
  150. else if (parameter is ObjectPattern objectPattern)
  151. {
  152. HandleObjectPattern(context, initiallyEmpty, argument, objectPattern);
  153. }
  154. else if (parameter is AssignmentPattern assignmentPattern)
  155. {
  156. HandleAssignmentPatternOrExpression(context, assignmentPattern.Left, assignmentPattern.Right, argument, initiallyEmpty);
  157. }
  158. else if (parameter is AssignmentExpression assignmentExpression)
  159. {
  160. HandleAssignmentPatternOrExpression(context, assignmentExpression.Left, assignmentExpression.Right, argument, initiallyEmpty);
  161. }
  162. }
  163. private void HandleObjectPattern(EvaluationContext context, bool initiallyEmpty, JsValue argument, ObjectPattern objectPattern)
  164. {
  165. if (argument.IsNullOrUndefined())
  166. {
  167. Throw.TypeError(_functionObject._realm, "Destructed parameter is null or undefined");
  168. }
  169. var argumentObject = TypeConverter.ToObject(_engine.Realm, argument);
  170. ref readonly var properties = ref objectPattern.Properties;
  171. var processedProperties = properties.Count > 0 && properties[properties.Count - 1] is RestElement
  172. ? new HashSet<JsValue>()
  173. : null;
  174. var jsValues = _engine._jsValueArrayPool.RentArray(1);
  175. foreach (var property in properties)
  176. {
  177. var oldEnv = _engine.ExecutionContext.LexicalEnvironment;
  178. var paramVarEnv = JintEnvironment.NewDeclarativeEnvironment(_engine, oldEnv);
  179. PrivateEnvironment? privateEnvironment = null; // TODO PRIVATE check when implemented
  180. _engine.EnterExecutionContext(paramVarEnv, paramVarEnv, _engine.ExecutionContext.Realm, privateEnvironment);
  181. try
  182. {
  183. if (property is AssignmentProperty p)
  184. {
  185. var propertyName = p.GetKey(_engine);
  186. processedProperties?.Add(propertyName.ToString());
  187. jsValues[0] = argumentObject.Get(propertyName);
  188. SetFunctionParameter(context, p.Value, jsValues, 0, initiallyEmpty);
  189. }
  190. else
  191. {
  192. if (((RestElement) property).Argument is Identifier restIdentifier)
  193. {
  194. var rest = _engine.Realm.Intrinsics.Object.Construct((argumentObject.Properties?.Count ?? 0) - processedProperties!.Count);
  195. argumentObject.CopyDataProperties(rest, processedProperties);
  196. SetItemSafely(restIdentifier.Name, rest, initiallyEmpty);
  197. }
  198. else
  199. {
  200. Throw.SyntaxError(_functionObject._realm, "Object rest parameter can only be objects");
  201. }
  202. }
  203. }
  204. finally
  205. {
  206. _engine.LeaveExecutionContext();
  207. }
  208. }
  209. _engine._jsValueArrayPool.ReturnArray(jsValues);
  210. }
  211. private void HandleArrayPattern(EvaluationContext context, bool initiallyEmpty, JsValue argument, ArrayPattern arrayPattern)
  212. {
  213. if (argument.IsNull())
  214. {
  215. Throw.TypeError(_functionObject._realm, "Destructed parameter is null");
  216. }
  217. JsArray? array;
  218. if (argument is JsArray { HasOriginalIterator: true } ai)
  219. {
  220. array = ai;
  221. }
  222. else
  223. {
  224. if (!argument.TryGetIterator(_functionObject._realm, out var iterator))
  225. {
  226. Throw.TypeError(context.Engine.Realm, "object is not iterable");
  227. }
  228. array = _engine.Realm.Intrinsics.Array.ArrayCreate(0);
  229. var max = arrayPattern.Elements.Count;
  230. if (max > 0 && arrayPattern.Elements[max - 1]?.Type == NodeType.RestElement)
  231. {
  232. // need to consume all
  233. max = int.MaxValue;
  234. }
  235. var protocol = new ArrayPatternProtocol(_engine, array, iterator, max);
  236. protocol.Execute();
  237. }
  238. var arrayContents = array.ToArray();
  239. for (var i = 0; i < arrayPattern.Elements.Count; i++)
  240. {
  241. SetFunctionParameter(context, arrayPattern.Elements[i], arrayContents, i, initiallyEmpty);
  242. }
  243. }
  244. private void HandleRestElementArray(
  245. EvaluationContext context,
  246. RestElement restElement,
  247. JsCallArguments arguments,
  248. int index,
  249. bool initiallyEmpty)
  250. {
  251. // index + 1 == parameters.count because rest is last
  252. int restCount = arguments.Length - (index + 1) + 1;
  253. uint count = restCount > 0 ? (uint) restCount : 0;
  254. uint targetIndex = 0;
  255. var rest = new JsValue[count];
  256. for (var argIndex = index; argIndex < arguments.Length; ++argIndex)
  257. {
  258. rest[targetIndex++] = arguments[argIndex];
  259. }
  260. var array = new JsArray(_engine, rest);
  261. if (restElement.Argument is Identifier restIdentifier)
  262. {
  263. SetItemSafely(restIdentifier.Name, array, initiallyEmpty);
  264. }
  265. else if (restElement.Argument is DestructuringPattern pattern)
  266. {
  267. SetFunctionParameter(context, pattern, [array], 0, initiallyEmpty);
  268. }
  269. else
  270. {
  271. Throw.SyntaxError(_functionObject._realm, "Rest parameters can only be identifiers or arrays");
  272. }
  273. }
  274. private void HandleAssignmentPatternOrExpression(
  275. EvaluationContext context,
  276. Node left,
  277. Node right,
  278. JsValue argument,
  279. bool initiallyEmpty)
  280. {
  281. var idLeft = left as Identifier;
  282. if (idLeft != null
  283. && right is Identifier idRight
  284. && string.Equals(idLeft.Name, idRight.Name, StringComparison.Ordinal))
  285. {
  286. Throw.ReferenceNameError(_functionObject._realm, idRight.Name);
  287. }
  288. if (argument.IsUndefined())
  289. {
  290. var expression = (Expression) right;
  291. var jintExpression = JintExpression.Build(expression);
  292. var oldEnv = _engine.ExecutionContext.LexicalEnvironment;
  293. var paramVarEnv = JintEnvironment.NewDeclarativeEnvironment(_engine, oldEnv);
  294. _engine.EnterExecutionContext(new ExecutionContext(null, paramVarEnv, paramVarEnv, null, _engine.Realm, null));
  295. try
  296. {
  297. argument = jintExpression.GetValue(context);
  298. }
  299. finally
  300. {
  301. _engine.LeaveExecutionContext();
  302. }
  303. if (idLeft != null && right.IsFunctionDefinition())
  304. {
  305. ((Function) argument).SetFunctionName(idLeft.Name);
  306. }
  307. }
  308. SetFunctionParameter(context, left, [argument], 0, initiallyEmpty);
  309. }
  310. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  311. private void SetItemSafely(Key name, JsValue argument, bool initiallyEmpty)
  312. {
  313. if (initiallyEmpty)
  314. {
  315. _dictionary ??= new HybridDictionary<Binding>();
  316. _dictionary[name] = new Binding(argument, canBeDeleted: false, mutable: true, strict: false);
  317. }
  318. else
  319. {
  320. SetItemCheckExisting(name, argument);
  321. }
  322. }
  323. private void SetItemCheckExisting(Key name, JsValue argument)
  324. {
  325. _dictionary ??= new HybridDictionary<Binding>();
  326. if (!_dictionary.TryGetValue(name, out var existing))
  327. {
  328. _dictionary[name] = new Binding(argument, canBeDeleted: false, mutable: true, strict: false);
  329. }
  330. else
  331. {
  332. if (existing.Mutable)
  333. {
  334. _dictionary[name] = existing.ChangeValue(argument);
  335. }
  336. else
  337. {
  338. Throw.TypeError(_functionObject._realm, "Can't update the value of an immutable binding.");
  339. }
  340. }
  341. }
  342. private sealed class ArrayPatternProtocol : IteratorProtocol
  343. {
  344. private readonly JsArray _instance;
  345. private readonly int _max;
  346. private long _index;
  347. public ArrayPatternProtocol(
  348. Engine engine,
  349. JsArray instance,
  350. IteratorInstance iterator,
  351. int max) : base(engine, iterator, 0)
  352. {
  353. _instance = instance;
  354. _max = max;
  355. }
  356. protected override void ProcessItem(JsValue[] arguments, JsValue currentValue)
  357. {
  358. _instance.SetIndexValue((uint) _index, currentValue, updateLength: false);
  359. _index++;
  360. }
  361. protected override bool ShouldContinue => _index < _max;
  362. protected override void IterationEnd()
  363. {
  364. if (_index > 0)
  365. {
  366. _instance.SetLength((uint) _index);
  367. IteratorClose(CompletionType.Normal);
  368. }
  369. }
  370. }
  371. }