FunctionEnvironmentRecord.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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 = arguments.At(index);
  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.At(index);
  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. var argumentObject = TypeConverter.ToObject(_engine.Realm , argument);
  175. ref readonly var properties = ref objectPattern.Properties;
  176. var processedProperties = properties.Count > 0 && properties[properties.Count - 1] is RestElement
  177. ? new HashSet<JsValue>()
  178. : null;
  179. var jsValues = _engine._jsValueArrayPool.RentArray(1);
  180. foreach (var property in properties)
  181. {
  182. var oldEnv = _engine.ExecutionContext.LexicalEnvironment;
  183. var paramVarEnv = JintEnvironment.NewDeclarativeEnvironment(_engine, oldEnv);
  184. PrivateEnvironmentRecord? privateEnvironment = null; // TODO PRIVATE check when implemented
  185. _engine.EnterExecutionContext(paramVarEnv, paramVarEnv, _engine.ExecutionContext.Realm, privateEnvironment);
  186. try
  187. {
  188. if (property is Property p)
  189. {
  190. var propertyName = p.GetKey(_engine);
  191. processedProperties?.Add(propertyName.ToString());
  192. jsValues[0] = argumentObject.Get(propertyName);
  193. SetFunctionParameter(context, p.Value, jsValues, 0, initiallyEmpty);
  194. }
  195. else
  196. {
  197. if (((RestElement) property).Argument is Identifier restIdentifier)
  198. {
  199. var rest = _engine.Realm.Intrinsics.Object.Construct(argumentObject.Properties!.Count - processedProperties!.Count);
  200. argumentObject.CopyDataProperties(rest, processedProperties);
  201. SetItemSafely(restIdentifier.Name, rest, initiallyEmpty);
  202. }
  203. else
  204. {
  205. ExceptionHelper.ThrowSyntaxError(_functionObject._realm, "Object rest parameter can only be objects");
  206. }
  207. }
  208. }
  209. finally
  210. {
  211. _engine.LeaveExecutionContext();
  212. }
  213. }
  214. _engine._jsValueArrayPool.ReturnArray(jsValues);
  215. }
  216. private void HandleArrayPattern(EvaluationContext context, bool initiallyEmpty, JsValue argument, ArrayPattern arrayPattern)
  217. {
  218. if (argument.IsNull())
  219. {
  220. ExceptionHelper.ThrowTypeError(_functionObject._realm, "Destructed parameter is null");
  221. }
  222. ArrayInstance? array;
  223. if (argument is ArrayInstance { HasOriginalIterator: true } ai)
  224. {
  225. array = ai;
  226. }
  227. else
  228. {
  229. if (!argument.TryGetIterator(_functionObject._realm, out var iterator))
  230. {
  231. ExceptionHelper.ThrowTypeError(context.Engine.Realm, "object is not iterable");
  232. }
  233. array = _engine.Realm.Intrinsics.Array.ArrayCreate(0);
  234. var max = arrayPattern.Elements.Count;
  235. if (max > 0 && arrayPattern.Elements[max - 1]?.Type == Nodes.RestElement)
  236. {
  237. // need to consume all
  238. max = int.MaxValue;
  239. }
  240. var protocol = new ArrayPatternProtocol(_engine, array, iterator, max);
  241. protocol.Execute();
  242. }
  243. var arrayContents = array.ToArray();
  244. for (var i = 0; i < arrayPattern.Elements.Count; i++)
  245. {
  246. SetFunctionParameter(context, arrayPattern.Elements[i], arrayContents, i, initiallyEmpty);
  247. }
  248. }
  249. private void HandleRestElementArray(
  250. EvaluationContext context,
  251. RestElement restElement,
  252. JsValue[] arguments,
  253. int index,
  254. bool initiallyEmpty)
  255. {
  256. // index + 1 == parameters.count because rest is last
  257. int restCount = arguments.Length - (index + 1) + 1;
  258. uint count = restCount > 0 ? (uint) restCount : 0;
  259. uint targetIndex = 0;
  260. var rest = new object[count];
  261. for (var argIndex = index; argIndex < arguments.Length; ++argIndex)
  262. {
  263. rest[targetIndex++] = arguments[argIndex];
  264. }
  265. var array = new ArrayInstance(_engine, rest);
  266. if (restElement.Argument is Identifier restIdentifier)
  267. {
  268. SetItemSafely(restIdentifier.Name, array, initiallyEmpty);
  269. }
  270. else if (restElement.Argument is BindingPattern bindingPattern)
  271. {
  272. SetFunctionParameter(context, bindingPattern, new [] { array }, 0, initiallyEmpty);
  273. }
  274. else
  275. {
  276. ExceptionHelper.ThrowSyntaxError(_functionObject._realm, "Rest parameters can only be identifiers or arrays");
  277. }
  278. }
  279. private void HandleAssignmentPatternOrExpression(
  280. EvaluationContext context,
  281. Node left,
  282. Node right,
  283. JsValue argument,
  284. bool initiallyEmpty)
  285. {
  286. var idLeft = left as Identifier;
  287. if (idLeft != null
  288. && right is Identifier idRight
  289. && idLeft.Name == idRight.Name)
  290. {
  291. ExceptionHelper.ThrowReferenceNameError(_functionObject._realm, idRight.Name);
  292. }
  293. if (argument.IsUndefined())
  294. {
  295. var expression = right.As<Expression>();
  296. var jintExpression = JintExpression.Build(expression);
  297. var oldEnv = _engine.ExecutionContext.LexicalEnvironment;
  298. var paramVarEnv = JintEnvironment.NewDeclarativeEnvironment(_engine, oldEnv);
  299. _engine.EnterExecutionContext(new ExecutionContext(null, paramVarEnv, paramVarEnv, null, _engine.Realm, null));
  300. try
  301. {
  302. argument = jintExpression.GetValue(context);
  303. }
  304. finally
  305. {
  306. _engine.LeaveExecutionContext();
  307. }
  308. if (idLeft != null && right.IsFunctionDefinition())
  309. {
  310. ((FunctionInstance) argument).SetFunctionName(idLeft.Name);
  311. }
  312. }
  313. SetFunctionParameter(context, left, new[]
  314. {
  315. argument
  316. }, 0, initiallyEmpty);
  317. }
  318. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  319. private void SetItemSafely(Key name, JsValue argument, bool initiallyEmpty)
  320. {
  321. if (initiallyEmpty)
  322. {
  323. _dictionary ??= new HybridDictionary<Binding>();
  324. _dictionary[name] = new Binding(argument, canBeDeleted: false, mutable: true, strict: false);
  325. }
  326. else
  327. {
  328. SetItemCheckExisting(name, argument);
  329. }
  330. }
  331. private void SetItemCheckExisting(Key name, JsValue argument)
  332. {
  333. _dictionary ??= new HybridDictionary<Binding>();
  334. if (!_dictionary.TryGetValue(name, out var existing))
  335. {
  336. _dictionary[name] = new Binding(argument, canBeDeleted: false, mutable: true, strict: false);
  337. }
  338. else
  339. {
  340. if (existing.Mutable)
  341. {
  342. _dictionary[name] = existing.ChangeValue(argument);
  343. }
  344. else
  345. {
  346. ExceptionHelper.ThrowTypeError(_functionObject._realm, "Can't update the value of an immutable binding.");
  347. }
  348. }
  349. }
  350. private sealed class ArrayPatternProtocol : IteratorProtocol
  351. {
  352. private readonly ArrayInstance _instance;
  353. private readonly int _max;
  354. private long _index;
  355. public ArrayPatternProtocol(
  356. Engine engine,
  357. ArrayInstance instance,
  358. IteratorInstance iterator,
  359. int max) : base(engine, iterator, 0)
  360. {
  361. _instance = instance;
  362. _max = max;
  363. }
  364. protected override void ProcessItem(JsValue[] args, JsValue currentValue)
  365. {
  366. _instance.SetIndexValue((uint) _index, currentValue, updateLength: false);
  367. _index++;
  368. }
  369. protected override bool ShouldContinue => _index < _max;
  370. protected override void IterationEnd()
  371. {
  372. if (_index > 0)
  373. {
  374. _instance.SetLength((uint) _index);
  375. IteratorClose(CompletionType.Normal);
  376. }
  377. }
  378. }
  379. }
  380. }