Engine.cs 52 KB

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