Engine.cs 60 KB

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