Engine.cs 59 KB

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