DeclarativeEnvironmentRecord.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.CompilerServices;
  4. using Esprima.Ast;
  5. using Jint.Collections;
  6. using Jint.Native;
  7. using Jint.Native.Argument;
  8. using Jint.Native.Function;
  9. using Jint.Runtime.Interpreter.Expressions;
  10. namespace Jint.Runtime.Environments
  11. {
  12. /// <summary>
  13. /// Represents a declarative environment record
  14. /// http://www.ecma-international.org/ecma-262/5.1/#sec-10.2.1.1
  15. /// </summary>
  16. public sealed class DeclarativeEnvironmentRecord : EnvironmentRecord
  17. {
  18. private StringDictionarySlim<Binding> _dictionary;
  19. private bool _set;
  20. private string _key;
  21. private Binding _value;
  22. private const string BindingNameArguments = "arguments";
  23. private Binding _argumentsBinding;
  24. // false = not accessed, true = accessed, null = values copied
  25. private bool? _argumentsBindingWasAccessed = false;
  26. public DeclarativeEnvironmentRecord(Engine engine) : base(engine)
  27. {
  28. }
  29. private void SetItem(string key, in Binding value)
  30. {
  31. if (_set && _key != key)
  32. {
  33. if (_dictionary == null)
  34. {
  35. _dictionary = new StringDictionarySlim<Binding>();
  36. }
  37. _dictionary[_key] = _value;
  38. }
  39. _set = true;
  40. _key = key;
  41. _value = value;
  42. if (_dictionary != null)
  43. {
  44. _dictionary[key] = value;
  45. }
  46. }
  47. private ref Binding GetExistingItem(string key)
  48. {
  49. if (_set && _key == key)
  50. {
  51. return ref _value;
  52. }
  53. if (key.Length == 9 && key == BindingNameArguments)
  54. {
  55. _argumentsBindingWasAccessed = true;
  56. return ref _argumentsBinding;
  57. }
  58. return ref _dictionary[key];
  59. }
  60. private bool ContainsKey(string key)
  61. {
  62. if (key.Length == 9 && key == BindingNameArguments)
  63. {
  64. return !ReferenceEquals(_argumentsBinding.Value, null);
  65. }
  66. if (_set && key == _key)
  67. {
  68. return true;
  69. }
  70. return _dictionary?.ContainsKey(key) == true;
  71. }
  72. private void Remove(string key)
  73. {
  74. if (_set && key == _key)
  75. {
  76. _set = false;
  77. _key = null;
  78. _value = default;
  79. }
  80. if (key == BindingNameArguments)
  81. {
  82. _argumentsBinding.Value = null;
  83. }
  84. else
  85. {
  86. _dictionary?.Remove(key);
  87. }
  88. }
  89. private bool TryGetValue(string key, out Binding value)
  90. {
  91. value = default;
  92. if (_set && _key == key)
  93. {
  94. value = _value;
  95. return true;
  96. }
  97. return _dictionary != null && _dictionary.TryGetValue(key, out value);
  98. }
  99. public override bool HasBinding(string name)
  100. {
  101. return ContainsKey(name);
  102. }
  103. internal override bool TryGetBinding(string name, bool strict, out Binding binding)
  104. {
  105. if (_set && _key == name)
  106. {
  107. binding = _value;
  108. return true;
  109. }
  110. if (name.Length == 9
  111. && name == BindingNameArguments
  112. && !ReferenceEquals(_argumentsBinding.Value, null))
  113. {
  114. _argumentsBindingWasAccessed = true;
  115. binding = _argumentsBinding;
  116. return true;
  117. }
  118. if (_dictionary != null)
  119. {
  120. return _dictionary.TryGetValue(name, out binding);
  121. }
  122. binding = default;
  123. return false;
  124. }
  125. public override void CreateMutableBinding(string name, JsValue value, bool canBeDeleted = false)
  126. {
  127. SetItem(name, new Binding(value, canBeDeleted, mutable: true));
  128. }
  129. public override void SetMutableBinding(string name, JsValue value, bool strict)
  130. {
  131. ref var binding = ref GetExistingItem(name);
  132. if (binding.Mutable)
  133. {
  134. binding.Value = value;
  135. }
  136. else
  137. {
  138. if (strict)
  139. {
  140. ExceptionHelper.ThrowTypeError(_engine, "Can't update the value of an immutable binding.");
  141. }
  142. }
  143. }
  144. public override JsValue GetBindingValue(string name, bool strict)
  145. {
  146. ref var binding = ref GetExistingItem(name);
  147. return UnwrapBindingValue(name, strict, binding);
  148. }
  149. internal override JsValue UnwrapBindingValue(string name, bool strict, in Binding binding)
  150. {
  151. return UnwrapBindingValueInternal(strict, binding);
  152. }
  153. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  154. private JsValue UnwrapBindingValueInternal(bool strict, in Binding binding)
  155. {
  156. if (!binding.Mutable && binding.Value._type == Types.Undefined)
  157. {
  158. if (strict)
  159. {
  160. ThrowUninitializedBindingException();
  161. }
  162. return Undefined;
  163. }
  164. return binding.Value;
  165. }
  166. private void ThrowUninitializedBindingException()
  167. {
  168. throw new JavaScriptException(_engine.ReferenceError, "Can't access an uninitialized immutable binding.");
  169. }
  170. public override bool DeleteBinding(string name)
  171. {
  172. ref Binding binding = ref GetExistingItem(name);
  173. if (ReferenceEquals(binding.Value, null))
  174. {
  175. return true;
  176. }
  177. if (!binding.CanBeDeleted)
  178. {
  179. return false;
  180. }
  181. Remove(name);
  182. return true;
  183. }
  184. public override JsValue ImplicitThisValue()
  185. {
  186. return Undefined;
  187. }
  188. /// <inheritdoc />
  189. public override string[] GetAllBindingNames()
  190. {
  191. int size = _set ? 1 : 0;
  192. if (!ReferenceEquals(_argumentsBinding.Value, null))
  193. {
  194. size += 1;
  195. }
  196. if (_dictionary != null)
  197. {
  198. size += _dictionary.Count;
  199. }
  200. var keys = size > 0 ? new string[size] : ArrayExt.Empty<string>();
  201. int n = 0;
  202. if (_set)
  203. {
  204. keys[n++] = _key;
  205. }
  206. if (!ReferenceEquals(_argumentsBinding.Value, null))
  207. {
  208. keys[n++] = BindingNameArguments;
  209. }
  210. _dictionary?.Keys.CopyTo(keys, n);
  211. return keys;
  212. }
  213. /// <summary>
  214. /// Optimized version for function calls.
  215. /// </summary>
  216. internal void AddFunctionParameters(
  217. FunctionInstance functionInstance,
  218. JsValue[] arguments,
  219. ArgumentsInstance argumentsInstance,
  220. IFunction functionDeclaration)
  221. {
  222. var parameters = functionInstance._formalParameters;
  223. bool empty = _dictionary == null && !_set;
  224. if (empty && parameters.Length == 1 && parameters[0].Length != BindingNameArguments.Length)
  225. {
  226. var jsValue = arguments.Length == 0 ? Undefined : arguments[0];
  227. jsValue = HandleAssignmentPatternIfNeeded(functionDeclaration, jsValue, 0);
  228. jsValue = HandleRestPatternIfNeeded(_engine, functionDeclaration, arguments, 0, jsValue);
  229. var binding = new Binding(jsValue, false, true);
  230. _set = true;
  231. _key = parameters[0];
  232. _value = binding;
  233. }
  234. else
  235. {
  236. AddMultipleParameters(arguments, parameters, functionDeclaration);
  237. }
  238. if (ReferenceEquals(_argumentsBinding.Value, null))
  239. {
  240. _argumentsBinding = new Binding(argumentsInstance, canBeDeleted: false, mutable: true);
  241. }
  242. }
  243. private void AddMultipleParameters(JsValue[] arguments, string[] parameters, IFunction functionDeclaration)
  244. {
  245. bool empty = _dictionary == null && !_set;
  246. for (var i = 0; i < parameters.Length; i++)
  247. {
  248. var argName = parameters[i];
  249. var jsValue = i + 1 > arguments.Length ? Undefined : arguments[i];
  250. jsValue = HandleAssignmentPatternIfNeeded(functionDeclaration, jsValue, i);
  251. if (i == parameters.Length - 1)
  252. {
  253. jsValue = HandleRestPatternIfNeeded(_engine, functionDeclaration, arguments, i, jsValue);
  254. }
  255. if (empty || !TryGetValue(argName, out var existing))
  256. {
  257. var binding = new Binding(jsValue, false, true);
  258. if (argName.Length == 9 && argName == BindingNameArguments)
  259. {
  260. _argumentsBinding = binding;
  261. }
  262. else
  263. {
  264. SetItem(argName, binding);
  265. }
  266. }
  267. else
  268. {
  269. if (existing.Mutable)
  270. {
  271. ref var b = ref GetExistingItem(argName);
  272. b.Value = jsValue;
  273. }
  274. else
  275. {
  276. ExceptionHelper.ThrowTypeError(_engine, "Can't update the value of an immutable binding.");
  277. }
  278. }
  279. }
  280. }
  281. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  282. internal static JsValue HandleAssignmentPatternIfNeeded(IFunction functionDeclaration, JsValue jsValue, int index)
  283. {
  284. if (jsValue.IsUndefined()
  285. && index < functionDeclaration?.Params.Count
  286. && functionDeclaration.Params[index] is AssignmentPattern ap
  287. && ap.Right is Literal l)
  288. {
  289. return JintLiteralExpression.ConvertToJsValue(l);
  290. }
  291. return jsValue;
  292. }
  293. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  294. private static JsValue HandleRestPatternIfNeeded(
  295. Engine engine,
  296. IFunction functionDeclaration,
  297. JsValue[] arguments,
  298. int index,
  299. JsValue defaultValue)
  300. {
  301. if (index < functionDeclaration?.Params.Count
  302. && functionDeclaration.Params[index] is RestElement)
  303. {
  304. var count = (uint) (arguments.Length - functionDeclaration.Params.Count + 1);
  305. var rest = engine.Array.ConstructFast(count);
  306. uint targetIndex = 0;
  307. for (var i = index; i < arguments.Length; ++i)
  308. {
  309. rest.SetIndexValue(targetIndex++, arguments[i], updateLength: false);
  310. }
  311. return rest;
  312. }
  313. return defaultValue;
  314. }
  315. internal void AddVariableDeclarations(List<VariableDeclaration> variableDeclarations)
  316. {
  317. var variableDeclarationsCount = variableDeclarations.Count;
  318. for (var i = 0; i < variableDeclarationsCount; i++)
  319. {
  320. var variableDeclaration = variableDeclarations[i];
  321. var declarationsCount = variableDeclaration.Declarations.Count;
  322. for (var j = 0; j < declarationsCount; j++)
  323. {
  324. var d = variableDeclaration.Declarations[j];
  325. var dn = ((Identifier) d.Id).Name;
  326. if (!ContainsKey(dn))
  327. {
  328. var binding = new Binding(Undefined, canBeDeleted: false, mutable: true);
  329. SetItem(dn, binding);
  330. }
  331. }
  332. }
  333. }
  334. internal override void FunctionWasCalled()
  335. {
  336. // we can safely release arguments only if it doesn't have possibility to escape the scope
  337. // so check if someone ever accessed it
  338. if (!(_argumentsBinding.Value is ArgumentsInstance argumentsInstance))
  339. {
  340. return;
  341. }
  342. if (!argumentsInstance._initialized && _argumentsBindingWasAccessed == false)
  343. {
  344. _engine._argumentsInstancePool.Return(argumentsInstance);
  345. _argumentsBinding = default;
  346. }
  347. else if (_argumentsBindingWasAccessed != null && argumentsInstance._args.Length > 0)
  348. {
  349. // we need to ensure we hold on to arguments given
  350. argumentsInstance.PersistArguments();
  351. _argumentsBindingWasAccessed = null;
  352. }
  353. }
  354. }
  355. }