FunctionEnvironmentRecord.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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. private readonly FunctionInstance _functionObject;
  26. private readonly JsValue _homeObject = Undefined;
  27. private readonly JsValue _newTarget;
  28. public FunctionEnvironmentRecord(
  29. Engine engine,
  30. FunctionInstance functionObject,
  31. JsValue newTarget) : base(engine)
  32. {
  33. _functionObject = functionObject;
  34. _newTarget = newTarget;
  35. if (functionObject is ArrowFunctionInstance)
  36. {
  37. _thisBindingStatus = ThisBindingStatus.Lexical;
  38. }
  39. else
  40. {
  41. _thisBindingStatus = ThisBindingStatus.Uninitialized;
  42. }
  43. }
  44. public override bool HasThisBinding() => _thisBindingStatus != ThisBindingStatus.Lexical;
  45. public override bool HasSuperBinding() =>
  46. _thisBindingStatus != ThisBindingStatus.Lexical && !_homeObject.IsUndefined();
  47. public override JsValue WithBaseObject()
  48. {
  49. return _thisBindingStatus == ThisBindingStatus.Uninitialized
  50. ? ExceptionHelper.ThrowReferenceError<JsValue>(_engine)
  51. : _thisValue;
  52. }
  53. public JsValue BindThisValue(JsValue value)
  54. {
  55. if (_thisBindingStatus == ThisBindingStatus.Initialized)
  56. {
  57. ExceptionHelper.ThrowReferenceError<JsValue>(_engine);
  58. }
  59. _thisValue = value;
  60. _thisBindingStatus = ThisBindingStatus.Initialized;
  61. return value;
  62. }
  63. public override JsValue GetThisBinding()
  64. {
  65. return _thisBindingStatus == ThisBindingStatus.Uninitialized
  66. ? ExceptionHelper.ThrowReferenceError<JsValue>(_engine)
  67. : _thisValue;
  68. }
  69. public JsValue GetSuperBase()
  70. {
  71. return _homeObject.IsUndefined()
  72. ? Undefined
  73. : ((ObjectInstance) _homeObject).Prototype;
  74. }
  75. // optimization to have logic near record internal structures.
  76. internal void InitializeParameters(
  77. Key[] parameterNames,
  78. bool hasDuplicates,
  79. JsValue[] arguments)
  80. {
  81. var value = hasDuplicates ? Undefined : null;
  82. var directSet = !hasDuplicates && _dictionary.Count == 0;
  83. for (var i = 0; (uint) i < (uint) parameterNames.Length; i++)
  84. {
  85. var paramName = parameterNames[i];
  86. if (directSet || !_dictionary.ContainsKey(paramName))
  87. {
  88. var parameterValue = value;
  89. if (arguments != null)
  90. {
  91. parameterValue = (uint) i < (uint) arguments.Length ? arguments[i] : Undefined;
  92. }
  93. _dictionary[paramName] = new Binding(parameterValue, canBeDeleted: false, mutable: true, strict: false);
  94. }
  95. }
  96. }
  97. internal void AddFunctionParameters(IFunction functionDeclaration, JsValue[] arguments)
  98. {
  99. bool empty = _dictionary.Count == 0;
  100. ref readonly var parameters = ref functionDeclaration.Params;
  101. var count = parameters.Count;
  102. for (var i = 0; i < count; i++)
  103. {
  104. SetFunctionParameter(parameters[i], arguments, i, empty);
  105. }
  106. }
  107. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  108. private void SetFunctionParameter(
  109. Node parameter,
  110. JsValue[] arguments,
  111. int index,
  112. bool initiallyEmpty)
  113. {
  114. if (parameter is Identifier identifier)
  115. {
  116. var argument = (uint) index < (uint) arguments.Length ? arguments[index] : Undefined;
  117. SetItemSafely(identifier.Name, argument, initiallyEmpty);
  118. }
  119. else
  120. {
  121. SetFunctionParameterUnlikely(parameter, arguments, index, initiallyEmpty);
  122. }
  123. }
  124. private void SetFunctionParameterUnlikely(
  125. Node parameter,
  126. JsValue[] arguments,
  127. int index,
  128. bool initiallyEmpty)
  129. {
  130. var argument = arguments.Length > index ? arguments[index] : Undefined;
  131. if (parameter is RestElement restElement)
  132. {
  133. HandleRestElementArray(restElement, arguments, index, initiallyEmpty);
  134. }
  135. else if (parameter is ArrayPattern arrayPattern)
  136. {
  137. HandleArrayPattern(initiallyEmpty, argument, arrayPattern);
  138. }
  139. else if (parameter is ObjectPattern objectPattern)
  140. {
  141. HandleObjectPattern(initiallyEmpty, argument, objectPattern);
  142. }
  143. else if (parameter is AssignmentPattern assignmentPattern)
  144. {
  145. HandleAssignmentPatternOrExpression(assignmentPattern.Left, assignmentPattern.Right, argument, initiallyEmpty);
  146. }
  147. else if (parameter is AssignmentExpression assignmentExpression)
  148. {
  149. HandleAssignmentPatternOrExpression(assignmentExpression.Left, assignmentExpression.Right, argument, initiallyEmpty);
  150. }
  151. }
  152. private void HandleObjectPattern(bool initiallyEmpty, JsValue argument, ObjectPattern objectPattern)
  153. {
  154. if (argument.IsNullOrUndefined())
  155. {
  156. ExceptionHelper.ThrowTypeError(_engine, "Destructed parameter is null or undefined");
  157. }
  158. if (!argument.IsObject())
  159. {
  160. return;
  161. }
  162. var argumentObject = argument.AsObject();
  163. var processedProperties = objectPattern.Properties.Count > 0 &&
  164. objectPattern.Properties[objectPattern.Properties.Count - 1] is RestElement
  165. ? new HashSet<JsValue>()
  166. : null;
  167. var jsValues = _engine._jsValueArrayPool.RentArray(1);
  168. foreach (var property in objectPattern.Properties)
  169. {
  170. var oldEnv = _engine.ExecutionContext.LexicalEnvironment;
  171. var paramVarEnv = LexicalEnvironment.NewDeclarativeEnvironment(_engine, oldEnv);
  172. _engine.EnterExecutionContext(paramVarEnv, paramVarEnv);
  173. try
  174. {
  175. if (property is Property p)
  176. {
  177. JsString propertyName;
  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(_engine, callExpression);
  189. var jsValue = jintCallExpression.GetValue();
  190. propertyName = TypeConverter.ToJsString(jsValue);
  191. }
  192. else
  193. {
  194. propertyName = ExceptionHelper.ThrowArgumentOutOfRangeException<JsString>("property", "unknown object pattern property type");
  195. }
  196. processedProperties?.Add(propertyName.AsStringWithoutTypeCheck());
  197. jsValues[0] = argumentObject.Get(propertyName);
  198. SetFunctionParameter(p.Value, jsValues, 0, initiallyEmpty);
  199. }
  200. else
  201. {
  202. if (((RestElement) property).Argument is Identifier restIdentifier)
  203. {
  204. var rest = _engine.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(_engine, "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(bool initiallyEmpty, JsValue argument, ArrayPattern arrayPattern)
  222. {
  223. if (argument.IsNull())
  224. {
  225. ExceptionHelper.ThrowTypeError(_engine, "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(_engine, out var iterator))
  234. {
  235. array = _engine.Array.ConstructFast(0);
  236. var protocol = new ArrayPatternProtocol(_engine, array, iterator, arrayPattern.Elements.Count);
  237. protocol.Execute();
  238. }
  239. if (!ReferenceEquals(array, null))
  240. {
  241. arrayContents = new JsValue[array.GetLength()];
  242. for (uint i = 0; i < (uint) arrayContents.Length; i++)
  243. {
  244. arrayContents[i] = array.Get(i);
  245. }
  246. }
  247. for (uint arrayIndex = 0; arrayIndex < arrayPattern.Elements.Count; arrayIndex++)
  248. {
  249. SetFunctionParameter(arrayPattern.Elements[(int) arrayIndex], arrayContents, (int) arrayIndex, initiallyEmpty);
  250. }
  251. }
  252. private void HandleRestElementArray(
  253. RestElement restElement,
  254. JsValue[] arguments,
  255. int index,
  256. bool initiallyEmpty)
  257. {
  258. // index + 1 == parameters.count because rest is last
  259. int restCount = arguments.Length - (index + 1) + 1;
  260. uint count = restCount > 0 ? (uint) restCount : 0;
  261. var rest = _engine.Array.ConstructFast(count);
  262. uint targetIndex = 0;
  263. for (var argIndex = index; argIndex < arguments.Length; ++argIndex)
  264. {
  265. rest.SetIndexValue(targetIndex++, arguments[argIndex], updateLength: false);
  266. }
  267. if (restElement.Argument is Identifier restIdentifier)
  268. {
  269. SetItemSafely(restIdentifier.Name, rest, initiallyEmpty);
  270. }
  271. else if (restElement.Argument is BindingPattern bindingPattern)
  272. {
  273. SetFunctionParameter(bindingPattern, new JsValue[]
  274. {
  275. rest
  276. }, index, initiallyEmpty);
  277. }
  278. else
  279. {
  280. ExceptionHelper.ThrowSyntaxError(_engine, "Rest parameters can only be identifiers or arrays");
  281. }
  282. }
  283. private void HandleAssignmentPatternOrExpression(
  284. Node left,
  285. Node right,
  286. JsValue argument,
  287. bool initiallyEmpty)
  288. {
  289. var idLeft = left as Identifier;
  290. if (idLeft != null
  291. && right is Identifier idRight
  292. && idLeft.Name == idRight.Name)
  293. {
  294. ExceptionHelper.ThrowReferenceError(_engine, idRight.Name);
  295. }
  296. if (argument.IsUndefined())
  297. {
  298. var expression = right.As<Expression>();
  299. var jintExpression = JintExpression.Build(_engine, expression);
  300. var oldEnv = _engine.ExecutionContext.LexicalEnvironment;
  301. var paramVarEnv = LexicalEnvironment.NewDeclarativeEnvironment(_engine, oldEnv);
  302. _engine.EnterExecutionContext(paramVarEnv, paramVarEnv);
  303. try
  304. {
  305. argument = jintExpression.GetValue();
  306. }
  307. finally
  308. {
  309. _engine.LeaveExecutionContext();
  310. }
  311. if (idLeft != null && right.IsFunctionWithName())
  312. {
  313. ((FunctionInstance) argument).SetFunctionName(idLeft.Name);
  314. }
  315. }
  316. SetFunctionParameter(left, new[]
  317. {
  318. argument
  319. }, 0, initiallyEmpty);
  320. }
  321. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  322. private void SetItemSafely(Key name, JsValue argument, bool initiallyEmpty)
  323. {
  324. if (initiallyEmpty)
  325. {
  326. _dictionary[name] = new Binding(argument, canBeDeleted: false, mutable: true, strict: false);
  327. }
  328. else
  329. {
  330. SetItemCheckExisting(name, argument);
  331. }
  332. }
  333. private void SetItemCheckExisting(Key name, JsValue argument)
  334. {
  335. if (!_dictionary.TryGetValue(name, out var existing))
  336. {
  337. _dictionary[name] = new Binding(argument, canBeDeleted: false, mutable: true, strict: false);
  338. }
  339. else
  340. {
  341. if (existing.Mutable)
  342. {
  343. _dictionary[name] = existing.ChangeValue(argument);
  344. }
  345. else
  346. {
  347. ExceptionHelper.ThrowTypeError(_engine, "Can't update the value of an immutable binding.");
  348. }
  349. }
  350. }
  351. private sealed class ArrayPatternProtocol : IteratorProtocol
  352. {
  353. private readonly ArrayInstance _instance;
  354. private readonly int _max;
  355. private long _index = -1;
  356. public ArrayPatternProtocol(
  357. Engine engine,
  358. ArrayInstance instance,
  359. IIterator iterator,
  360. int max) : base(engine, iterator, 0)
  361. {
  362. _instance = instance;
  363. _max = max;
  364. }
  365. protected override void ProcessItem(JsValue[] args, JsValue currentValue)
  366. {
  367. _index++;
  368. var jsValue = ExtractValueFromIteratorInstance(currentValue);
  369. _instance.SetIndexValue((uint) _index, jsValue, updateLength: false);
  370. }
  371. protected override bool ShouldContinue => _index < _max;
  372. protected override void IterationEnd()
  373. {
  374. if (_index >= 0)
  375. {
  376. _instance.SetLength((uint) _index);
  377. IteratorClose(CompletionType.Normal);
  378. }
  379. }
  380. }
  381. }
  382. }