FunctionEnvironmentRecord.cs 16 KB

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