Engine.cs 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434
  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 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. internal JsValue GetValue(object value)
  332. {
  333. return GetValue(value, false);
  334. }
  335. internal JsValue GetValue(object value, bool returnReferenceToPool)
  336. {
  337. if (value is JsValue jsValue)
  338. {
  339. return jsValue;
  340. }
  341. if (value is not Reference reference)
  342. {
  343. return ((Completion) value).Value;
  344. }
  345. return GetValue(reference, returnReferenceToPool);
  346. }
  347. internal JsValue GetValue(Reference reference, bool returnReferenceToPool)
  348. {
  349. var baseValue = reference.GetBase();
  350. if (baseValue.IsUndefined())
  351. {
  352. if (_referenceResolver.TryUnresolvableReference(this, reference, out var val))
  353. {
  354. return val;
  355. }
  356. ExceptionHelper.ThrowReferenceError(Realm, reference);
  357. }
  358. if ((baseValue._type & InternalTypes.ObjectEnvironmentRecord) == 0
  359. && _referenceResolver.TryPropertyReference(this, reference, ref baseValue))
  360. {
  361. return baseValue;
  362. }
  363. if (reference.IsPropertyReference())
  364. {
  365. var property = reference.GetReferencedName();
  366. if (returnReferenceToPool)
  367. {
  368. _referencePool.Return(reference);
  369. }
  370. if (baseValue.IsObject())
  371. {
  372. var o = TypeConverter.ToObject(Realm, baseValue);
  373. var v = o.Get(property, reference.GetThisValue());
  374. return v;
  375. }
  376. else
  377. {
  378. // check if we are accessing a string, boxing operation can be costly to do index access
  379. // we have good chance to have fast path with integer or string indexer
  380. ObjectInstance? o = null;
  381. if ((property._type & (InternalTypes.String | InternalTypes.Integer)) != 0
  382. && baseValue is JsString s
  383. && TryHandleStringValue(property, s, ref o, out var jsValue))
  384. {
  385. return jsValue;
  386. }
  387. if (o is null)
  388. {
  389. o = TypeConverter.ToObject(Realm, baseValue);
  390. }
  391. var desc = o.GetProperty(property);
  392. if (desc == PropertyDescriptor.Undefined)
  393. {
  394. return JsValue.Undefined;
  395. }
  396. if (desc.IsDataDescriptor())
  397. {
  398. return desc.Value;
  399. }
  400. var getter = desc.Get!;
  401. if (getter.IsUndefined())
  402. {
  403. return Undefined.Instance;
  404. }
  405. var callable = (ICallable) getter.AsObject();
  406. return callable.Call(baseValue, Arguments.Empty);
  407. }
  408. }
  409. var record = baseValue as EnvironmentRecord;
  410. if (record is null)
  411. {
  412. ExceptionHelper.ThrowArgumentException();
  413. }
  414. var bindingValue = record.GetBindingValue(reference.GetReferencedName().ToString(), reference.IsStrictReference());
  415. if (returnReferenceToPool)
  416. {
  417. _referencePool.Return(reference);
  418. }
  419. return bindingValue;
  420. }
  421. private bool TryHandleStringValue(JsValue property, JsString s, ref ObjectInstance? o, out JsValue jsValue)
  422. {
  423. if (property == CommonProperties.Length)
  424. {
  425. jsValue = JsNumber.Create((uint) s.Length);
  426. return true;
  427. }
  428. if (property is JsNumber number && number.IsInteger())
  429. {
  430. var index = number.AsInteger();
  431. var str = s._value;
  432. if (index < 0 || index >= str.Length)
  433. {
  434. jsValue = JsValue.Undefined;
  435. return true;
  436. }
  437. jsValue = JsString.Create(str[index]);
  438. return true;
  439. }
  440. if (property is JsString propertyString
  441. && propertyString._value.Length > 0
  442. && char.IsLower(propertyString._value[0]))
  443. {
  444. // trying to find property that's always in prototype
  445. o = Realm.Intrinsics.String.PrototypeObject;
  446. }
  447. jsValue = JsValue.Undefined;
  448. return false;
  449. }
  450. /// <summary>
  451. /// https://tc39.es/ecma262/#sec-putvalue
  452. /// </summary>
  453. internal void PutValue(Reference reference, JsValue value)
  454. {
  455. var baseValue = reference.GetBase();
  456. if (reference.IsUnresolvableReference())
  457. {
  458. if (reference.IsStrictReference())
  459. {
  460. ExceptionHelper.ThrowReferenceError(Realm, reference);
  461. }
  462. Realm.GlobalObject.Set(reference.GetReferencedName(), value, throwOnError: false);
  463. }
  464. else if (reference.IsPropertyReference())
  465. {
  466. if (reference.HasPrimitiveBase())
  467. {
  468. baseValue = TypeConverter.ToObject(Realm, baseValue);
  469. }
  470. var succeeded = baseValue.Set(reference.GetReferencedName(), value, reference.GetThisValue());
  471. if (!succeeded && reference.IsStrictReference())
  472. {
  473. ExceptionHelper.ThrowTypeError(Realm);
  474. }
  475. }
  476. else
  477. {
  478. ((EnvironmentRecord) baseValue).SetMutableBinding(TypeConverter.ToString(reference.GetReferencedName()),
  479. value, reference.IsStrictReference());
  480. }
  481. }
  482. /// <summary>
  483. /// Invoke the current value as function.
  484. /// </summary>
  485. /// <param name="propertyName">The name of the function to call.</param>
  486. /// <param name="arguments">The arguments of the function call.</param>
  487. /// <returns>The value returned by the function call.</returns>
  488. public JsValue Invoke(string propertyName, params object[] arguments)
  489. {
  490. return Invoke(propertyName, null, arguments);
  491. }
  492. /// <summary>
  493. /// Invoke the current value as function.
  494. /// </summary>
  495. /// <param name="propertyName">The name of the function to call.</param>
  496. /// <param name="thisObj">The this value inside the function call.</param>
  497. /// <param name="arguments">The arguments of the function call.</param>
  498. /// <returns>The value returned by the function call.</returns>
  499. public JsValue Invoke(string propertyName, object? thisObj, object[] arguments)
  500. {
  501. var value = GetValue(propertyName);
  502. return Invoke(value, thisObj, arguments);
  503. }
  504. /// <summary>
  505. /// Invoke the current value as function.
  506. /// </summary>
  507. /// <param name="value">The function to call.</param>
  508. /// <param name="arguments">The arguments of the function call.</param>
  509. /// <returns>The value returned by the function call.</returns>
  510. public JsValue Invoke(JsValue value, params object[] arguments)
  511. {
  512. return Invoke(value, null, arguments);
  513. }
  514. /// <summary>
  515. /// Invoke the current value as function.
  516. /// </summary>
  517. /// <param name="value">The function to call.</param>
  518. /// <param name="thisObj">The this value inside the function call.</param>
  519. /// <param name="arguments">The arguments of the function call.</param>
  520. /// <returns>The value returned by the function call.</returns>
  521. public JsValue Invoke(JsValue value, object? thisObj, object[] arguments)
  522. {
  523. var callable = value as ICallable;
  524. if (callable is null)
  525. {
  526. ExceptionHelper.ThrowJavaScriptException(Realm.Intrinsics.TypeError, "Can only invoke functions");
  527. }
  528. JsValue DoInvoke()
  529. {
  530. var items = _jsValueArrayPool.RentArray(arguments.Length);
  531. for (var i = 0; i < arguments.Length; ++i)
  532. {
  533. items[i] = JsValue.FromObject(this, arguments[i]);
  534. }
  535. var result = callable.Call(JsValue.FromObject(this, thisObj), items);
  536. _jsValueArrayPool.ReturnArray(items);
  537. return result;
  538. }
  539. return ExecuteWithConstraints(Options.Strict, DoInvoke);
  540. }
  541. private T ExecuteWithConstraints<T>(bool strict, Func<T> callback)
  542. {
  543. ResetConstraints();
  544. var ownsContext = _activeEvaluationContext is null;
  545. _activeEvaluationContext ??= new EvaluationContext(this);
  546. var oldStrict = _isStrict;
  547. try
  548. {
  549. _isStrict = strict;
  550. using (new StrictModeScope(_isStrict))
  551. {
  552. return callback();
  553. }
  554. }
  555. finally
  556. {
  557. if (ownsContext)
  558. {
  559. _activeEvaluationContext = null!;
  560. }
  561. _isStrict = oldStrict;
  562. ResetConstraints();
  563. _agent.ClearKeptObjects();
  564. }
  565. }
  566. /// <summary>
  567. /// https://tc39.es/ecma262/#sec-invoke
  568. /// </summary>
  569. internal JsValue Invoke(JsValue v, JsValue p, JsValue[] arguments)
  570. {
  571. var ownsContext = _activeEvaluationContext is null;
  572. _activeEvaluationContext ??= new EvaluationContext(this);
  573. try
  574. {
  575. var func = GetV(v, p);
  576. var callable = func as ICallable;
  577. if (callable is null)
  578. {
  579. ExceptionHelper.ThrowTypeErrorNoEngine("Can only invoke functions");
  580. }
  581. return callable.Call(v, arguments);
  582. }
  583. finally
  584. {
  585. if (ownsContext)
  586. {
  587. _activeEvaluationContext = null!;
  588. }
  589. }
  590. }
  591. /// <summary>
  592. /// https://tc39.es/ecma262/#sec-getv
  593. /// </summary>
  594. private JsValue GetV(JsValue v, JsValue p)
  595. {
  596. var o = TypeConverter.ToObject(Realm, v);
  597. return o.Get(p);
  598. }
  599. /// <summary>
  600. /// Gets a named value from the Global scope.
  601. /// </summary>
  602. /// <param name="propertyName">The name of the property to return.</param>
  603. public JsValue GetValue(string propertyName)
  604. {
  605. return GetValue(Realm.GlobalObject, new JsString(propertyName));
  606. }
  607. /// <summary>
  608. /// Gets the last evaluated <see cref="Node"/>.
  609. /// </summary>
  610. internal SyntaxElement? GetLastSyntaxElement()
  611. {
  612. return _activeEvaluationContext?.LastSyntaxElement;
  613. }
  614. /// <summary>
  615. /// Gets a named value from the specified scope.
  616. /// </summary>
  617. /// <param name="scope">The scope to get the property from.</param>
  618. /// <param name="property">The name of the property to return.</param>
  619. public JsValue GetValue(JsValue scope, JsValue property)
  620. {
  621. var reference = _referencePool.Rent(scope, property, _isStrict, thisValue: null);
  622. var jsValue = GetValue(reference, false);
  623. _referencePool.Return(reference);
  624. return jsValue;
  625. }
  626. /// <summary>
  627. /// https://tc39.es/ecma262/#sec-resolvebinding
  628. /// </summary>
  629. internal Reference ResolveBinding(string name, EnvironmentRecord? env = null)
  630. {
  631. env ??= ExecutionContext.LexicalEnvironment;
  632. return GetIdentifierReference(env, name, StrictModeScope.IsStrictModeCode);
  633. }
  634. private static Reference GetIdentifierReference(EnvironmentRecord? env, string name, bool strict)
  635. {
  636. if (env is null)
  637. {
  638. return new Reference(JsValue.Undefined, name, strict);
  639. }
  640. var envRec = env;
  641. if (envRec.HasBinding(name))
  642. {
  643. return new Reference(envRec, name, strict);
  644. }
  645. return GetIdentifierReference(env._outerEnv, name, strict);
  646. }
  647. /// <summary>
  648. /// https://tc39.es/ecma262/#sec-getnewtarget
  649. /// </summary>
  650. internal JsValue GetNewTarget(EnvironmentRecord? thisEnvironment = null)
  651. {
  652. // we can take as argument if caller site has already determined the value, otherwise resolve
  653. thisEnvironment ??= ExecutionContext.GetThisEnvironment();
  654. return thisEnvironment.NewTarget ?? JsValue.Undefined;
  655. }
  656. /// <summary>
  657. /// https://tc39.es/ecma262/#sec-resolvethisbinding
  658. /// </summary>
  659. internal JsValue ResolveThisBinding()
  660. {
  661. var envRec = ExecutionContext.GetThisEnvironment();
  662. return envRec.GetThisBinding();
  663. }
  664. /// <summary>
  665. /// https://tc39.es/ecma262/#sec-globaldeclarationinstantiation
  666. /// </summary>
  667. private void GlobalDeclarationInstantiation(
  668. Script script,
  669. GlobalEnvironmentRecord env)
  670. {
  671. var strict = _isStrict || StrictModeScope.IsStrictModeCode;
  672. var hoistingScope = HoistingScope.GetProgramLevelDeclarations(strict, script);
  673. var functionDeclarations = hoistingScope._functionDeclarations;
  674. var varDeclarations = hoistingScope._variablesDeclarations;
  675. var lexDeclarations = hoistingScope._lexicalDeclarations;
  676. var functionToInitialize = new LinkedList<JintFunctionDefinition>();
  677. var declaredFunctionNames = new HashSet<string>();
  678. var declaredVarNames = new List<string>();
  679. var realm = Realm;
  680. if (functionDeclarations != null)
  681. {
  682. for (var i = functionDeclarations.Count - 1; i >= 0; i--)
  683. {
  684. var d = functionDeclarations[i];
  685. var fn = d.Id!.Name;
  686. if (!declaredFunctionNames.Contains(fn))
  687. {
  688. var fnDefinable = env.CanDeclareGlobalFunction(fn);
  689. if (!fnDefinable)
  690. {
  691. ExceptionHelper.ThrowTypeError(realm, "Cannot declare global function " + fn);
  692. }
  693. declaredFunctionNames.Add(fn);
  694. functionToInitialize.AddFirst(new JintFunctionDefinition(d));
  695. }
  696. }
  697. }
  698. var boundNames = new List<string>();
  699. if (varDeclarations != null)
  700. {
  701. for (var i = 0; i < varDeclarations.Count; i++)
  702. {
  703. var d = varDeclarations[i];
  704. boundNames.Clear();
  705. d.GetBoundNames(boundNames);
  706. for (var j = 0; j < boundNames.Count; j++)
  707. {
  708. var vn = boundNames[j];
  709. if (env.HasLexicalDeclaration(vn))
  710. {
  711. ExceptionHelper.ThrowSyntaxError(realm, $"Identifier '{vn}' has already been declared");
  712. }
  713. if (!declaredFunctionNames.Contains(vn))
  714. {
  715. var vnDefinable = env.CanDeclareGlobalVar(vn);
  716. if (!vnDefinable)
  717. {
  718. ExceptionHelper.ThrowTypeError(realm);
  719. }
  720. declaredVarNames.Add(vn);
  721. }
  722. }
  723. }
  724. }
  725. PrivateEnvironmentRecord? privateEnv = null;
  726. if (lexDeclarations != null)
  727. {
  728. for (var i = 0; i < lexDeclarations.Count; i++)
  729. {
  730. var d = lexDeclarations[i];
  731. boundNames.Clear();
  732. d.GetBoundNames(boundNames);
  733. for (var j = 0; j < boundNames.Count; j++)
  734. {
  735. var dn = boundNames[j];
  736. if (env.HasVarDeclaration(dn)
  737. || env.HasLexicalDeclaration(dn)
  738. || env.HasRestrictedGlobalProperty(dn))
  739. {
  740. ExceptionHelper.ThrowSyntaxError(realm, $"Identifier '{dn}' has already been declared");
  741. }
  742. if (d.IsConstantDeclaration())
  743. {
  744. env.CreateImmutableBinding(dn, strict: true);
  745. }
  746. else
  747. {
  748. env.CreateMutableBinding(dn, canBeDeleted: false);
  749. }
  750. }
  751. }
  752. }
  753. foreach (var f in functionToInitialize)
  754. {
  755. var fn = f.Name!;
  756. if (env.HasLexicalDeclaration(fn))
  757. {
  758. ExceptionHelper.ThrowSyntaxError(realm, $"Identifier '{fn}' has already been declared");
  759. }
  760. var fo = realm.Intrinsics.Function.InstantiateFunctionObject(f, env, privateEnv);
  761. env.CreateGlobalFunctionBinding(fn, fo, canBeDeleted: false);
  762. }
  763. for (var i = 0; i < declaredVarNames.Count; i++)
  764. {
  765. var vn = declaredVarNames[i];
  766. env.CreateGlobalVarBinding(vn, canBeDeleted: false);
  767. }
  768. }
  769. /// <summary>
  770. /// https://tc39.es/ecma262/#sec-functiondeclarationinstantiation
  771. /// </summary>
  772. internal ArgumentsInstance? FunctionDeclarationInstantiation(
  773. FunctionInstance functionInstance,
  774. JsValue[] argumentsList)
  775. {
  776. var calleeContext = ExecutionContext;
  777. var func = functionInstance._functionDefinition;
  778. var env = (FunctionEnvironmentRecord) ExecutionContext.LexicalEnvironment;
  779. var strict = _isStrict || StrictModeScope.IsStrictModeCode;
  780. var configuration = func.Initialize();
  781. var parameterNames = configuration.ParameterNames;
  782. var hasDuplicates = configuration.HasDuplicates;
  783. var simpleParameterList = configuration.IsSimpleParameterList;
  784. var hasParameterExpressions = configuration.HasParameterExpressions;
  785. var canInitializeParametersOnDeclaration = simpleParameterList && !configuration.HasDuplicates;
  786. var arguments = canInitializeParametersOnDeclaration ? argumentsList : null;
  787. env.InitializeParameters(parameterNames, hasDuplicates, arguments);
  788. ArgumentsInstance? ao = null;
  789. if (configuration.ArgumentsObjectNeeded || _isDebugMode)
  790. {
  791. if (strict || !simpleParameterList)
  792. {
  793. ao = CreateUnmappedArgumentsObject(argumentsList);
  794. }
  795. else
  796. {
  797. // NOTE: mapped argument object is only provided for non-strict functions that don't have a rest parameter,
  798. // any parameter default value initializers, or any destructured parameters.
  799. ao = CreateMappedArgumentsObject(functionInstance, parameterNames, argumentsList, env, configuration.HasRestParameter);
  800. }
  801. if (strict)
  802. {
  803. env.CreateImmutableBindingAndInitialize(KnownKeys.Arguments, strict: false, ao);
  804. }
  805. else
  806. {
  807. env.CreateMutableBindingAndInitialize(KnownKeys.Arguments, canBeDeleted: false, ao);
  808. }
  809. }
  810. if (!canInitializeParametersOnDeclaration)
  811. {
  812. // slower set
  813. env.AddFunctionParameters(_activeEvaluationContext!, func.Function, argumentsList);
  814. }
  815. // Let iteratorRecord be CreateListIteratorRecord(argumentsList).
  816. // If hasDuplicates is true, then
  817. // Perform ? IteratorBindingInitialization for formals with iteratorRecord and undefined as arguments.
  818. // Else,
  819. // Perform ? IteratorBindingInitialization for formals with iteratorRecord and env as arguments.
  820. EnvironmentRecord varEnv;
  821. if (!hasParameterExpressions)
  822. {
  823. // NOTE: Only a single lexical environment is needed for the parameters and top-level vars.
  824. var varsToInitialize = configuration.VarsToInitialize!;
  825. for (var i = 0; i < varsToInitialize.Count; i++)
  826. {
  827. var pair = varsToInitialize[i];
  828. env.CreateMutableBindingAndInitialize(pair.Name, canBeDeleted: false, JsValue.Undefined);
  829. }
  830. varEnv = env;
  831. }
  832. else
  833. {
  834. // NOTE: A separate Environment Record is needed to ensure that closures created by expressions
  835. // in the formal parameter list do not have visibility of declarations in the function body.
  836. var varEnvRec = JintEnvironment.NewDeclarativeEnvironment(this, env);
  837. varEnv = varEnvRec;
  838. UpdateVariableEnvironment(varEnv);
  839. var varsToInitialize = configuration.VarsToInitialize!;
  840. for (var i = 0; i < varsToInitialize.Count; i++)
  841. {
  842. var pair = varsToInitialize[i];
  843. var initialValue = pair.InitialValue ?? env.GetBindingValue(pair.Name, strict: false);
  844. varEnvRec.CreateMutableBindingAndInitialize(pair.Name, canBeDeleted: false, initialValue);
  845. }
  846. }
  847. // NOTE: Annex B.3.3.1 adds additional steps at this point.
  848. // A https://tc39.es/ecma262/#sec-web-compat-functiondeclarationinstantiation
  849. EnvironmentRecord lexEnv;
  850. if (!strict)
  851. {
  852. lexEnv = JintEnvironment.NewDeclarativeEnvironment(this, varEnv);
  853. // NOTE: Non-strict functions use a separate lexical Environment Record for top-level lexical declarations
  854. // so that a direct eval can determine whether any var scoped declarations introduced by the eval code conflict
  855. // with pre-existing top-level lexically scoped declarations. This is not needed for strict functions
  856. // because a strict direct eval always places all declarations into a new Environment Record.
  857. }
  858. else
  859. {
  860. lexEnv = varEnv;
  861. }
  862. UpdateLexicalEnvironment(lexEnv);
  863. if (configuration.LexicalDeclarations.Length > 0)
  864. {
  865. foreach (var d in configuration.LexicalDeclarations)
  866. {
  867. for (var j = 0; j < d.BoundNames.Count; j++)
  868. {
  869. var dn = d.BoundNames[j];
  870. if (d.IsConstantDeclaration)
  871. {
  872. lexEnv.CreateImmutableBinding(dn, strict: true);
  873. }
  874. else
  875. {
  876. lexEnv.CreateMutableBinding(dn, canBeDeleted: false);
  877. }
  878. }
  879. }
  880. }
  881. if (configuration.FunctionsToInitialize != null)
  882. {
  883. var privateEnv = calleeContext.PrivateEnvironment;
  884. var realm = Realm;
  885. foreach (var f in configuration.FunctionsToInitialize)
  886. {
  887. var fn = f.Name!;
  888. var fo = realm.Intrinsics.Function.InstantiateFunctionObject(f, lexEnv, privateEnv);
  889. varEnv.SetMutableBinding(fn, fo, strict: false);
  890. }
  891. }
  892. return ao;
  893. }
  894. private ArgumentsInstance CreateMappedArgumentsObject(
  895. FunctionInstance func,
  896. Key[] formals,
  897. JsValue[] argumentsList,
  898. DeclarativeEnvironmentRecord envRec,
  899. bool hasRestParameter)
  900. {
  901. return _argumentsInstancePool.Rent(func, formals, argumentsList, envRec, hasRestParameter);
  902. }
  903. private ArgumentsInstance CreateUnmappedArgumentsObject(JsValue[] argumentsList)
  904. {
  905. return _argumentsInstancePool.Rent(argumentsList);
  906. }
  907. /// <summary>
  908. /// https://tc39.es/ecma262/#sec-evaldeclarationinstantiation
  909. /// </summary>
  910. internal void EvalDeclarationInstantiation(
  911. Script script,
  912. EnvironmentRecord varEnv,
  913. EnvironmentRecord lexEnv,
  914. PrivateEnvironmentRecord? privateEnv,
  915. bool strict)
  916. {
  917. var hoistingScope = HoistingScope.GetProgramLevelDeclarations(strict, script);
  918. var lexEnvRec = (DeclarativeEnvironmentRecord) lexEnv;
  919. var varEnvRec = varEnv;
  920. var realm = Realm;
  921. if (!strict && hoistingScope._variablesDeclarations != null)
  922. {
  923. if (varEnvRec is GlobalEnvironmentRecord globalEnvironmentRecord)
  924. {
  925. ref readonly var nodes = ref hoistingScope._variablesDeclarations;
  926. for (var i = 0; i < nodes.Count; i++)
  927. {
  928. var variablesDeclaration = nodes[i];
  929. var identifier = (Identifier) variablesDeclaration.Declarations[0].Id;
  930. if (globalEnvironmentRecord.HasLexicalDeclaration(identifier.Name))
  931. {
  932. ExceptionHelper.ThrowSyntaxError(realm, "Identifier '" + identifier.Name + "' has already been declared");
  933. }
  934. }
  935. }
  936. var thisLex = lexEnv;
  937. while (!ReferenceEquals(thisLex, varEnv))
  938. {
  939. var thisEnvRec = thisLex;
  940. if (thisEnvRec is not ObjectEnvironmentRecord)
  941. {
  942. ref readonly var nodes = ref hoistingScope._variablesDeclarations;
  943. for (var i = 0; i < nodes.Count; i++)
  944. {
  945. var variablesDeclaration = nodes[i];
  946. var identifier = (Identifier) variablesDeclaration.Declarations[0].Id;
  947. if (thisEnvRec!.HasBinding(identifier.Name))
  948. {
  949. ExceptionHelper.ThrowSyntaxError(realm);
  950. }
  951. }
  952. }
  953. thisLex = thisLex!._outerEnv;
  954. }
  955. }
  956. var functionDeclarations = hoistingScope._functionDeclarations;
  957. var functionsToInitialize = new LinkedList<JintFunctionDefinition>();
  958. var declaredFunctionNames = new HashSet<string>();
  959. if (functionDeclarations != null)
  960. {
  961. for (var i = functionDeclarations.Count - 1; i >= 0; i--)
  962. {
  963. var d = functionDeclarations[i];
  964. var fn = d.Id!.Name;
  965. if (!declaredFunctionNames.Contains(fn))
  966. {
  967. if (varEnvRec is GlobalEnvironmentRecord ger)
  968. {
  969. var fnDefinable = ger.CanDeclareGlobalFunction(fn);
  970. if (!fnDefinable)
  971. {
  972. ExceptionHelper.ThrowTypeError(realm);
  973. }
  974. }
  975. declaredFunctionNames.Add(fn);
  976. functionsToInitialize.AddFirst(new JintFunctionDefinition(d));
  977. }
  978. }
  979. }
  980. var boundNames = new List<string>();
  981. var declaredVarNames = new List<string>();
  982. var variableDeclarations = hoistingScope._variablesDeclarations;
  983. var variableDeclarationsCount = variableDeclarations?.Count;
  984. for (var i = 0; i < variableDeclarationsCount; i++)
  985. {
  986. var variableDeclaration = variableDeclarations![i];
  987. boundNames.Clear();
  988. variableDeclaration.GetBoundNames(boundNames);
  989. for (var j = 0; j < boundNames.Count; j++)
  990. {
  991. var vn = boundNames[j];
  992. if (!declaredFunctionNames.Contains(vn))
  993. {
  994. if (varEnvRec is GlobalEnvironmentRecord ger)
  995. {
  996. var vnDefinable = ger.CanDeclareGlobalFunction(vn);
  997. if (!vnDefinable)
  998. {
  999. ExceptionHelper.ThrowTypeError(realm);
  1000. }
  1001. }
  1002. declaredVarNames.Add(vn);
  1003. }
  1004. }
  1005. }
  1006. var lexicalDeclarations = hoistingScope._lexicalDeclarations;
  1007. var lexicalDeclarationsCount = lexicalDeclarations?.Count;
  1008. for (var i = 0; i < lexicalDeclarationsCount; i++)
  1009. {
  1010. boundNames.Clear();
  1011. var d = lexicalDeclarations![i];
  1012. d.GetBoundNames(boundNames);
  1013. for (var j = 0; j < boundNames.Count; j++)
  1014. {
  1015. var dn = boundNames[j];
  1016. if (d.IsConstantDeclaration())
  1017. {
  1018. lexEnvRec.CreateImmutableBinding(dn, strict: true);
  1019. }
  1020. else
  1021. {
  1022. lexEnvRec.CreateMutableBinding(dn, canBeDeleted: false);
  1023. }
  1024. }
  1025. }
  1026. foreach (var f in functionsToInitialize)
  1027. {
  1028. var fn = f.Name!;
  1029. var fo = realm.Intrinsics.Function.InstantiateFunctionObject(f, lexEnv, privateEnv);
  1030. if (varEnvRec is GlobalEnvironmentRecord ger)
  1031. {
  1032. ger.CreateGlobalFunctionBinding(fn, fo, canBeDeleted: true);
  1033. }
  1034. else
  1035. {
  1036. var bindingExists = varEnvRec.HasBinding(fn);
  1037. if (!bindingExists)
  1038. {
  1039. varEnvRec.CreateMutableBinding(fn, canBeDeleted: true);
  1040. varEnvRec.InitializeBinding(fn, fo);
  1041. }
  1042. else
  1043. {
  1044. varEnvRec.SetMutableBinding(fn, fo, strict: false);
  1045. }
  1046. }
  1047. }
  1048. foreach (var vn in declaredVarNames)
  1049. {
  1050. if (varEnvRec is GlobalEnvironmentRecord ger)
  1051. {
  1052. ger.CreateGlobalVarBinding(vn, true);
  1053. }
  1054. else
  1055. {
  1056. var bindingExists = varEnvRec.HasBinding(vn);
  1057. if (!bindingExists)
  1058. {
  1059. varEnvRec.CreateMutableBinding(vn, canBeDeleted: true);
  1060. varEnvRec.InitializeBinding(vn, JsValue.Undefined);
  1061. }
  1062. }
  1063. }
  1064. }
  1065. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1066. internal void UpdateLexicalEnvironment(EnvironmentRecord newEnv)
  1067. {
  1068. _executionContexts.ReplaceTopLexicalEnvironment(newEnv);
  1069. }
  1070. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1071. internal void UpdateVariableEnvironment(EnvironmentRecord newEnv)
  1072. {
  1073. _executionContexts.ReplaceTopVariableEnvironment(newEnv);
  1074. }
  1075. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1076. internal void UpdatePrivateEnvironment(PrivateEnvironmentRecord? newEnv)
  1077. {
  1078. _executionContexts.ReplaceTopPrivateEnvironment(newEnv);
  1079. }
  1080. /// <summary>
  1081. /// Invokes the named callable and returns the resulting object.
  1082. /// </summary>
  1083. /// <param name="callableName">The name of the callable.</param>
  1084. /// <param name="arguments">The arguments of the call.</param>
  1085. /// <returns>The value returned by the call.</returns>
  1086. public JsValue Call(string callableName, params JsValue[] arguments)
  1087. {
  1088. var callable = Evaluate(callableName);
  1089. return Call(callable, arguments);
  1090. }
  1091. /// <summary>
  1092. /// Invokes the callable and returns the resulting object.
  1093. /// </summary>
  1094. /// <param name="callable">The callable.</param>
  1095. /// <param name="arguments">The arguments of the call.</param>
  1096. /// <returns>The value returned by the call.</returns>
  1097. public JsValue Call(JsValue callable, params JsValue[] arguments)
  1098. => Call(callable, thisObject: JsValue.Undefined, arguments);
  1099. /// <summary>
  1100. /// Invokes the callable and returns the resulting object.
  1101. /// </summary>
  1102. /// <param name="callable">The callable.</param>
  1103. /// <param name="thisObject">Value bound as this.</param>
  1104. /// <param name="arguments">The arguments of the call.</param>
  1105. /// <returns>The value returned by the call.</returns>
  1106. public JsValue Call(JsValue callable, JsValue thisObject, JsValue[] arguments)
  1107. {
  1108. JsValue Callback()
  1109. {
  1110. if (!callable.IsCallable)
  1111. {
  1112. ExceptionHelper.ThrowArgumentException(callable + " is not callable");
  1113. }
  1114. return Call((ICallable) callable, thisObject, arguments, null);
  1115. }
  1116. return ExecuteWithConstraints(Options.Strict, Callback);
  1117. }
  1118. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1119. internal JsValue Call(ICallable callable, JsValue thisObject, JsValue[] arguments, JintExpression? expression)
  1120. {
  1121. if (callable is FunctionInstance functionInstance)
  1122. {
  1123. return Call(functionInstance, thisObject, arguments, expression);
  1124. }
  1125. return callable.Call(thisObject, arguments);
  1126. }
  1127. /// <summary>
  1128. /// Calls the named constructor and returns the resulting object.
  1129. /// </summary>
  1130. /// <param name="constructorName">The name of the constructor to call.</param>
  1131. /// <param name="arguments">The arguments of the constructor call.</param>
  1132. /// <returns>The value returned by the constructor call.</returns>
  1133. public ObjectInstance Construct(string constructorName, params JsValue[] arguments)
  1134. {
  1135. var constructor = Evaluate(constructorName);
  1136. return Construct(constructor, arguments);
  1137. }
  1138. /// <summary>
  1139. /// Calls the constructor and returns the resulting object.
  1140. /// </summary>
  1141. /// <param name="constructor">The name of the constructor to call.</param>
  1142. /// <param name="arguments">The arguments of the constructor call.</param>
  1143. /// <returns>The value returned by the constructor call.</returns>
  1144. public ObjectInstance Construct(JsValue constructor, params JsValue[] arguments)
  1145. {
  1146. ObjectInstance Callback()
  1147. {
  1148. if (!constructor.IsConstructor)
  1149. {
  1150. ExceptionHelper.ThrowArgumentException(constructor + " is not a constructor");
  1151. }
  1152. return Construct(constructor, arguments, constructor, null);
  1153. }
  1154. return ExecuteWithConstraints(Options.Strict, Callback);
  1155. }
  1156. internal ObjectInstance Construct(
  1157. JsValue constructor,
  1158. JsValue[] arguments,
  1159. JsValue newTarget,
  1160. JintExpression? expression)
  1161. {
  1162. if (constructor is FunctionInstance functionInstance)
  1163. {
  1164. return Construct(functionInstance, arguments, newTarget, expression);
  1165. }
  1166. return ((IConstructor) constructor).Construct(arguments, newTarget);
  1167. }
  1168. internal JsValue Call(
  1169. FunctionInstance functionInstance,
  1170. JsValue thisObject,
  1171. JsValue[] arguments,
  1172. JintExpression? expression)
  1173. {
  1174. // ensure logic is in sync between Call, Construct and JintCallExpression!
  1175. var recursionDepth = CallStack.Push(functionInstance, expression, ExecutionContext);
  1176. if (recursionDepth > Options.Constraints.MaxRecursionDepth)
  1177. {
  1178. // automatically pops the current element as it was never reached
  1179. ExceptionHelper.ThrowRecursionDepthOverflowException(CallStack);
  1180. }
  1181. JsValue result;
  1182. try
  1183. {
  1184. result = functionInstance.Call(thisObject, arguments);
  1185. }
  1186. finally
  1187. {
  1188. // if call stack was reset due to recursive call to engine or similar, we might not have it anymore
  1189. if (CallStack.Count > 0)
  1190. {
  1191. CallStack.Pop();
  1192. }
  1193. }
  1194. return result;
  1195. }
  1196. private ObjectInstance Construct(
  1197. FunctionInstance functionInstance,
  1198. JsValue[] arguments,
  1199. JsValue newTarget,
  1200. JintExpression? expression)
  1201. {
  1202. // ensure logic is in sync between Call, Construct and JintCallExpression!
  1203. var recursionDepth = CallStack.Push(functionInstance, expression, ExecutionContext);
  1204. if (recursionDepth > Options.Constraints.MaxRecursionDepth)
  1205. {
  1206. // automatically pops the current element as it was never reached
  1207. ExceptionHelper.ThrowRecursionDepthOverflowException(CallStack);
  1208. }
  1209. ObjectInstance result;
  1210. try
  1211. {
  1212. result = ((IConstructor) functionInstance).Construct(arguments, newTarget);
  1213. }
  1214. finally
  1215. {
  1216. CallStack.Pop();
  1217. }
  1218. return result;
  1219. }
  1220. public void Dispose()
  1221. {
  1222. // no-op for now
  1223. }
  1224. }
  1225. }