2
0

Engine.cs 59 KB

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