FunctionEnvironmentRecord.cs 15 KB

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