Engine.cs 50 KB

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