Engine.cs 58 KB

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