Engine.cs 55 KB

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