FunctionEnvironmentRecord.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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.Expressions;
  10. namespace Jint.Runtime.Environments
  11. {
  12. /// <summary>
  13. /// https://tc39.es/ecma262/#sec-function-environment-records
  14. /// </summary>
  15. internal sealed class FunctionEnvironmentRecord : DeclarativeEnvironmentRecord
  16. {
  17. private enum ThisBindingStatus
  18. {
  19. Lexical,
  20. Initialized,
  21. Uninitialized
  22. }
  23. private JsValue _thisValue;
  24. private ThisBindingStatus _thisBindingStatus;
  25. internal readonly FunctionInstance _functionObject;
  26. public FunctionEnvironmentRecord(
  27. Engine engine,
  28. FunctionInstance 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. public override bool HasThisBinding() => _thisBindingStatus != ThisBindingStatus.Lexical;
  43. public override bool HasSuperBinding() =>
  44. _thisBindingStatus != ThisBindingStatus.Lexical && !_functionObject._homeObject.IsUndefined();
  45. public JsValue BindThisValue(JsValue value)
  46. {
  47. if (_thisBindingStatus == ThisBindingStatus.Initialized)
  48. {
  49. ExceptionHelper.ThrowReferenceError(_functionObject._realm, (string) null);
  50. }
  51. _thisValue = value;
  52. _thisBindingStatus = ThisBindingStatus.Initialized;
  53. return value;
  54. }
  55. public override JsValue GetThisBinding()
  56. {
  57. if (_thisBindingStatus != ThisBindingStatus.Uninitialized)
  58. {
  59. return _thisValue;
  60. }
  61. ExceptionHelper.ThrowReferenceError(_engine.ExecutionContext.Realm, (string) null);
  62. return null;
  63. }
  64. public JsValue GetSuperBase()
  65. {
  66. var home = _functionObject._homeObject;
  67. return home.IsUndefined()
  68. ? Undefined
  69. : ((ObjectInstance) home).GetPrototypeOf();
  70. }
  71. // optimization to have logic near record internal structures.
  72. internal void InitializeParameters(
  73. Key[] parameterNames,
  74. bool hasDuplicates,
  75. JsValue[] arguments)
  76. {
  77. var value = hasDuplicates ? Undefined : null;
  78. var directSet = !hasDuplicates && _dictionary.Count == 0;
  79. for (var i = 0; (uint) i < (uint) parameterNames.Length; i++)
  80. {
  81. var paramName = parameterNames[i];
  82. if (directSet || !_dictionary.ContainsKey(paramName))
  83. {
  84. var parameterValue = value;
  85. if (arguments != null)
  86. {
  87. parameterValue = (uint) i < (uint) arguments.Length ? arguments[i] : Undefined;
  88. }
  89. _dictionary[paramName] = new Binding(parameterValue, canBeDeleted: false, mutable: true, strict: false);
  90. }
  91. }
  92. }
  93. internal void AddFunctionParameters(IFunction functionDeclaration, JsValue[] arguments)
  94. {
  95. bool empty = _dictionary.Count == 0;
  96. ref readonly var parameters = ref functionDeclaration.Params;
  97. var count = parameters.Count;
  98. for (var i = 0; i < count; i++)
  99. {
  100. SetFunctionParameter(parameters[i], arguments, i, empty);
  101. }
  102. }
  103. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  104. private void SetFunctionParameter(
  105. Node parameter,
  106. JsValue[] arguments,
  107. int index,
  108. bool initiallyEmpty)
  109. {
  110. if (parameter is Identifier identifier)
  111. {
  112. var argument = (uint) index < (uint) arguments.Length ? arguments[index] : Undefined;
  113. SetItemSafely(identifier.Name, argument, initiallyEmpty);
  114. }
  115. else
  116. {
  117. SetFunctionParameterUnlikely(parameter, arguments, index, initiallyEmpty);
  118. }
  119. }
  120. private void SetFunctionParameterUnlikely(
  121. Node parameter,
  122. JsValue[] arguments,
  123. int index,
  124. bool initiallyEmpty)
  125. {
  126. var argument = arguments.Length > index ? arguments[index] : Undefined;
  127. if (parameter is RestElement restElement)
  128. {
  129. HandleRestElementArray(restElement, arguments, index, initiallyEmpty);
  130. }
  131. else if (parameter is ArrayPattern arrayPattern)
  132. {
  133. HandleArrayPattern(initiallyEmpty, argument, arrayPattern);
  134. }
  135. else if (parameter is ObjectPattern objectPattern)
  136. {
  137. HandleObjectPattern(initiallyEmpty, argument, objectPattern);
  138. }
  139. else if (parameter is AssignmentPattern assignmentPattern)
  140. {
  141. HandleAssignmentPatternOrExpression(assignmentPattern.Left, assignmentPattern.Right, argument, initiallyEmpty);
  142. }
  143. else if (parameter is AssignmentExpression assignmentExpression)
  144. {
  145. HandleAssignmentPatternOrExpression(assignmentExpression.Left, assignmentExpression.Right, argument, initiallyEmpty);
  146. }
  147. }
  148. private void HandleObjectPattern(bool initiallyEmpty, JsValue argument, ObjectPattern objectPattern)
  149. {
  150. if (argument.IsNullOrUndefined())
  151. {
  152. ExceptionHelper.ThrowTypeError(_functionObject._realm, "Destructed parameter is null or undefined");
  153. }
  154. if (!argument.IsObject())
  155. {
  156. return;
  157. }
  158. var argumentObject = argument.AsObject();
  159. var processedProperties = objectPattern.Properties.Count > 0 &&
  160. objectPattern.Properties[objectPattern.Properties.Count - 1] is RestElement
  161. ? new HashSet<JsValue>()
  162. : null;
  163. var jsValues = _engine._jsValueArrayPool.RentArray(1);
  164. foreach (var property in objectPattern.Properties)
  165. {
  166. var oldEnv = _engine.ExecutionContext.LexicalEnvironment;
  167. var paramVarEnv = JintEnvironment.NewDeclarativeEnvironment(_engine, oldEnv);
  168. PrivateEnvironmentRecord privateEnvironment = null; // TODO PRIVATE check when implemented
  169. _engine.EnterExecutionContext(paramVarEnv, paramVarEnv, _engine.ExecutionContext.Realm, privateEnvironment);
  170. try
  171. {
  172. if (property is Property p)
  173. {
  174. JsString propertyName = JsString.Empty;
  175. if (p.Key is Identifier propertyIdentifier)
  176. {
  177. propertyName = JsString.Create(propertyIdentifier.Name);
  178. }
  179. else if (p.Key is Literal propertyLiteral)
  180. {
  181. propertyName = JsString.Create(propertyLiteral.Raw);
  182. }
  183. else if (p.Key is CallExpression callExpression)
  184. {
  185. var jintCallExpression = new JintCallExpression(_engine, callExpression);
  186. var jsValue = jintCallExpression.GetValue();
  187. propertyName = TypeConverter.ToJsString(jsValue);
  188. }
  189. else
  190. {
  191. ExceptionHelper.ThrowArgumentOutOfRangeException("property", "unknown object pattern property type");
  192. }
  193. processedProperties?.Add(propertyName.ToString());
  194. jsValues[0] = argumentObject.Get(propertyName);
  195. SetFunctionParameter(p.Value, jsValues, 0, initiallyEmpty);
  196. }
  197. else
  198. {
  199. if (((RestElement) property).Argument is Identifier restIdentifier)
  200. {
  201. var rest = _engine.Realm.Intrinsics.Object.Construct(argumentObject.Properties.Count - processedProperties.Count);
  202. argumentObject.CopyDataProperties(rest, processedProperties);
  203. SetItemSafely(restIdentifier.Name, rest, initiallyEmpty);
  204. }
  205. else
  206. {
  207. ExceptionHelper.ThrowSyntaxError(_functionObject._realm, "Object rest parameter can only be objects");
  208. }
  209. }
  210. }
  211. finally
  212. {
  213. _engine.LeaveExecutionContext();
  214. }
  215. }
  216. _engine._jsValueArrayPool.ReturnArray(jsValues);
  217. }
  218. private void HandleArrayPattern(bool initiallyEmpty, JsValue argument, ArrayPattern arrayPattern)
  219. {
  220. if (argument.IsNull())
  221. {
  222. ExceptionHelper.ThrowTypeError(_functionObject._realm, "Destructed parameter is null");
  223. }
  224. ArrayInstance array = null;
  225. var arrayContents = System.Array.Empty<JsValue>();
  226. if (argument.IsArray())
  227. {
  228. array = argument.AsArray();
  229. }
  230. else if (argument.IsObject() && argument.TryGetIterator(_functionObject._realm, out var iterator))
  231. {
  232. array = _engine.Realm.Intrinsics.Array.ConstructFast(0);
  233. var protocol = new ArrayPatternProtocol(_engine, array, iterator, arrayPattern.Elements.Count);
  234. protocol.Execute();
  235. }
  236. if (!ReferenceEquals(array, null))
  237. {
  238. arrayContents = new JsValue[array.GetLength()];
  239. for (uint i = 0; i < (uint) arrayContents.Length; i++)
  240. {
  241. arrayContents[i] = array.Get(i);
  242. }
  243. }
  244. for (uint arrayIndex = 0; arrayIndex < arrayPattern.Elements.Count; arrayIndex++)
  245. {
  246. SetFunctionParameter(arrayPattern.Elements[(int) arrayIndex], arrayContents, (int) arrayIndex, initiallyEmpty);
  247. }
  248. }
  249. private void HandleRestElementArray(
  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. var rest = _engine.Realm.Intrinsics.Array.ConstructFast(count);
  259. uint targetIndex = 0;
  260. for (var argIndex = index; argIndex < arguments.Length; ++argIndex)
  261. {
  262. rest.SetIndexValue(targetIndex++, arguments[argIndex], updateLength: false);
  263. }
  264. if (restElement.Argument is Identifier restIdentifier)
  265. {
  266. SetItemSafely(restIdentifier.Name, rest, initiallyEmpty);
  267. }
  268. else if (restElement.Argument is BindingPattern bindingPattern)
  269. {
  270. SetFunctionParameter(bindingPattern, new JsValue[]
  271. {
  272. rest
  273. }, index, initiallyEmpty);
  274. }
  275. else
  276. {
  277. ExceptionHelper.ThrowSyntaxError(_functionObject._realm, "Rest parameters can only be identifiers or arrays");
  278. }
  279. }
  280. private void HandleAssignmentPatternOrExpression(
  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.ThrowReferenceError(_functionObject._realm, idRight.Name);
  292. }
  293. if (argument.IsUndefined())
  294. {
  295. var expression = right.As<Expression>();
  296. var jintExpression = JintExpression.Build(_engine, expression);
  297. var oldEnv = _engine.ExecutionContext.LexicalEnvironment;
  298. var paramVarEnv = JintEnvironment.NewDeclarativeEnvironment(_engine, oldEnv);
  299. _engine.EnterExecutionContext(new ExecutionContext(paramVarEnv, paramVarEnv, null, _engine.Realm, null));
  300. try
  301. {
  302. argument = jintExpression.GetValue();
  303. }
  304. finally
  305. {
  306. _engine.LeaveExecutionContext();
  307. }
  308. if (idLeft != null && right.IsFunctionWithName())
  309. {
  310. ((FunctionInstance) argument).SetFunctionName(idLeft.Name);
  311. }
  312. }
  313. SetFunctionParameter(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[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. 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 ArrayInstance _instance;
  351. private readonly int _max;
  352. private long _index = -1;
  353. public ArrayPatternProtocol(
  354. Engine engine,
  355. ArrayInstance instance,
  356. IIterator iterator,
  357. int max) : base(engine, iterator, 0)
  358. {
  359. _instance = instance;
  360. _max = max;
  361. }
  362. protected override void ProcessItem(JsValue[] args, JsValue currentValue)
  363. {
  364. _index++;
  365. var jsValue = ExtractValueFromIteratorInstance(currentValue);
  366. _instance.SetIndexValue((uint) _index, jsValue, updateLength: false);
  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. }