Engine.cs 52 KB

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