2
0

Engine.cs 55 KB

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