2
0

Engine.cs 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.CompilerServices;
  4. using Esprima;
  5. using Esprima.Ast;
  6. using Jint.Native;
  7. using Jint.Native.Argument;
  8. using Jint.Native.Function;
  9. using Jint.Native.Object;
  10. using Jint.Native.Promise;
  11. using Jint.Native.Symbol;
  12. using Jint.Pooling;
  13. using Jint.Runtime;
  14. using Jint.Runtime.CallStack;
  15. using Jint.Runtime.Debugger;
  16. using Jint.Runtime.Descriptors;
  17. using Jint.Runtime.Environments;
  18. using Jint.Runtime.Interop;
  19. using Jint.Runtime.Interop.Reflection;
  20. using Jint.Runtime.Interpreter;
  21. using Jint.Runtime.Interpreter.Expressions;
  22. using Jint.Runtime.References;
  23. namespace Jint
  24. {
  25. public partial class Engine
  26. {
  27. private static readonly ParserOptions DefaultParserOptions = new("<anonymous>")
  28. {
  29. AdaptRegexp = true,
  30. Tolerant = true
  31. };
  32. private readonly ExecutionContextStack _executionContexts;
  33. private JsValue _completionValue = JsValue.Undefined;
  34. internal Node _lastSyntaxNode;
  35. private readonly EventLoop _eventLoop = new();
  36. // lazy properties
  37. private DebugHandler _debugHandler;
  38. // cached access
  39. internal readonly IObjectConverter[] _objectConverters;
  40. private readonly IConstraint[] _constraints;
  41. internal readonly bool _isDebugMode;
  42. internal readonly bool _isStrict;
  43. internal readonly IReferenceResolver _referenceResolver;
  44. internal readonly ReferencePool _referencePool;
  45. internal readonly ArgumentsInstancePool _argumentsInstancePool;
  46. internal readonly JsValueArrayPool _jsValueArrayPool;
  47. internal readonly ExtensionMethodCache _extensionMethods;
  48. public ITypeConverter ClrTypeConverter { get; internal set; }
  49. // cache of types used when resolving CLR type names
  50. internal readonly Dictionary<string, Type> TypeCache = new();
  51. // shared frozen version
  52. internal readonly PropertyDescriptor _callerCalleeArgumentsThrowerConfigurable;
  53. internal readonly PropertyDescriptor _callerCalleeArgumentsThrowerNonConfigurable;
  54. internal readonly JintCallStack CallStack;
  55. // needed in initial engine setup, for example CLR function construction
  56. internal Intrinsics _originalIntrinsics;
  57. internal Host _host;
  58. /// <summary>
  59. /// Constructs a new engine instance.
  60. /// </summary>
  61. public Engine() : this((Action<Options>) null)
  62. {
  63. }
  64. /// <summary>
  65. /// Constructs a new engine instance and allows customizing options.
  66. /// </summary>
  67. public Engine(Action<Options> options)
  68. : this((engine, opts) => options?.Invoke(opts))
  69. {
  70. }
  71. /// <summary>
  72. /// Constructs a new engine with a custom <see cref="Options"/> instance.
  73. /// </summary>
  74. public Engine(Options options) : this((e, o) => e.Options = options)
  75. {
  76. }
  77. /// <summary>
  78. /// Constructs a new engine instance and allows customizing options.
  79. /// </summary>
  80. /// <remarks>The provided engine instance in callback is not guaranteed to be fully configured</remarks>
  81. public Engine(Action<Engine, Options> options)
  82. {
  83. _executionContexts = new ExecutionContextStack(2);
  84. _callerCalleeArgumentsThrowerConfigurable = new GetSetPropertyDescriptor.ThrowerPropertyDescriptor(this,
  85. PropertyFlag.Configurable | PropertyFlag.CustomJsValue,
  86. "'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them");
  87. _callerCalleeArgumentsThrowerNonConfigurable = new GetSetPropertyDescriptor.ThrowerPropertyDescriptor(this,
  88. PropertyFlag.CustomJsValue,
  89. "'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them");
  90. Options = new Options();
  91. options?.Invoke(this, Options);
  92. Reset();
  93. // gather some options as fields for faster checks
  94. _isDebugMode = Options.Debugger.Enabled;
  95. _isStrict = Options.Strict;
  96. _objectConverters = Options.Interop.ObjectConverters.Count > 0
  97. ? Options.Interop.ObjectConverters.ToArray()
  98. : null;
  99. _constraints = Options.Constraints.Constraints.ToArray();
  100. _referenceResolver = Options.ReferenceResolver;
  101. _extensionMethods = ExtensionMethodCache.Build(Options.Interop.ExtensionMethodTypes);
  102. CallStack = new JintCallStack(Options.Constraints.MaxRecursionDepth >= 0);
  103. _referencePool = new ReferencePool();
  104. _argumentsInstancePool = new ArgumentsInstancePool(this);
  105. _jsValueArrayPool = new JsValueArrayPool();
  106. Options.Apply(this);
  107. }
  108. private void Reset()
  109. {
  110. _host = Options.Host.Factory(this);
  111. _host.Initialize(this);
  112. }
  113. internal ref readonly ExecutionContext ExecutionContext
  114. {
  115. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  116. get => ref _executionContexts.Peek();
  117. }
  118. // temporary state for realm so that we can easily pass it to functions while still not
  119. // having a proper execution context established
  120. internal Realm _realmInConstruction;
  121. public Realm Realm => _realmInConstruction ?? ExecutionContext.Realm;
  122. internal GlobalSymbolRegistry GlobalSymbolRegistry { get; } = new();
  123. internal long CurrentMemoryUsage { get; private set; }
  124. internal Options Options
  125. {
  126. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  127. get;
  128. private set;
  129. }
  130. public DebugHandler DebugHandler => _debugHandler ??= new DebugHandler(this);
  131. internal ExecutionContext EnterExecutionContext(
  132. EnvironmentRecord lexicalEnvironment,
  133. EnvironmentRecord variableEnvironment,
  134. Realm realm,
  135. PrivateEnvironmentRecord privateEnvironment)
  136. {
  137. var context = new ExecutionContext(
  138. lexicalEnvironment,
  139. variableEnvironment,
  140. privateEnvironment,
  141. realm,
  142. null);
  143. _executionContexts.Push(context);
  144. return context;
  145. }
  146. internal ExecutionContext EnterExecutionContext(ExecutionContext context)
  147. {
  148. _executionContexts.Push(context);
  149. return context;
  150. }
  151. public Engine SetValue(JsValue name, Delegate value)
  152. {
  153. Realm.GlobalObject.FastAddProperty(name, new DelegateWrapper(this, value), true, false, true);
  154. return this;
  155. }
  156. public Engine SetValue(JsValue name, string value)
  157. {
  158. return SetValue(name, new JsString(value));
  159. }
  160. public Engine SetValue(JsValue name, double value)
  161. {
  162. return SetValue(name, JsNumber.Create(value));
  163. }
  164. public Engine SetValue(JsValue name, int value)
  165. {
  166. return SetValue(name, JsNumber.Create(value));
  167. }
  168. public Engine SetValue(JsValue name, bool value)
  169. {
  170. return SetValue(name, value ? JsBoolean.True : JsBoolean.False);
  171. }
  172. public Engine SetValue(JsValue name, JsValue value)
  173. {
  174. Realm.GlobalObject.Set(name, value);
  175. return this;
  176. }
  177. public Engine SetValue(JsValue name, object obj)
  178. {
  179. var value = obj is Type t
  180. ? TypeReference.CreateTypeReference(this, t)
  181. : JsValue.FromObject(this, obj);
  182. return SetValue(name, value);
  183. }
  184. internal void LeaveExecutionContext()
  185. {
  186. _executionContexts.Pop();
  187. }
  188. /// <summary>
  189. /// Initializes the statements count
  190. /// </summary>
  191. public void ResetConstraints()
  192. {
  193. foreach (var constraint in _constraints)
  194. {
  195. constraint.Reset();
  196. }
  197. }
  198. /// <summary>
  199. /// Initializes list of references of called functions
  200. /// </summary>
  201. public void ResetCallStack()
  202. {
  203. CallStack.Clear();
  204. }
  205. public JsValue Evaluate(string source)
  206. => Execute(source, DefaultParserOptions)._completionValue;
  207. public JsValue Evaluate(string source, ParserOptions parserOptions)
  208. => Execute(source, parserOptions)._completionValue;
  209. public JsValue Evaluate(Script script)
  210. => Execute(script)._completionValue;
  211. public Engine Execute(string source)
  212. => Execute(source, DefaultParserOptions);
  213. public Engine Execute(string source, ParserOptions parserOptions)
  214. => Execute(new JavaScriptParser(source, parserOptions).ParseScript());
  215. public Engine Execute(Script script)
  216. {
  217. ResetConstraints();
  218. ResetLastStatement();
  219. using (new StrictModeScope(_isStrict || script.Strict))
  220. {
  221. GlobalDeclarationInstantiation(
  222. script,
  223. Realm.GlobalEnv);
  224. var list = new JintStatementList(this, null, script.Body);
  225. Completion result;
  226. try
  227. {
  228. result = list.Execute();
  229. }
  230. catch
  231. {
  232. // unhandled exception
  233. ResetCallStack();
  234. throw;
  235. }
  236. if (result.Type == CompletionType.Throw)
  237. {
  238. var ex = new JavaScriptException(result.GetValueOrDefault())
  239. .SetCallstack(this, result.Location);
  240. ResetCallStack();
  241. throw ex;
  242. }
  243. // TODO what about callstack and thrown exceptions?
  244. RunAvailableContinuations(_eventLoop);
  245. _completionValue = result.GetValueOrDefault();
  246. }
  247. return this;
  248. }
  249. /// <summary>
  250. /// EXPERIMENTAL! Subject to change.
  251. ///
  252. /// Registers a promise within the currently running EventLoop (has to be called within "ExecuteWithEventLoop" call).
  253. /// Note that ExecuteWithEventLoop will not trigger "onFinished" callback until ALL manual promises are settled.
  254. ///
  255. /// NOTE: that resolve and reject need to be called withing the same thread as "ExecuteWithEventLoop".
  256. /// The API assumes that the Engine is called from a single thread.
  257. /// </summary>
  258. /// <returns>a Promise instance and functions to either resolve or reject it</returns>
  259. public ManualPromise RegisterPromise()
  260. {
  261. var promise = new PromiseInstance(this)
  262. {
  263. _prototype = Realm.Intrinsics.Promise.PrototypeObject
  264. };
  265. var (resolve, reject) = promise.CreateResolvingFunctions();
  266. Action<JsValue> SettleWith(FunctionInstance settle) => value =>
  267. {
  268. settle.Call(JsValue.Undefined, new[] {value});
  269. RunAvailableContinuations(_eventLoop);
  270. };
  271. return new ManualPromise(promise, SettleWith(resolve), SettleWith(reject));
  272. }
  273. internal void AddToEventLoop(Action continuation)
  274. {
  275. _eventLoop.Events.Enqueue(continuation);
  276. }
  277. private static void RunAvailableContinuations(EventLoop loop)
  278. {
  279. var queue = loop.Events;
  280. while (true)
  281. {
  282. if (queue.Count == 0)
  283. {
  284. return;
  285. }
  286. var nextContinuation = queue.Dequeue();
  287. // note that continuation can enqueue new events
  288. nextContinuation();
  289. }
  290. }
  291. private void ResetLastStatement()
  292. {
  293. _lastSyntaxNode = null;
  294. }
  295. internal void RunBeforeExecuteStatementChecks(Statement statement)
  296. {
  297. // Avoid allocating the enumerator because we run this loop very often.
  298. foreach (var constraint in _constraints)
  299. {
  300. constraint.Check();
  301. }
  302. if (_isDebugMode)
  303. {
  304. DebugHandler.OnStep(statement);
  305. }
  306. }
  307. /// <summary>
  308. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.7.1
  309. /// </summary>
  310. public JsValue GetValue(object value)
  311. {
  312. return GetValue(value, false);
  313. }
  314. internal JsValue GetValue(object value, bool returnReferenceToPool)
  315. {
  316. if (value is JsValue jsValue)
  317. {
  318. return jsValue;
  319. }
  320. if (!(value is Reference reference))
  321. {
  322. return ((Completion) value).Value;
  323. }
  324. return GetValue(reference, returnReferenceToPool);
  325. }
  326. internal JsValue GetValue(Reference reference, bool returnReferenceToPool)
  327. {
  328. var baseValue = reference.GetBase();
  329. if (baseValue.IsUndefined())
  330. {
  331. if (_referenceResolver.TryUnresolvableReference(this, reference, out JsValue val))
  332. {
  333. return val;
  334. }
  335. ExceptionHelper.ThrowReferenceError(Realm, reference);
  336. }
  337. if ((baseValue._type & InternalTypes.ObjectEnvironmentRecord) == 0
  338. && _referenceResolver.TryPropertyReference(this, reference, ref baseValue))
  339. {
  340. return baseValue;
  341. }
  342. if (reference.IsPropertyReference())
  343. {
  344. var property = reference.GetReferencedName();
  345. if (returnReferenceToPool)
  346. {
  347. _referencePool.Return(reference);
  348. }
  349. if (baseValue.IsObject())
  350. {
  351. var o = TypeConverter.ToObject(Realm, baseValue);
  352. var v = o.Get(property, reference.GetThisValue());
  353. return v;
  354. }
  355. else
  356. {
  357. // check if we are accessing a string, boxing operation can be costly to do index access
  358. // we have good chance to have fast path with integer or string indexer
  359. ObjectInstance o = null;
  360. if ((property._type & (InternalTypes.String | InternalTypes.Integer)) != 0
  361. && baseValue is JsString s
  362. && TryHandleStringValue(property, s, ref o, out var jsValue))
  363. {
  364. return jsValue;
  365. }
  366. if (o is null)
  367. {
  368. o = TypeConverter.ToObject(Realm, baseValue);
  369. }
  370. var desc = o.GetProperty(property);
  371. if (desc == PropertyDescriptor.Undefined)
  372. {
  373. return JsValue.Undefined;
  374. }
  375. if (desc.IsDataDescriptor())
  376. {
  377. return desc.Value;
  378. }
  379. var getter = desc.Get;
  380. if (getter.IsUndefined())
  381. {
  382. return Undefined.Instance;
  383. }
  384. var callable = (ICallable) getter.AsObject();
  385. return callable.Call(baseValue, Arguments.Empty);
  386. }
  387. }
  388. var record = baseValue as EnvironmentRecord;
  389. if (record is null)
  390. {
  391. ExceptionHelper.ThrowArgumentException();
  392. }
  393. var bindingValue = record.GetBindingValue(reference.GetReferencedName().ToString(), reference.IsStrictReference());
  394. if (returnReferenceToPool)
  395. {
  396. _referencePool.Return(reference);
  397. }
  398. return bindingValue;
  399. }
  400. private bool TryHandleStringValue(JsValue property, JsString s, ref ObjectInstance o, out JsValue jsValue)
  401. {
  402. if (property == CommonProperties.Length)
  403. {
  404. jsValue = JsNumber.Create((uint) s.Length);
  405. return true;
  406. }
  407. if (property is JsNumber number && number.IsInteger())
  408. {
  409. var index = number.AsInteger();
  410. var str = s._value;
  411. if (index < 0 || index >= str.Length)
  412. {
  413. jsValue = JsValue.Undefined;
  414. return true;
  415. }
  416. jsValue = JsString.Create(str[index]);
  417. return true;
  418. }
  419. if (property is JsString propertyString
  420. && propertyString._value.Length > 0
  421. && char.IsLower(propertyString._value[0]))
  422. {
  423. // trying to find property that's always in prototype
  424. o = Realm.Intrinsics.String.PrototypeObject;
  425. }
  426. jsValue = JsValue.Undefined;
  427. return false;
  428. }
  429. /// <summary>
  430. /// https://tc39.es/ecma262/#sec-putvalue
  431. /// </summary>
  432. internal void PutValue(Reference reference, JsValue value)
  433. {
  434. var baseValue = reference.GetBase();
  435. if (reference.IsUnresolvableReference())
  436. {
  437. if (reference.IsStrictReference())
  438. {
  439. ExceptionHelper.ThrowReferenceError(Realm, reference);
  440. }
  441. Realm.GlobalObject.Set(reference.GetReferencedName(), value, throwOnError: false);
  442. }
  443. else if (reference.IsPropertyReference())
  444. {
  445. if (reference.HasPrimitiveBase())
  446. {
  447. baseValue = TypeConverter.ToObject(Realm, baseValue);
  448. }
  449. var succeeded = baseValue.Set(reference.GetReferencedName(), value, reference.GetThisValue());
  450. if (!succeeded && reference.IsStrictReference())
  451. {
  452. ExceptionHelper.ThrowTypeError(Realm);
  453. }
  454. }
  455. else
  456. {
  457. ((EnvironmentRecord) baseValue).SetMutableBinding(TypeConverter.ToString(reference.GetReferencedName()),
  458. value, reference.IsStrictReference());
  459. }
  460. }
  461. /// <summary>
  462. /// http://www.ecma-international.org/ecma-262/6.0/#sec-initializereferencedbinding
  463. /// </summary>
  464. public void InitializeReferenceBinding(Reference reference, JsValue value)
  465. {
  466. var baseValue = (EnvironmentRecord) reference.GetBase();
  467. baseValue.InitializeBinding(TypeConverter.ToString(reference.GetReferencedName()), value);
  468. }
  469. /// <summary>
  470. /// Invoke the current value as function.
  471. /// </summary>
  472. /// <param name="propertyName">The name of the function to call.</param>
  473. /// <param name="arguments">The arguments of the function call.</param>
  474. /// <returns>The value returned by the function call.</returns>
  475. public JsValue Invoke(string propertyName, params object[] arguments)
  476. {
  477. return Invoke(propertyName, null, arguments);
  478. }
  479. /// <summary>
  480. /// Invoke the current value as function.
  481. /// </summary>
  482. /// <param name="propertyName">The name of the function to call.</param>
  483. /// <param name="thisObj">The this value inside the function call.</param>
  484. /// <param name="arguments">The arguments of the function call.</param>
  485. /// <returns>The value returned by the function call.</returns>
  486. public JsValue Invoke(string propertyName, object thisObj, object[] arguments)
  487. {
  488. var value = GetValue(propertyName);
  489. return Invoke(value, thisObj, arguments);
  490. }
  491. /// <summary>
  492. /// Invoke the current value as function.
  493. /// </summary>
  494. /// <param name="value">The function to call.</param>
  495. /// <param name="arguments">The arguments of the function call.</param>
  496. /// <returns>The value returned by the function call.</returns>
  497. public JsValue Invoke(JsValue value, params object[] arguments)
  498. {
  499. return Invoke(value, null, arguments);
  500. }
  501. /// <summary>
  502. /// Invoke the current value as function.
  503. /// </summary>
  504. /// <param name="value">The function to call.</param>
  505. /// <param name="thisObj">The this value inside the function call.</param>
  506. /// <param name="arguments">The arguments of the function call.</param>
  507. /// <returns>The value returned by the function call.</returns>
  508. public JsValue Invoke(JsValue value, object thisObj, object[] arguments)
  509. {
  510. var callable = value as ICallable;
  511. if (callable is null)
  512. {
  513. ExceptionHelper.ThrowTypeError(Realm, "Can only invoke functions");
  514. }
  515. var items = _jsValueArrayPool.RentArray(arguments.Length);
  516. for (int i = 0; i < arguments.Length; ++i)
  517. {
  518. items[i] = JsValue.FromObject(this, arguments[i]);
  519. }
  520. var result = callable.Call(JsValue.FromObject(this, thisObj), items);
  521. _jsValueArrayPool.ReturnArray(items);
  522. return result;
  523. }
  524. /// <summary>
  525. /// https://tc39.es/ecma262/#sec-invoke
  526. /// </summary>
  527. internal JsValue Invoke(JsValue v, JsValue p, JsValue[] arguments)
  528. {
  529. var func = GetV(v, p);
  530. var callable = func as ICallable;
  531. if (callable is null)
  532. {
  533. ExceptionHelper.ThrowTypeErrorNoEngine("Can only invoke functions");
  534. }
  535. return callable.Call(v, arguments);
  536. }
  537. /// <summary>
  538. /// https://tc39.es/ecma262/#sec-getv
  539. /// </summary>
  540. internal JsValue GetV(JsValue v, JsValue p)
  541. {
  542. var o = TypeConverter.ToObject(Realm, v);
  543. return o.Get(p);
  544. }
  545. /// <summary>
  546. /// Gets a named value from the Global scope.
  547. /// </summary>
  548. /// <param name="propertyName">The name of the property to return.</param>
  549. public JsValue GetValue(string propertyName)
  550. {
  551. return GetValue(Realm.GlobalObject, new JsString(propertyName));
  552. }
  553. /// <summary>
  554. /// Gets the last evaluated <see cref="Node"/>.
  555. /// </summary>
  556. internal Node GetLastSyntaxNode()
  557. {
  558. return _lastSyntaxNode;
  559. }
  560. /// <summary>
  561. /// Gets a named value from the specified scope.
  562. /// </summary>
  563. /// <param name="scope">The scope to get the property from.</param>
  564. /// <param name="property">The name of the property to return.</param>
  565. public JsValue GetValue(JsValue scope, JsValue property)
  566. {
  567. var reference = _referencePool.Rent(scope, property, _isStrict, thisValue: null);
  568. var jsValue = GetValue(reference, false);
  569. _referencePool.Return(reference);
  570. return jsValue;
  571. }
  572. /// <summary>
  573. /// https://tc39.es/ecma262/#sec-resolvebinding
  574. /// </summary>
  575. internal Reference ResolveBinding(string name, EnvironmentRecord env = null)
  576. {
  577. env ??= ExecutionContext.LexicalEnvironment;
  578. return GetIdentifierReference(env, name, StrictModeScope.IsStrictModeCode);
  579. }
  580. private Reference GetIdentifierReference(EnvironmentRecord env, string name, bool strict)
  581. {
  582. if (env is null)
  583. {
  584. return new Reference(JsValue.Undefined, name, strict);
  585. }
  586. var envRec = env;
  587. if (envRec.HasBinding(name))
  588. {
  589. return new Reference(envRec, name, strict);
  590. }
  591. return GetIdentifierReference(env._outerEnv, name, strict);
  592. }
  593. /// <summary>
  594. /// https://tc39.es/ecma262/#sec-getnewtarget
  595. /// </summary>
  596. internal JsValue GetNewTarget(EnvironmentRecord thisEnvironment = null)
  597. {
  598. // we can take as argument if caller site has already determined the value, otherwise resolve
  599. thisEnvironment ??= ExecutionContext.GetThisEnvironment();
  600. return thisEnvironment.NewTarget;
  601. }
  602. /// <summary>
  603. /// https://tc39.es/ecma262/#sec-resolvethisbinding
  604. /// </summary>
  605. internal JsValue ResolveThisBinding()
  606. {
  607. var envRec = ExecutionContext.GetThisEnvironment();
  608. return envRec.GetThisBinding();
  609. }
  610. /// <summary>
  611. /// https://tc39.es/ecma262/#sec-globaldeclarationinstantiation
  612. /// </summary>
  613. private void GlobalDeclarationInstantiation(
  614. Script script,
  615. GlobalEnvironmentRecord env)
  616. {
  617. var hoistingScope = HoistingScope.GetProgramLevelDeclarations(script);
  618. var functionDeclarations = hoistingScope._functionDeclarations;
  619. var varDeclarations = hoistingScope._variablesDeclarations;
  620. var lexDeclarations = hoistingScope._lexicalDeclarations;
  621. var functionToInitialize = new LinkedList<JintFunctionDefinition>();
  622. var declaredFunctionNames = new HashSet<string>();
  623. var declaredVarNames = new List<string>();
  624. var realm = Realm;
  625. if (functionDeclarations != null)
  626. {
  627. for (var i = functionDeclarations.Count - 1; i >= 0; i--)
  628. {
  629. var d = functionDeclarations[i];
  630. var fn = d.Id.Name;
  631. if (!declaredFunctionNames.Contains(fn))
  632. {
  633. var fnDefinable = env.CanDeclareGlobalFunction(fn);
  634. if (!fnDefinable)
  635. {
  636. ExceptionHelper.ThrowTypeError(realm);
  637. }
  638. declaredFunctionNames.Add(fn);
  639. functionToInitialize.AddFirst(new JintFunctionDefinition(this, d));
  640. }
  641. }
  642. }
  643. var boundNames = new List<string>();
  644. if (varDeclarations != null)
  645. {
  646. for (var i = 0; i < varDeclarations.Count; i++)
  647. {
  648. var d = varDeclarations[i];
  649. boundNames.Clear();
  650. d.GetBoundNames(boundNames);
  651. for (var j = 0; j < boundNames.Count; j++)
  652. {
  653. var vn = boundNames[j];
  654. if (env.HasLexicalDeclaration(vn))
  655. {
  656. ExceptionHelper.ThrowSyntaxError(realm, $"Identifier '{vn}' has already been declared");
  657. }
  658. if (!declaredFunctionNames.Contains(vn))
  659. {
  660. var vnDefinable = env.CanDeclareGlobalVar(vn);
  661. if (!vnDefinable)
  662. {
  663. ExceptionHelper.ThrowTypeError(realm);
  664. }
  665. declaredVarNames.Add(vn);
  666. }
  667. }
  668. }
  669. }
  670. if (lexDeclarations != null)
  671. {
  672. for (var i = 0; i < lexDeclarations.Count; i++)
  673. {
  674. var d = lexDeclarations[i];
  675. boundNames.Clear();
  676. d.GetBoundNames(boundNames);
  677. for (var j = 0; j < boundNames.Count; j++)
  678. {
  679. var dn = boundNames[j];
  680. if (env.HasVarDeclaration(dn)
  681. || env.HasLexicalDeclaration(dn)
  682. || env.HasRestrictedGlobalProperty(dn))
  683. {
  684. ExceptionHelper.ThrowSyntaxError(realm, $"Identifier '{dn}' has already been declared");
  685. }
  686. if (d.Kind == VariableDeclarationKind.Const)
  687. {
  688. env.CreateImmutableBinding(dn, strict: true);
  689. }
  690. else
  691. {
  692. env.CreateMutableBinding(dn, canBeDeleted: false);
  693. }
  694. }
  695. }
  696. }
  697. foreach (var f in functionToInitialize)
  698. {
  699. var fn = f.Function.Id!.Name;
  700. if (env.HasLexicalDeclaration(fn))
  701. {
  702. ExceptionHelper.ThrowSyntaxError(realm, $"Identifier '{fn}' has already been declared");
  703. }
  704. var fo = realm.Intrinsics.Function.InstantiateFunctionObject(f, env);
  705. env.CreateGlobalFunctionBinding(fn, fo, canBeDeleted: false);
  706. }
  707. for (var i = 0; i < declaredVarNames.Count; i++)
  708. {
  709. var vn = declaredVarNames[i];
  710. env.CreateGlobalVarBinding(vn, canBeDeleted: false);
  711. }
  712. }
  713. /// <summary>
  714. /// https://tc39.es/ecma262/#sec-functiondeclarationinstantiation
  715. /// </summary>
  716. internal ArgumentsInstance FunctionDeclarationInstantiation(
  717. FunctionInstance functionInstance,
  718. JsValue[] argumentsList,
  719. EnvironmentRecord env)
  720. {
  721. var func = functionInstance._functionDefinition;
  722. var envRec = (FunctionEnvironmentRecord) env;
  723. var strict = StrictModeScope.IsStrictModeCode;
  724. var configuration = func.Initialize(functionInstance);
  725. var parameterNames = configuration.ParameterNames;
  726. var hasDuplicates = configuration.HasDuplicates;
  727. var simpleParameterList = configuration.IsSimpleParameterList;
  728. var hasParameterExpressions = configuration.HasParameterExpressions;
  729. var canInitializeParametersOnDeclaration = simpleParameterList && !configuration.HasDuplicates;
  730. envRec.InitializeParameters(parameterNames, hasDuplicates,
  731. canInitializeParametersOnDeclaration ? argumentsList : null);
  732. ArgumentsInstance ao = null;
  733. if (configuration.ArgumentsObjectNeeded)
  734. {
  735. if (strict || !simpleParameterList)
  736. {
  737. ao = CreateUnmappedArgumentsObject(argumentsList);
  738. }
  739. else
  740. {
  741. // NOTE: mapped argument object is only provided for non-strict functions that don't have a rest parameter,
  742. // any parameter default value initializers, or any destructured parameters.
  743. ao = CreateMappedArgumentsObject(functionInstance, parameterNames, argumentsList, envRec, configuration.HasRestParameter);
  744. }
  745. if (strict)
  746. {
  747. envRec.CreateImmutableBindingAndInitialize(KnownKeys.Arguments, strict: false, ao);
  748. }
  749. else
  750. {
  751. envRec.CreateMutableBindingAndInitialize(KnownKeys.Arguments, canBeDeleted: false, ao);
  752. }
  753. }
  754. if (!canInitializeParametersOnDeclaration)
  755. {
  756. // slower set
  757. envRec.AddFunctionParameters(func.Function, argumentsList);
  758. }
  759. // Let iteratorRecord be CreateListIteratorRecord(argumentsList).
  760. // If hasDuplicates is true, then
  761. // Perform ? IteratorBindingInitialization for formals with iteratorRecord and undefined as arguments.
  762. // Else,
  763. // Perform ? IteratorBindingInitialization for formals with iteratorRecord and env as arguments.
  764. EnvironmentRecord varEnv;
  765. DeclarativeEnvironmentRecord varEnvRec;
  766. if (!hasParameterExpressions)
  767. {
  768. // NOTE: Only a single lexical environment is needed for the parameters and top-level vars.
  769. for (var i = 0; i < configuration.VarsToInitialize.Count; i++)
  770. {
  771. var pair = configuration.VarsToInitialize[i];
  772. envRec.CreateMutableBindingAndInitialize(pair.Name, canBeDeleted: false, JsValue.Undefined);
  773. }
  774. varEnv = env;
  775. varEnvRec = envRec;
  776. }
  777. else
  778. {
  779. // NOTE: A separate Environment Record is needed to ensure that closures created by expressions
  780. // in the formal parameter list do not have visibility of declarations in the function body.
  781. varEnv = JintEnvironment.NewDeclarativeEnvironment(this, env);
  782. varEnvRec = (DeclarativeEnvironmentRecord) varEnv;
  783. UpdateVariableEnvironment(varEnv);
  784. for (var i = 0; i < configuration.VarsToInitialize.Count; i++)
  785. {
  786. var pair = configuration.VarsToInitialize[i];
  787. var initialValue = pair.InitialValue ?? envRec.GetBindingValue(pair.Name, strict: false);
  788. varEnvRec.CreateMutableBindingAndInitialize(pair.Name, canBeDeleted: false, initialValue);
  789. }
  790. }
  791. // NOTE: Annex B.3.3.1 adds additional steps at this point.
  792. // A https://tc39.es/ecma262/#sec-web-compat-functiondeclarationinstantiation
  793. EnvironmentRecord lexEnv;
  794. if (!strict)
  795. {
  796. lexEnv = JintEnvironment.NewDeclarativeEnvironment(this, varEnv);
  797. // NOTE: Non-strict functions use a separate lexical Environment Record for top-level lexical declarations
  798. // so that a direct eval can determine whether any var scoped declarations introduced by the eval code conflict
  799. // with pre-existing top-level lexically scoped declarations. This is not needed for strict functions
  800. // because a strict direct eval always places all declarations into a new Environment Record.
  801. }
  802. else
  803. {
  804. lexEnv = varEnv;
  805. }
  806. var lexEnvRec = lexEnv;
  807. UpdateLexicalEnvironment(lexEnv);
  808. if (configuration.LexicalDeclarations.Length > 0)
  809. {
  810. InitializeLexicalDeclarations(configuration.LexicalDeclarations, lexEnvRec);
  811. }
  812. if (configuration.FunctionsToInitialize != null)
  813. {
  814. InitializeFunctions(configuration.FunctionsToInitialize, lexEnv, varEnvRec);
  815. }
  816. return ao;
  817. }
  818. private void InitializeFunctions(
  819. LinkedList<JintFunctionDefinition> functionsToInitialize,
  820. EnvironmentRecord lexEnv,
  821. DeclarativeEnvironmentRecord varEnvRec)
  822. {
  823. var realm = Realm;
  824. foreach (var f in functionsToInitialize)
  825. {
  826. var fn = f.Function.Id.Name;
  827. var fo = realm.Intrinsics.Function.InstantiateFunctionObject(f, lexEnv);
  828. varEnvRec.SetMutableBinding(fn, fo, strict: false);
  829. }
  830. }
  831. private static void InitializeLexicalDeclarations(
  832. JintFunctionDefinition.State.LexicalVariableDeclaration[] lexicalDeclarations,
  833. EnvironmentRecord lexEnvRec)
  834. {
  835. foreach (var d in lexicalDeclarations)
  836. {
  837. for (var j = 0; j < d.BoundNames.Count; j++)
  838. {
  839. var dn = d.BoundNames[j];
  840. if (d.Kind == VariableDeclarationKind.Const)
  841. {
  842. lexEnvRec.CreateImmutableBinding(dn, strict: true);
  843. }
  844. else
  845. {
  846. lexEnvRec.CreateMutableBinding(dn, canBeDeleted: false);
  847. }
  848. }
  849. }
  850. }
  851. private ArgumentsInstance CreateMappedArgumentsObject(
  852. FunctionInstance func,
  853. Key[] formals,
  854. JsValue[] argumentsList,
  855. DeclarativeEnvironmentRecord envRec,
  856. bool hasRestParameter)
  857. {
  858. return _argumentsInstancePool.Rent(func, formals, argumentsList, envRec, hasRestParameter);
  859. }
  860. private ArgumentsInstance CreateUnmappedArgumentsObject(JsValue[] argumentsList)
  861. {
  862. return _argumentsInstancePool.Rent(argumentsList);
  863. }
  864. /// <summary>
  865. /// https://tc39.es/ecma262/#sec-evaldeclarationinstantiation
  866. /// </summary>
  867. internal void EvalDeclarationInstantiation(
  868. Script script,
  869. EnvironmentRecord varEnv,
  870. EnvironmentRecord lexEnv,
  871. PrivateEnvironmentRecord privateEnv,
  872. bool strict)
  873. {
  874. var hoistingScope = HoistingScope.GetProgramLevelDeclarations(script);
  875. var lexEnvRec = (DeclarativeEnvironmentRecord) lexEnv;
  876. var varEnvRec = varEnv;
  877. var realm = Realm;
  878. if (!strict && hoistingScope._variablesDeclarations != null)
  879. {
  880. if (varEnvRec is GlobalEnvironmentRecord globalEnvironmentRecord)
  881. {
  882. ref readonly var nodes = ref hoistingScope._variablesDeclarations;
  883. for (var i = 0; i < nodes.Count; i++)
  884. {
  885. var variablesDeclaration = nodes[i];
  886. var identifier = (Identifier) variablesDeclaration.Declarations[0].Id;
  887. if (globalEnvironmentRecord.HasLexicalDeclaration(identifier.Name))
  888. {
  889. ExceptionHelper.ThrowSyntaxError(realm, "Identifier '" + identifier.Name + "' has already been declared");
  890. }
  891. }
  892. }
  893. var thisLex = lexEnv;
  894. while (!ReferenceEquals(thisLex, varEnv))
  895. {
  896. var thisEnvRec = thisLex;
  897. if (!(thisEnvRec is ObjectEnvironmentRecord))
  898. {
  899. ref readonly var nodes = ref hoistingScope._variablesDeclarations;
  900. for (var i = 0; i < nodes.Count; i++)
  901. {
  902. var variablesDeclaration = nodes[i];
  903. var identifier = (Identifier) variablesDeclaration.Declarations[0].Id;
  904. if (thisEnvRec.HasBinding(identifier.Name))
  905. {
  906. ExceptionHelper.ThrowSyntaxError(realm);
  907. }
  908. }
  909. }
  910. thisLex = thisLex._outerEnv;
  911. }
  912. }
  913. var functionDeclarations = hoistingScope._functionDeclarations;
  914. var functionsToInitialize = new LinkedList<JintFunctionDefinition>();
  915. var declaredFunctionNames = new HashSet<string>();
  916. if (functionDeclarations != null)
  917. {
  918. for (var i = functionDeclarations.Count - 1; i >= 0; i--)
  919. {
  920. var d = functionDeclarations[i];
  921. var fn = d.Id.Name;
  922. if (!declaredFunctionNames.Contains(fn))
  923. {
  924. if (varEnvRec is GlobalEnvironmentRecord ger)
  925. {
  926. var fnDefinable = ger.CanDeclareGlobalFunction(fn);
  927. if (!fnDefinable)
  928. {
  929. ExceptionHelper.ThrowTypeError(realm);
  930. }
  931. }
  932. declaredFunctionNames.Add(fn);
  933. functionsToInitialize.AddFirst(new JintFunctionDefinition(this, d));
  934. }
  935. }
  936. }
  937. var boundNames = new List<string>();
  938. var declaredVarNames = new List<string>();
  939. var variableDeclarations = hoistingScope._variablesDeclarations;
  940. var variableDeclarationsCount = variableDeclarations?.Count;
  941. for (var i = 0; i < variableDeclarationsCount; i++)
  942. {
  943. var variableDeclaration = variableDeclarations[i];
  944. boundNames.Clear();
  945. variableDeclaration.GetBoundNames(boundNames);
  946. for (var j = 0; j < boundNames.Count; j++)
  947. {
  948. var vn = boundNames[j];
  949. if (!declaredFunctionNames.Contains(vn))
  950. {
  951. if (varEnvRec is GlobalEnvironmentRecord ger)
  952. {
  953. var vnDefinable = ger.CanDeclareGlobalFunction(vn);
  954. if (!vnDefinable)
  955. {
  956. ExceptionHelper.ThrowTypeError(realm);
  957. }
  958. }
  959. declaredVarNames.Add(vn);
  960. }
  961. }
  962. }
  963. var lexicalDeclarations = hoistingScope._lexicalDeclarations;
  964. var lexicalDeclarationsCount = lexicalDeclarations?.Count;
  965. for (var i = 0; i < lexicalDeclarationsCount; i++)
  966. {
  967. boundNames.Clear();
  968. var d = lexicalDeclarations[i];
  969. d.GetBoundNames(boundNames);
  970. for (var j = 0; j < boundNames.Count; j++)
  971. {
  972. var dn = boundNames[j];
  973. if (d.Kind == VariableDeclarationKind.Const)
  974. {
  975. lexEnvRec.CreateImmutableBinding(dn, strict: true);
  976. }
  977. else
  978. {
  979. lexEnvRec.CreateMutableBinding(dn, canBeDeleted: false);
  980. }
  981. }
  982. }
  983. foreach (var f in functionsToInitialize)
  984. {
  985. var fn = f.Function.Id.Name;
  986. var fo = realm.Intrinsics.Function.InstantiateFunctionObject(f, lexEnv);
  987. if (varEnvRec is GlobalEnvironmentRecord ger)
  988. {
  989. ger.CreateGlobalFunctionBinding(fn, fo, canBeDeleted: true);
  990. }
  991. else
  992. {
  993. var bindingExists = varEnvRec.HasBinding(fn);
  994. if (!bindingExists)
  995. {
  996. varEnvRec.CreateMutableBinding(fn, canBeDeleted: true);
  997. varEnvRec.InitializeBinding(fn, fo);
  998. }
  999. else
  1000. {
  1001. varEnvRec.SetMutableBinding(fn, fo, strict: false);
  1002. }
  1003. }
  1004. }
  1005. foreach (var vn in declaredVarNames)
  1006. {
  1007. if (varEnvRec is GlobalEnvironmentRecord ger)
  1008. {
  1009. ger.CreateGlobalVarBinding(vn, true);
  1010. }
  1011. else
  1012. {
  1013. var bindingExists = varEnvRec.HasBinding(vn);
  1014. if (!bindingExists)
  1015. {
  1016. varEnvRec.CreateMutableBinding(vn, canBeDeleted: true);
  1017. varEnvRec.InitializeBinding(vn, JsValue.Undefined);
  1018. }
  1019. }
  1020. }
  1021. }
  1022. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1023. internal void UpdateLexicalEnvironment(EnvironmentRecord newEnv)
  1024. {
  1025. _executionContexts.ReplaceTopLexicalEnvironment(newEnv);
  1026. }
  1027. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1028. internal void UpdateVariableEnvironment(EnvironmentRecord newEnv)
  1029. {
  1030. _executionContexts.ReplaceTopVariableEnvironment(newEnv);
  1031. }
  1032. internal JsValue Call(ICallable callable, JsValue thisObject, JsValue[] arguments, JintExpression expression)
  1033. {
  1034. if (callable is FunctionInstance functionInstance)
  1035. {
  1036. return Call(functionInstance, thisObject, arguments, expression);
  1037. }
  1038. return callable.Call(thisObject, arguments);
  1039. }
  1040. internal JsValue Construct(IConstructor constructor, JsValue[] arguments, JsValue newTarget,
  1041. JintExpression expression)
  1042. {
  1043. if (constructor is FunctionInstance functionInstance)
  1044. {
  1045. return Construct(functionInstance, arguments, newTarget, expression);
  1046. }
  1047. return constructor.Construct(arguments, newTarget);
  1048. }
  1049. internal JsValue Call(
  1050. FunctionInstance functionInstance,
  1051. JsValue thisObject,
  1052. JsValue[] arguments,
  1053. JintExpression expression)
  1054. {
  1055. var callStackElement = new CallStackElement(functionInstance, expression, ExecutionContext);
  1056. var recursionDepth = CallStack.Push(callStackElement);
  1057. if (recursionDepth > Options.Constraints.MaxRecursionDepth)
  1058. {
  1059. // pop the current element as it was never reached
  1060. CallStack.Pop();
  1061. ExceptionHelper.ThrowRecursionDepthOverflowException(CallStack, callStackElement.ToString());
  1062. }
  1063. var result = functionInstance.Call(thisObject, arguments);
  1064. CallStack.Pop();
  1065. return result;
  1066. }
  1067. internal JsValue Construct(
  1068. FunctionInstance functionInstance,
  1069. JsValue[] arguments,
  1070. JsValue newTarget,
  1071. JintExpression expression)
  1072. {
  1073. var callStackElement = new CallStackElement(functionInstance, expression, ExecutionContext);
  1074. var recursionDepth = CallStack.Push(callStackElement);
  1075. if (recursionDepth > Options.Constraints.MaxRecursionDepth)
  1076. {
  1077. // pop the current element as it was never reached
  1078. CallStack.Pop();
  1079. ExceptionHelper.ThrowRecursionDepthOverflowException(CallStack, callStackElement.ToString());
  1080. }
  1081. var result = ((IConstructor) functionInstance).Construct(arguments, newTarget);
  1082. CallStack.Pop();
  1083. return result;
  1084. }
  1085. }
  1086. }