2
0

Engine.cs 57 KB

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