Engine.cs 58 KB

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