FunctionEnvironment.cs 16 KB

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