Engine.cs 52 KB

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