FunctionEnvironment.cs 16 KB

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