Engine.cs 55 KB

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