2
0

Engine.cs 53 KB

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