Engine.cs 50 KB

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