2
0

Engine.cs 59 KB

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