FunctionEnvironmentRecord.cs 17 KB

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