FunctionEnvironment.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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 is 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. ExceptionHelper.ThrowReferenceError(_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. ExceptionHelper.ThrowReferenceError(_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. JsValue[]? 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. for (uint i = 0; i < (uint) parameterNames.Length; i++)
  94. {
  95. var paramName = parameterNames[i];
  96. if (directSet || _dictionary is null || !_dictionary.ContainsKey(paramName))
  97. {
  98. var parameterValue = value;
  99. if (arguments != null)
  100. {
  101. parameterValue = i < (uint) arguments.Length ? arguments[i] : Undefined;
  102. }
  103. _dictionary ??= new HybridDictionary<Binding>();
  104. _dictionary[paramName] = new Binding(parameterValue!, canBeDeleted: false, mutable: true, strict: false);
  105. }
  106. }
  107. }
  108. internal void AddFunctionParameters(EvaluationContext context, IFunction functionDeclaration, JsValue[] arguments)
  109. {
  110. var empty = _dictionary is null || _dictionary.Count == 0;
  111. ref readonly var parameters = ref functionDeclaration.Params;
  112. var count = parameters.Count;
  113. for (var i = 0; i < count; i++)
  114. {
  115. SetFunctionParameter(context, parameters[i], arguments, i, empty);
  116. }
  117. }
  118. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  119. private void SetFunctionParameter(
  120. EvaluationContext context,
  121. Node? parameter,
  122. JsValue[] arguments,
  123. int index,
  124. bool initiallyEmpty)
  125. {
  126. if (parameter is Identifier identifier)
  127. {
  128. var argument = arguments.At(index);
  129. SetItemSafely(identifier.Name, argument, initiallyEmpty);
  130. }
  131. else
  132. {
  133. SetFunctionParameterUnlikely(context, parameter, arguments, index, initiallyEmpty);
  134. }
  135. }
  136. private void SetFunctionParameterUnlikely(
  137. EvaluationContext context,
  138. Node? parameter,
  139. JsValue[] arguments,
  140. int index,
  141. bool initiallyEmpty)
  142. {
  143. var argument = arguments.At(index);
  144. if (parameter is RestElement restElement)
  145. {
  146. HandleRestElementArray(context, restElement, arguments, index, initiallyEmpty);
  147. }
  148. else if (parameter is ArrayPattern arrayPattern)
  149. {
  150. HandleArrayPattern(context, initiallyEmpty, argument, arrayPattern);
  151. }
  152. else if (parameter is ObjectPattern objectPattern)
  153. {
  154. HandleObjectPattern(context, initiallyEmpty, argument, objectPattern);
  155. }
  156. else if (parameter is AssignmentPattern assignmentPattern)
  157. {
  158. HandleAssignmentPatternOrExpression(context, assignmentPattern.Left, assignmentPattern.Right, argument, initiallyEmpty);
  159. }
  160. else if (parameter is AssignmentExpression assignmentExpression)
  161. {
  162. HandleAssignmentPatternOrExpression(context, assignmentExpression.Left, assignmentExpression.Right, argument, initiallyEmpty);
  163. }
  164. }
  165. private void HandleObjectPattern(EvaluationContext context, bool initiallyEmpty, JsValue argument, ObjectPattern objectPattern)
  166. {
  167. if (argument.IsNullOrUndefined())
  168. {
  169. ExceptionHelper.ThrowTypeError(_functionObject._realm, "Destructed parameter is null or undefined");
  170. }
  171. var argumentObject = TypeConverter.ToObject(_engine.Realm , argument);
  172. ref readonly var properties = ref objectPattern.Properties;
  173. var processedProperties = properties.Count > 0 && properties[properties.Count - 1] is RestElement
  174. ? new HashSet<JsValue>()
  175. : null;
  176. var jsValues = _engine._jsValueArrayPool.RentArray(1);
  177. foreach (var property in properties)
  178. {
  179. var oldEnv = _engine.ExecutionContext.LexicalEnvironment;
  180. var paramVarEnv = JintEnvironment.NewDeclarativeEnvironment(_engine, oldEnv);
  181. PrivateEnvironment? privateEnvironment = null; // TODO PRIVATE check when implemented
  182. _engine.EnterExecutionContext(paramVarEnv, paramVarEnv, _engine.ExecutionContext.Realm, privateEnvironment);
  183. try
  184. {
  185. if (property is AssignmentProperty p)
  186. {
  187. var propertyName = p.GetKey(_engine);
  188. processedProperties?.Add(propertyName.ToString());
  189. jsValues[0] = argumentObject.Get(propertyName);
  190. SetFunctionParameter(context, p.Value, jsValues, 0, initiallyEmpty);
  191. }
  192. else
  193. {
  194. if (((RestElement) property).Argument is Identifier restIdentifier)
  195. {
  196. var rest = _engine.Realm.Intrinsics.Object.Construct((argumentObject.Properties?.Count ?? 0) - processedProperties!.Count);
  197. argumentObject.CopyDataProperties(rest, processedProperties);
  198. SetItemSafely(restIdentifier.Name, rest, initiallyEmpty);
  199. }
  200. else
  201. {
  202. ExceptionHelper.ThrowSyntaxError(_functionObject._realm, "Object rest parameter can only be objects");
  203. }
  204. }
  205. }
  206. finally
  207. {
  208. _engine.LeaveExecutionContext();
  209. }
  210. }
  211. _engine._jsValueArrayPool.ReturnArray(jsValues);
  212. }
  213. private void HandleArrayPattern(EvaluationContext context, bool initiallyEmpty, JsValue argument, ArrayPattern arrayPattern)
  214. {
  215. if (argument.IsNull())
  216. {
  217. ExceptionHelper.ThrowTypeError(_functionObject._realm, "Destructed parameter is null");
  218. }
  219. JsArray? array;
  220. if (argument is JsArray { HasOriginalIterator: true } ai)
  221. {
  222. array = ai;
  223. }
  224. else
  225. {
  226. if (!argument.TryGetIterator(_functionObject._realm, out var iterator))
  227. {
  228. ExceptionHelper.ThrowTypeError(context.Engine.Realm, "object is not iterable");
  229. }
  230. array = _engine.Realm.Intrinsics.Array.ArrayCreate(0);
  231. var max = arrayPattern.Elements.Count;
  232. if (max > 0 && arrayPattern.Elements[max - 1]?.Type == NodeType.RestElement)
  233. {
  234. // need to consume all
  235. max = int.MaxValue;
  236. }
  237. var protocol = new ArrayPatternProtocol(_engine, array, iterator, max);
  238. protocol.Execute();
  239. }
  240. var arrayContents = array.ToArray();
  241. for (var i = 0; i < arrayPattern.Elements.Count; i++)
  242. {
  243. SetFunctionParameter(context, arrayPattern.Elements[i], arrayContents, i, initiallyEmpty);
  244. }
  245. }
  246. private void HandleRestElementArray(
  247. EvaluationContext context,
  248. RestElement restElement,
  249. JsValue[] arguments,
  250. int index,
  251. bool initiallyEmpty)
  252. {
  253. // index + 1 == parameters.count because rest is last
  254. int restCount = arguments.Length - (index + 1) + 1;
  255. uint count = restCount > 0 ? (uint) restCount : 0;
  256. uint targetIndex = 0;
  257. var rest = new JsValue[count];
  258. for (var argIndex = index; argIndex < arguments.Length; ++argIndex)
  259. {
  260. rest[targetIndex++] = arguments[argIndex];
  261. }
  262. var array = new JsArray(_engine, rest);
  263. if (restElement.Argument is Identifier restIdentifier)
  264. {
  265. SetItemSafely(restIdentifier.Name, array, initiallyEmpty);
  266. }
  267. else if (restElement.Argument is DestructuringPattern pattern)
  268. {
  269. SetFunctionParameter(context, pattern, [array], 0, initiallyEmpty);
  270. }
  271. else
  272. {
  273. ExceptionHelper.ThrowSyntaxError(_functionObject._realm, "Rest parameters can only be identifiers or arrays");
  274. }
  275. }
  276. private void HandleAssignmentPatternOrExpression(
  277. EvaluationContext context,
  278. Node left,
  279. Node right,
  280. JsValue argument,
  281. bool initiallyEmpty)
  282. {
  283. var idLeft = left as Identifier;
  284. if (idLeft != null
  285. && right is Identifier idRight
  286. && string.Equals(idLeft.Name, idRight.Name, StringComparison.Ordinal))
  287. {
  288. ExceptionHelper.ThrowReferenceNameError(_functionObject._realm, idRight.Name);
  289. }
  290. if (argument.IsUndefined())
  291. {
  292. var expression = (Expression) right;
  293. var jintExpression = JintExpression.Build(expression);
  294. var oldEnv = _engine.ExecutionContext.LexicalEnvironment;
  295. var paramVarEnv = JintEnvironment.NewDeclarativeEnvironment(_engine, oldEnv);
  296. _engine.EnterExecutionContext(new ExecutionContext(null, paramVarEnv, paramVarEnv, null, _engine.Realm, null));
  297. try
  298. {
  299. argument = jintExpression.GetValue(context);
  300. }
  301. finally
  302. {
  303. _engine.LeaveExecutionContext();
  304. }
  305. if (idLeft != null && right.IsFunctionDefinition())
  306. {
  307. ((Function) argument).SetFunctionName(idLeft.Name);
  308. }
  309. }
  310. SetFunctionParameter(context, left, new[]
  311. {
  312. argument
  313. }, 0, initiallyEmpty);
  314. }
  315. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  316. private void SetItemSafely(Key name, JsValue argument, bool initiallyEmpty)
  317. {
  318. if (initiallyEmpty)
  319. {
  320. _dictionary ??= new HybridDictionary<Binding>();
  321. _dictionary[name] = new Binding(argument, canBeDeleted: false, mutable: true, strict: false);
  322. }
  323. else
  324. {
  325. SetItemCheckExisting(name, argument);
  326. }
  327. }
  328. private void SetItemCheckExisting(Key name, JsValue argument)
  329. {
  330. _dictionary ??= new HybridDictionary<Binding>();
  331. if (!_dictionary.TryGetValue(name, out var existing))
  332. {
  333. _dictionary[name] = new Binding(argument, canBeDeleted: false, mutable: true, strict: false);
  334. }
  335. else
  336. {
  337. if (existing.Mutable)
  338. {
  339. _dictionary[name] = existing.ChangeValue(argument);
  340. }
  341. else
  342. {
  343. ExceptionHelper.ThrowTypeError(_functionObject._realm, "Can't update the value of an immutable binding.");
  344. }
  345. }
  346. }
  347. private sealed class ArrayPatternProtocol : IteratorProtocol
  348. {
  349. private readonly JsArray _instance;
  350. private readonly int _max;
  351. private long _index;
  352. public ArrayPatternProtocol(
  353. Engine engine,
  354. JsArray instance,
  355. IteratorInstance iterator,
  356. int max) : base(engine, iterator, 0)
  357. {
  358. _instance = instance;
  359. _max = max;
  360. }
  361. protected override void ProcessItem(JsValue[] arguments, JsValue currentValue)
  362. {
  363. _instance.SetIndexValue((uint) _index, currentValue, updateLength: false);
  364. _index++;
  365. }
  366. protected override bool ShouldContinue => _index < _max;
  367. protected override void IterationEnd()
  368. {
  369. if (_index > 0)
  370. {
  371. _instance.SetLength((uint) _index);
  372. IteratorClose(CompletionType.Normal);
  373. }
  374. }
  375. }
  376. }