Engine.cs 54 KB

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