Engine.cs 57 KB

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