Engine.cs 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624
  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 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. ExceptionHelper.ThrowInvalidPreparedScriptArgumentException(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, new[] { 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. ExceptionHelper.ThrowReferenceError(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. ExceptionHelper.ThrowReferenceError(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. ExceptionHelper.ThrowTypeError(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. ExceptionHelper.ThrowJavaScriptException(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, JsValue[] 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. ExceptionHelper.ThrowTypeErrorNoEngine("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. ExceptionHelper.ThrowTypeError(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. ExceptionHelper.ThrowSyntaxError(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. ExceptionHelper.ThrowTypeError(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 (dn, constant) = lexNames[i];
  852. if (env.HasLexicalDeclaration(dn) || env.HasRestrictedGlobalProperty(dn))
  853. {
  854. ExceptionHelper.ThrowSyntaxError(realm, $"Identifier '{dn}' has already been declared");
  855. }
  856. if (constant)
  857. {
  858. env.CreateImmutableBinding(dn, strict: true);
  859. }
  860. else
  861. {
  862. env.CreateMutableBinding(dn, canBeDeleted: false);
  863. }
  864. }
  865. // we need to go through in reverse order to handle the hoisting correctly
  866. for (var i = functionToInitialize.Count - 1; i > -1; i--)
  867. {
  868. var f = functionToInitialize[i];
  869. Key fn = f.Name!;
  870. if (env.HasLexicalDeclaration(fn))
  871. {
  872. ExceptionHelper.ThrowSyntaxError(realm, $"Identifier '{fn}' has already been declared");
  873. }
  874. var fo = realm.Intrinsics.Function.InstantiateFunctionObject(f, env, privateEnv);
  875. env.CreateGlobalFunctionBinding(fn, fo, canBeDeleted: false);
  876. }
  877. env.CreateGlobalVarBindings(declaredVarNames, canBeDeleted: false);
  878. }
  879. /// <summary>
  880. /// https://tc39.es/ecma262/#sec-functiondeclarationinstantiation
  881. /// </summary>
  882. internal JsArguments? FunctionDeclarationInstantiation(
  883. Function function,
  884. JsValue[] argumentsList)
  885. {
  886. var calleeContext = ExecutionContext;
  887. var func = function._functionDefinition;
  888. var env = (FunctionEnvironment) ExecutionContext.LexicalEnvironment;
  889. var strict = _isStrict || StrictModeScope.IsStrictModeCode;
  890. var configuration = func!.Initialize();
  891. var parameterNames = configuration.ParameterNames;
  892. var hasDuplicates = configuration.HasDuplicates;
  893. var simpleParameterList = configuration.IsSimpleParameterList;
  894. var hasParameterExpressions = configuration.HasParameterExpressions;
  895. var canInitializeParametersOnDeclaration = simpleParameterList && !configuration.HasDuplicates;
  896. var arguments = canInitializeParametersOnDeclaration ? argumentsList : null;
  897. env.InitializeParameters(parameterNames, hasDuplicates, arguments);
  898. JsArguments? ao = null;
  899. if (configuration.ArgumentsObjectNeeded || _isDebugMode)
  900. {
  901. if (strict || !simpleParameterList)
  902. {
  903. ao = CreateUnmappedArgumentsObject(argumentsList);
  904. }
  905. else
  906. {
  907. // NOTE: mapped argument object is only provided for non-strict functions that don't have a rest parameter,
  908. // any parameter default value initializers, or any destructured parameters.
  909. ao = CreateMappedArgumentsObject(function, parameterNames, argumentsList, env, configuration.HasRestParameter);
  910. }
  911. if (strict)
  912. {
  913. env.CreateImmutableBindingAndInitialize(KnownKeys.Arguments, strict: false, ao);
  914. }
  915. else
  916. {
  917. env.CreateMutableBindingAndInitialize(KnownKeys.Arguments, canBeDeleted: false, ao);
  918. }
  919. }
  920. if (!canInitializeParametersOnDeclaration)
  921. {
  922. // slower set
  923. env.AddFunctionParameters(_activeEvaluationContext!, func.Function, argumentsList);
  924. }
  925. // Let iteratorRecord be CreateListIteratorRecord(argumentsList).
  926. // If hasDuplicates is true, then
  927. // Perform ? IteratorBindingInitialization for formals with iteratorRecord and undefined as arguments.
  928. // Else,
  929. // Perform ? IteratorBindingInitialization for formals with iteratorRecord and env as arguments.
  930. DeclarativeEnvironment varEnv;
  931. if (!hasParameterExpressions)
  932. {
  933. // NOTE: Only a single lexical environment is needed for the parameters and top-level vars.
  934. var varsToInitialize = configuration.VarsToInitialize!;
  935. for (var i = 0; i < varsToInitialize.Count; i++)
  936. {
  937. var pair = varsToInitialize[i];
  938. env.CreateMutableBindingAndInitialize(pair.Name, canBeDeleted: false, JsValue.Undefined);
  939. }
  940. varEnv = env;
  941. }
  942. else
  943. {
  944. // NOTE: A separate Environment Record is needed to ensure that closures created by expressions
  945. // in the formal parameter list do not have visibility of declarations in the function body.
  946. var varEnvRec = JintEnvironment.NewDeclarativeEnvironment(this, env);
  947. varEnv = varEnvRec;
  948. UpdateVariableEnvironment(varEnv);
  949. var varsToInitialize = configuration.VarsToInitialize!;
  950. for (var i = 0; i < varsToInitialize.Count; i++)
  951. {
  952. var pair = varsToInitialize[i];
  953. var initialValue = pair.InitialValue ?? env.GetBindingValue(pair.Name, strict: false);
  954. varEnvRec.CreateMutableBindingAndInitialize(pair.Name, canBeDeleted: false, initialValue);
  955. }
  956. }
  957. // NOTE: Annex B.3.3.1 adds additional steps at this point.
  958. // A https://tc39.es/ecma262/#sec-web-compat-functiondeclarationinstantiation
  959. DeclarativeEnvironment lexEnv;
  960. if (!strict)
  961. {
  962. lexEnv = JintEnvironment.NewDeclarativeEnvironment(this, varEnv);
  963. // NOTE: Non-strict functions use a separate lexical Environment Record for top-level lexical declarations
  964. // so that a direct eval can determine whether any var scoped declarations introduced by the eval code conflict
  965. // with pre-existing top-level lexically scoped declarations. This is not needed for strict functions
  966. // because a strict direct eval always places all declarations into a new Environment Record.
  967. }
  968. else
  969. {
  970. lexEnv = varEnv;
  971. }
  972. UpdateLexicalEnvironment(lexEnv);
  973. if (configuration.LexicalDeclarations.Count > 0)
  974. {
  975. var dictionary = lexEnv._dictionary ??= new HybridDictionary<Binding>(configuration.LexicalDeclarations.Count, checkExistingKeys: true);
  976. dictionary.EnsureCapacity(dictionary.Count + configuration.LexicalDeclarations.Count);
  977. for (var i = 0; i < configuration.LexicalDeclarations.Count; i++)
  978. {
  979. var d = configuration.LexicalDeclarations[i];
  980. if (d.IsConstantDeclaration)
  981. {
  982. dictionary[d.BoundName] = new Binding(null!, canBeDeleted: false, mutable: false, strict);
  983. }
  984. else
  985. {
  986. dictionary[d.BoundName] = new Binding(null!, canBeDeleted: false, mutable: true, strict: false);
  987. }
  988. }
  989. }
  990. if (configuration.FunctionsToInitialize != null)
  991. {
  992. var privateEnv = calleeContext.PrivateEnvironment;
  993. var realm = Realm;
  994. foreach (var f in configuration.FunctionsToInitialize)
  995. {
  996. var jintFunctionDefinition = new JintFunctionDefinition(f);
  997. var fn = jintFunctionDefinition.Name!;
  998. var fo = realm.Intrinsics.Function.InstantiateFunctionObject(jintFunctionDefinition, lexEnv, privateEnv);
  999. varEnv.SetMutableBinding(fn, fo, strict: false);
  1000. }
  1001. }
  1002. return ao;
  1003. }
  1004. private JsArguments CreateMappedArgumentsObject(
  1005. Function func,
  1006. Key[] formals,
  1007. JsValue[] argumentsList,
  1008. DeclarativeEnvironment envRec,
  1009. bool hasRestParameter)
  1010. {
  1011. return _argumentsInstancePool.Rent(func, formals, argumentsList, envRec, hasRestParameter);
  1012. }
  1013. private JsArguments CreateUnmappedArgumentsObject(JsValue[] argumentsList)
  1014. {
  1015. return _argumentsInstancePool.Rent(argumentsList);
  1016. }
  1017. /// <summary>
  1018. /// https://tc39.es/ecma262/#sec-evaldeclarationinstantiation
  1019. /// </summary>
  1020. internal void EvalDeclarationInstantiation(
  1021. Script script,
  1022. Environment varEnv,
  1023. Environment lexEnv,
  1024. PrivateEnvironment? privateEnv,
  1025. bool strict)
  1026. {
  1027. var hoistingScope = HoistingScope.GetProgramLevelDeclarations(script);
  1028. var lexEnvRec = (DeclarativeEnvironment) lexEnv;
  1029. var varEnvRec = varEnv;
  1030. var realm = Realm;
  1031. if (!strict && hoistingScope._variablesDeclarations != null)
  1032. {
  1033. if (varEnvRec is GlobalEnvironment globalEnvironmentRecord)
  1034. {
  1035. ref readonly var nodes = ref hoistingScope._variablesDeclarations;
  1036. for (var i = 0; i < nodes.Count; i++)
  1037. {
  1038. var variablesDeclaration = nodes[i];
  1039. var identifier = (Identifier) variablesDeclaration.Declarations[0].Id;
  1040. if (globalEnvironmentRecord.HasLexicalDeclaration(identifier.Name))
  1041. {
  1042. ExceptionHelper.ThrowSyntaxError(realm, "Identifier '" + identifier.Name + "' has already been declared");
  1043. }
  1044. }
  1045. }
  1046. var thisLex = lexEnv;
  1047. while (!ReferenceEquals(thisLex, varEnv))
  1048. {
  1049. var thisEnvRec = thisLex;
  1050. if (thisEnvRec is not ObjectEnvironment)
  1051. {
  1052. ref readonly var nodes = ref hoistingScope._variablesDeclarations;
  1053. for (var i = 0; i < nodes.Count; i++)
  1054. {
  1055. var variablesDeclaration = nodes[i];
  1056. var identifier = (Identifier) variablesDeclaration.Declarations[0].Id;
  1057. if (thisEnvRec!.HasBinding(identifier.Name))
  1058. {
  1059. ExceptionHelper.ThrowSyntaxError(realm);
  1060. }
  1061. }
  1062. }
  1063. thisLex = thisLex!._outerEnv;
  1064. }
  1065. }
  1066. HashSet<PrivateIdentifier>? privateIdentifiers = null;
  1067. var pointer = privateEnv;
  1068. while (pointer is not null)
  1069. {
  1070. foreach (var name in pointer.Names)
  1071. {
  1072. privateIdentifiers ??= new HashSet<PrivateIdentifier>(PrivateIdentifierNameComparer._instance);
  1073. privateIdentifiers.Add(name.Key);
  1074. }
  1075. pointer = pointer.OuterPrivateEnvironment;
  1076. }
  1077. script.AllPrivateIdentifiersValid(realm, privateIdentifiers);
  1078. var functionDeclarations = hoistingScope._functionDeclarations;
  1079. var functionsToInitialize = new LinkedList<JintFunctionDefinition>();
  1080. var declaredFunctionNames = new HashSet<Key>();
  1081. if (functionDeclarations != null)
  1082. {
  1083. for (var i = functionDeclarations.Count - 1; i >= 0; i--)
  1084. {
  1085. var d = functionDeclarations[i];
  1086. Key fn = d.Id!.Name;
  1087. if (!declaredFunctionNames.Contains(fn))
  1088. {
  1089. if (varEnvRec is GlobalEnvironment ger)
  1090. {
  1091. var fnDefinable = ger.CanDeclareGlobalFunction(fn);
  1092. if (!fnDefinable)
  1093. {
  1094. ExceptionHelper.ThrowTypeError(realm);
  1095. }
  1096. }
  1097. declaredFunctionNames.Add(fn);
  1098. functionsToInitialize.AddFirst(new JintFunctionDefinition(d));
  1099. }
  1100. }
  1101. }
  1102. var boundNames = new List<Key>();
  1103. var declaredVarNames = new List<Key>();
  1104. var variableDeclarations = hoistingScope._variablesDeclarations;
  1105. var variableDeclarationsCount = variableDeclarations?.Count;
  1106. for (var i = 0; i < variableDeclarationsCount; i++)
  1107. {
  1108. var variableDeclaration = variableDeclarations![i];
  1109. boundNames.Clear();
  1110. variableDeclaration.GetBoundNames(boundNames);
  1111. for (var j = 0; j < boundNames.Count; j++)
  1112. {
  1113. var vn = boundNames[j];
  1114. if (!declaredFunctionNames.Contains(vn))
  1115. {
  1116. if (varEnvRec is GlobalEnvironment ger)
  1117. {
  1118. var vnDefinable = ger.CanDeclareGlobalFunction(vn);
  1119. if (!vnDefinable)
  1120. {
  1121. ExceptionHelper.ThrowTypeError(realm);
  1122. }
  1123. }
  1124. declaredVarNames.Add(vn);
  1125. }
  1126. }
  1127. }
  1128. var lexicalDeclarations = hoistingScope._lexicalDeclarations;
  1129. var lexicalDeclarationsCount = lexicalDeclarations?.Count;
  1130. for (var i = 0; i < lexicalDeclarationsCount; i++)
  1131. {
  1132. boundNames.Clear();
  1133. var d = lexicalDeclarations![i];
  1134. d.GetBoundNames(boundNames);
  1135. for (var j = 0; j < boundNames.Count; j++)
  1136. {
  1137. Key dn = boundNames[j];
  1138. if (d.IsConstantDeclaration())
  1139. {
  1140. lexEnvRec.CreateImmutableBinding(dn, strict: true);
  1141. }
  1142. else
  1143. {
  1144. lexEnvRec.CreateMutableBinding(dn, canBeDeleted: false);
  1145. }
  1146. }
  1147. }
  1148. foreach (var f in functionsToInitialize)
  1149. {
  1150. var fo = realm.Intrinsics.Function.InstantiateFunctionObject(f, lexEnv, privateEnv);
  1151. if (varEnvRec is GlobalEnvironment ger)
  1152. {
  1153. ger.CreateGlobalFunctionBinding(f.Name!, fo, canBeDeleted: true);
  1154. }
  1155. else
  1156. {
  1157. Key fn = f.Name!;
  1158. var bindingExists = varEnvRec.HasBinding(fn);
  1159. if (!bindingExists)
  1160. {
  1161. varEnvRec.CreateMutableBinding(fn, canBeDeleted: true);
  1162. varEnvRec.InitializeBinding(fn, fo);
  1163. }
  1164. else
  1165. {
  1166. varEnvRec.SetMutableBinding(fn, fo, strict: false);
  1167. }
  1168. }
  1169. }
  1170. foreach (var vn in declaredVarNames)
  1171. {
  1172. if (varEnvRec is GlobalEnvironment ger)
  1173. {
  1174. ger.CreateGlobalVarBinding(vn, canBeDeleted: true);
  1175. }
  1176. else
  1177. {
  1178. var bindingExists = varEnvRec.HasBinding(vn);
  1179. if (!bindingExists)
  1180. {
  1181. varEnvRec.CreateMutableBinding(vn, canBeDeleted: true);
  1182. varEnvRec.InitializeBinding(vn, JsValue.Undefined);
  1183. }
  1184. }
  1185. }
  1186. }
  1187. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1188. internal void UpdateLexicalEnvironment(Environment newEnv)
  1189. {
  1190. _executionContexts.ReplaceTopLexicalEnvironment(newEnv);
  1191. }
  1192. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1193. internal void UpdateVariableEnvironment(Environment newEnv)
  1194. {
  1195. _executionContexts.ReplaceTopVariableEnvironment(newEnv);
  1196. }
  1197. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1198. internal void UpdatePrivateEnvironment(PrivateEnvironment? newEnv)
  1199. {
  1200. _executionContexts.ReplaceTopPrivateEnvironment(newEnv);
  1201. }
  1202. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1203. internal ref readonly ExecutionContext UpdateGenerator(GeneratorInstance generator)
  1204. {
  1205. return ref _executionContexts.ReplaceTopGenerator(generator);
  1206. }
  1207. /// <summary>
  1208. /// Invokes the named callable and returns the resulting object.
  1209. /// </summary>
  1210. /// <param name="callableName">The name of the callable.</param>
  1211. /// <param name="arguments">The arguments of the call.</param>
  1212. /// <returns>The value returned by the call.</returns>
  1213. public JsValue Call(string callableName, params JsValue[] arguments)
  1214. {
  1215. var callable = Evaluate(callableName);
  1216. return Call(callable, arguments);
  1217. }
  1218. /// <summary>
  1219. /// Invokes the callable and returns the resulting object.
  1220. /// </summary>
  1221. /// <param name="callable">The callable.</param>
  1222. /// <param name="arguments">The arguments of the call.</param>
  1223. /// <returns>The value returned by the call.</returns>
  1224. public JsValue Call(JsValue callable, params JsValue[] arguments)
  1225. => Call(callable, thisObject: JsValue.Undefined, arguments);
  1226. /// <summary>
  1227. /// Invokes the callable and returns the resulting object.
  1228. /// </summary>
  1229. /// <param name="callable">The callable.</param>
  1230. /// <param name="thisObject">Value bound as this.</param>
  1231. /// <param name="arguments">The arguments of the call.</param>
  1232. /// <returns>The value returned by the call.</returns>
  1233. public JsValue Call(JsValue callable, JsValue thisObject, JsValue[] arguments)
  1234. {
  1235. JsValue Callback()
  1236. {
  1237. if (!callable.IsCallable)
  1238. {
  1239. ExceptionHelper.ThrowArgumentException(callable + " is not callable");
  1240. }
  1241. return Call((ICallable) callable, thisObject, arguments, null);
  1242. }
  1243. return ExecuteWithConstraints(Options.Strict, Callback);
  1244. }
  1245. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1246. internal JsValue Call(ICallable callable, JsValue thisObject, JsValue[] arguments, JintExpression? expression)
  1247. {
  1248. if (callable is Function functionInstance)
  1249. {
  1250. return Call(functionInstance, thisObject, arguments, expression);
  1251. }
  1252. return callable.Call(thisObject, arguments);
  1253. }
  1254. /// <summary>
  1255. /// Calls the named constructor and returns the resulting object.
  1256. /// </summary>
  1257. /// <param name="constructorName">The name of the constructor to call.</param>
  1258. /// <param name="arguments">The arguments of the constructor call.</param>
  1259. /// <returns>The value returned by the constructor call.</returns>
  1260. public ObjectInstance Construct(string constructorName, params JsValue[] arguments)
  1261. {
  1262. var constructor = Evaluate(constructorName);
  1263. return Construct(constructor, arguments);
  1264. }
  1265. /// <summary>
  1266. /// Calls the constructor and returns the resulting object.
  1267. /// </summary>
  1268. /// <param name="constructor">The name of the constructor to call.</param>
  1269. /// <param name="arguments">The arguments of the constructor call.</param>
  1270. /// <returns>The value returned by the constructor call.</returns>
  1271. public ObjectInstance Construct(JsValue constructor, params JsValue[] arguments)
  1272. {
  1273. ObjectInstance Callback()
  1274. {
  1275. if (!constructor.IsConstructor)
  1276. {
  1277. ExceptionHelper.ThrowArgumentException(constructor + " is not a constructor");
  1278. }
  1279. return Construct(constructor, arguments, constructor, null);
  1280. }
  1281. return ExecuteWithConstraints(Options.Strict, Callback);
  1282. }
  1283. internal ObjectInstance Construct(
  1284. JsValue constructor,
  1285. JsValue[] arguments,
  1286. JsValue newTarget,
  1287. JintExpression? expression)
  1288. {
  1289. if (constructor is Function functionInstance)
  1290. {
  1291. return Construct(functionInstance, arguments, newTarget, expression);
  1292. }
  1293. return ((IConstructor) constructor).Construct(arguments, newTarget);
  1294. }
  1295. internal JsValue Call(Function function, JsValue thisObject)
  1296. => Call(function, thisObject, Arguments.Empty, null);
  1297. internal JsValue Call(
  1298. Function function,
  1299. JsValue thisObject,
  1300. JsValue[] arguments,
  1301. JintExpression? expression)
  1302. {
  1303. // ensure logic is in sync between Call, Construct, engine.Invoke and JintCallExpression!
  1304. var recursionDepth = CallStack.Push(function, expression, ExecutionContext);
  1305. if (recursionDepth > Options.Constraints.MaxRecursionDepth)
  1306. {
  1307. // automatically pops the current element as it was never reached
  1308. ExceptionHelper.ThrowRecursionDepthOverflowException(CallStack);
  1309. }
  1310. JsValue result;
  1311. try
  1312. {
  1313. result = function.Call(thisObject, arguments);
  1314. }
  1315. finally
  1316. {
  1317. // if call stack was reset due to recursive call to engine or similar, we might not have it anymore
  1318. if (CallStack.Count > 0)
  1319. {
  1320. CallStack.Pop();
  1321. }
  1322. }
  1323. return result;
  1324. }
  1325. private ObjectInstance Construct(
  1326. Function function,
  1327. JsValue[] arguments,
  1328. JsValue newTarget,
  1329. JintExpression? expression)
  1330. {
  1331. // ensure logic is in sync between Call, Construct, engine.Invoke and JintCallExpression!
  1332. var recursionDepth = CallStack.Push(function, expression, ExecutionContext);
  1333. if (recursionDepth > Options.Constraints.MaxRecursionDepth)
  1334. {
  1335. // automatically pops the current element as it was never reached
  1336. ExceptionHelper.ThrowRecursionDepthOverflowException(CallStack);
  1337. }
  1338. ObjectInstance result;
  1339. try
  1340. {
  1341. result = ((IConstructor) function).Construct(arguments, newTarget);
  1342. }
  1343. finally
  1344. {
  1345. CallStack.Pop();
  1346. }
  1347. return result;
  1348. }
  1349. internal void SignalError(ErrorDispatchInfo error)
  1350. {
  1351. _error = error;
  1352. }
  1353. internal void RegisterTypeReference(TypeReference reference)
  1354. {
  1355. _typeReferences ??= new Dictionary<Type, TypeReference>();
  1356. _typeReferences[reference.ReferenceType] = reference;
  1357. }
  1358. internal ref readonly ExecutionContext GetExecutionContext(int fromTop)
  1359. {
  1360. return ref _executionContexts.Peek(fromTop);
  1361. }
  1362. public void Dispose()
  1363. {
  1364. if (_objectWrapperCache is null)
  1365. {
  1366. return;
  1367. }
  1368. #if SUPPORTS_WEAK_TABLE_CLEAR
  1369. _objectWrapperCache.Clear();
  1370. #else
  1371. // we can expect that reflection is OK as we've been generating object wrappers already
  1372. var clearMethod = _objectWrapperCache.GetType().GetMethod("Clear", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
  1373. clearMethod?.Invoke(_objectWrapperCache, Array.Empty<object>());
  1374. #endif
  1375. }
  1376. [DebuggerDisplay("Engine")]
  1377. private sealed class EngineDebugView
  1378. {
  1379. private readonly Engine _engine;
  1380. public EngineDebugView(Engine engine)
  1381. {
  1382. _engine = engine;
  1383. }
  1384. public ObjectInstance Globals => _engine.Realm.GlobalObject;
  1385. public Options Options => _engine.Options;
  1386. public Environment VariableEnvironment => _engine.ExecutionContext.VariableEnvironment;
  1387. public Environment LexicalEnvironment => _engine.ExecutionContext.LexicalEnvironment;
  1388. }
  1389. }