Engine.cs 51 KB

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