Engine.cs 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623
  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. internal JsValue GetValue(Reference reference, bool returnReferenceToPool)
  473. {
  474. var baseValue = reference.Base;
  475. if (baseValue.IsUndefined())
  476. {
  477. if (_referenceResolver.TryUnresolvableReference(this, reference, out var val))
  478. {
  479. return val;
  480. }
  481. ExceptionHelper.ThrowReferenceError(Realm, reference);
  482. }
  483. if ((baseValue._type & InternalTypes.ObjectEnvironmentRecord) == InternalTypes.Empty
  484. && _referenceResolver.TryPropertyReference(this, reference, ref baseValue))
  485. {
  486. return baseValue;
  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. var v = baseObj.Get(property, reference.ThisValue);
  503. return v;
  504. }
  505. // check if we are accessing a string, boxing operation can be costly to do index access
  506. // we have good chance to have fast path with integer or string indexer
  507. ObjectInstance? o = null;
  508. if ((property._type & (InternalTypes.String | InternalTypes.Integer)) != InternalTypes.Empty
  509. && baseValue is JsString s
  510. && TryHandleStringValue(property, s, ref o, out var jsValue))
  511. {
  512. return jsValue;
  513. }
  514. if (o is null)
  515. {
  516. o = Runtime.TypeConverter.ToObject(Realm, baseValue);
  517. }
  518. if (reference.IsPrivateReference)
  519. {
  520. return o.PrivateGet((PrivateName) reference.ReferencedName);
  521. }
  522. return o.Get(property, reference.ThisValue);
  523. }
  524. var record = (Environment) baseValue;
  525. var bindingValue = record.GetBindingValue(reference.ReferencedName.ToString(), reference.Strict);
  526. if (returnReferenceToPool)
  527. {
  528. _referencePool.Return(reference);
  529. }
  530. return bindingValue;
  531. }
  532. private bool TryHandleStringValue(JsValue property, JsString s, ref ObjectInstance? o, out JsValue jsValue)
  533. {
  534. if (CommonProperties.Length.Equals(property))
  535. {
  536. jsValue = JsNumber.Create((uint) s.Length);
  537. return true;
  538. }
  539. if (property is JsNumber number && number.IsInteger())
  540. {
  541. var index = number.AsInteger();
  542. var str = s._value;
  543. if (index < 0 || index >= str.Length)
  544. {
  545. jsValue = JsValue.Undefined;
  546. return true;
  547. }
  548. jsValue = JsString.Create(str[index]);
  549. return true;
  550. }
  551. if (property is JsString propertyString
  552. && propertyString._value.Length > 0
  553. && char.IsLower(propertyString._value[0]))
  554. {
  555. // trying to find property that's always in prototype
  556. o = Realm.Intrinsics.String.PrototypeObject;
  557. }
  558. jsValue = JsValue.Undefined;
  559. return false;
  560. }
  561. /// <summary>
  562. /// https://tc39.es/ecma262/#sec-putvalue
  563. /// </summary>
  564. internal void PutValue(Reference reference, JsValue value)
  565. {
  566. if (reference.IsUnresolvableReference)
  567. {
  568. if (reference.Strict && reference.ReferencedName != CommonProperties.Arguments)
  569. {
  570. ExceptionHelper.ThrowReferenceError(Realm, reference);
  571. }
  572. Realm.GlobalObject.Set(reference.ReferencedName, value, throwOnError: false);
  573. }
  574. else if (reference.IsPropertyReference)
  575. {
  576. var baseObject = Runtime.TypeConverter.ToObject(Realm, reference.Base);
  577. if (reference.IsPrivateReference)
  578. {
  579. baseObject.PrivateSet((PrivateName) reference.ReferencedName, value);
  580. return;
  581. }
  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 '" + reference.ReferencedName + "' of " + baseObject);
  586. }
  587. }
  588. else
  589. {
  590. ((Environment) reference.Base).SetMutableBinding(Runtime.TypeConverter.ToString(reference.ReferencedName), 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, JsValue[] 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 SyntaxElement 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, 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. if (env is null)
  768. {
  769. return new Reference(JsValue.Undefined, name, strict);
  770. }
  771. var envRec = env;
  772. if (envRec.HasBinding(name))
  773. {
  774. return new Reference(envRec, name, strict);
  775. }
  776. return GetIdentifierReference(env._outerEnv, name, strict);
  777. }
  778. /// <summary>
  779. /// https://tc39.es/ecma262/#sec-getnewtarget
  780. /// </summary>
  781. internal JsValue GetNewTarget(Environment? thisEnvironment = null)
  782. {
  783. // we can take as argument if caller site has already determined the value, otherwise resolve
  784. thisEnvironment ??= ExecutionContext.GetThisEnvironment();
  785. return thisEnvironment.NewTarget ?? JsValue.Undefined;
  786. }
  787. /// <summary>
  788. /// https://tc39.es/ecma262/#sec-resolvethisbinding
  789. /// </summary>
  790. internal JsValue ResolveThisBinding()
  791. {
  792. var envRec = ExecutionContext.GetThisEnvironment();
  793. return envRec.GetThisBinding();
  794. }
  795. /// <summary>
  796. /// https://tc39.es/ecma262/#sec-globaldeclarationinstantiation
  797. /// </summary>
  798. private void GlobalDeclarationInstantiation(
  799. Script script,
  800. GlobalEnvironment env)
  801. {
  802. var hoistingScope = script.GetHoistingScope();
  803. var functionDeclarations = hoistingScope._functionDeclarations;
  804. var functionToInitialize = new List<JintFunctionDefinition>();
  805. var declaredFunctionNames = new HashSet<Key>();
  806. var declaredVarNames = new List<Key>();
  807. var realm = Realm;
  808. if (functionDeclarations != null)
  809. {
  810. for (var i = functionDeclarations.Count - 1; i >= 0; i--)
  811. {
  812. var d = functionDeclarations[i];
  813. var fn = (Key) d.Id!.Name;
  814. if (!declaredFunctionNames.Contains(fn))
  815. {
  816. var fnDefinable = env.CanDeclareGlobalFunction(fn);
  817. if (!fnDefinable)
  818. {
  819. ExceptionHelper.ThrowTypeError(realm, "Cannot declare global function " + fn);
  820. }
  821. declaredFunctionNames.Add(fn);
  822. functionToInitialize.Add(new JintFunctionDefinition(d));
  823. }
  824. }
  825. }
  826. var varNames = script.GetVarNames(hoistingScope);
  827. for (var j = 0; j < varNames.Count; j++)
  828. {
  829. var vn = varNames[j];
  830. if (env.HasLexicalDeclaration(vn))
  831. {
  832. ExceptionHelper.ThrowSyntaxError(realm, $"Identifier '{vn}' has already been declared");
  833. }
  834. if (!declaredFunctionNames.Contains(vn))
  835. {
  836. var vnDefinable = env.CanDeclareGlobalVar(vn);
  837. if (!vnDefinable)
  838. {
  839. ExceptionHelper.ThrowTypeError(realm);
  840. }
  841. declaredVarNames.Add(vn);
  842. }
  843. }
  844. PrivateEnvironment? privateEnv = null;
  845. var lexNames = script.GetLexNames(hoistingScope);
  846. for (var i = 0; i < lexNames.Count; i++)
  847. {
  848. var (dn, constant) = lexNames[i];
  849. if (env.HasVarDeclaration(dn) || env.HasLexicalDeclaration(dn) || env.HasRestrictedGlobalProperty(dn))
  850. {
  851. ExceptionHelper.ThrowSyntaxError(realm, $"Identifier '{dn}' has already been declared");
  852. }
  853. if (constant)
  854. {
  855. env.CreateImmutableBinding(dn, strict: true);
  856. }
  857. else
  858. {
  859. env.CreateMutableBinding(dn, canBeDeleted: false);
  860. }
  861. }
  862. // we need to go trough in reverse order to handle the hoisting correctly
  863. for (var i = functionToInitialize.Count - 1; i > -1; i--)
  864. {
  865. var f = functionToInitialize[i];
  866. Key fn = f.Name!;
  867. if (env.HasLexicalDeclaration(fn))
  868. {
  869. ExceptionHelper.ThrowSyntaxError(realm, $"Identifier '{fn}' has already been declared");
  870. }
  871. var fo = realm.Intrinsics.Function.InstantiateFunctionObject(f, env, privateEnv);
  872. env.CreateGlobalFunctionBinding(fn, fo, canBeDeleted: false);
  873. }
  874. env.CreateGlobalVarBindings(declaredVarNames, canBeDeleted: false);
  875. }
  876. /// <summary>
  877. /// https://tc39.es/ecma262/#sec-functiondeclarationinstantiation
  878. /// </summary>
  879. internal JsArguments? FunctionDeclarationInstantiation(
  880. Function function,
  881. JsValue[] argumentsList)
  882. {
  883. var calleeContext = ExecutionContext;
  884. var func = function._functionDefinition;
  885. var env = (FunctionEnvironment) ExecutionContext.LexicalEnvironment;
  886. var strict = _isStrict || StrictModeScope.IsStrictModeCode;
  887. var configuration = func.Initialize();
  888. var parameterNames = configuration.ParameterNames;
  889. var hasDuplicates = configuration.HasDuplicates;
  890. var simpleParameterList = configuration.IsSimpleParameterList;
  891. var hasParameterExpressions = configuration.HasParameterExpressions;
  892. var canInitializeParametersOnDeclaration = simpleParameterList && !configuration.HasDuplicates;
  893. var arguments = canInitializeParametersOnDeclaration ? argumentsList : null;
  894. env.InitializeParameters(parameterNames, hasDuplicates, arguments);
  895. JsArguments? ao = null;
  896. if (configuration.ArgumentsObjectNeeded || _isDebugMode)
  897. {
  898. if (strict || !simpleParameterList)
  899. {
  900. ao = CreateUnmappedArgumentsObject(argumentsList);
  901. }
  902. else
  903. {
  904. // NOTE: mapped argument object is only provided for non-strict functions that don't have a rest parameter,
  905. // any parameter default value initializers, or any destructured parameters.
  906. ao = CreateMappedArgumentsObject(function, parameterNames, argumentsList, env, configuration.HasRestParameter);
  907. }
  908. if (strict)
  909. {
  910. env.CreateImmutableBindingAndInitialize(KnownKeys.Arguments, strict: false, ao);
  911. }
  912. else
  913. {
  914. env.CreateMutableBindingAndInitialize(KnownKeys.Arguments, canBeDeleted: false, ao);
  915. }
  916. }
  917. if (!canInitializeParametersOnDeclaration)
  918. {
  919. // slower set
  920. env.AddFunctionParameters(_activeEvaluationContext!, func.Function, argumentsList);
  921. }
  922. // Let iteratorRecord be CreateListIteratorRecord(argumentsList).
  923. // If hasDuplicates is true, then
  924. // Perform ? IteratorBindingInitialization for formals with iteratorRecord and undefined as arguments.
  925. // Else,
  926. // Perform ? IteratorBindingInitialization for formals with iteratorRecord and env as arguments.
  927. Environment varEnv;
  928. if (!hasParameterExpressions)
  929. {
  930. // NOTE: Only a single lexical environment is needed for the parameters and top-level vars.
  931. var varsToInitialize = configuration.VarsToInitialize!;
  932. for (var i = 0; i < varsToInitialize.Count; i++)
  933. {
  934. var pair = varsToInitialize[i];
  935. env.CreateMutableBindingAndInitialize(pair.Name, canBeDeleted: false, JsValue.Undefined);
  936. }
  937. varEnv = env;
  938. }
  939. else
  940. {
  941. // NOTE: A separate Environment Record is needed to ensure that closures created by expressions
  942. // in the formal parameter list do not have visibility of declarations in the function body.
  943. var varEnvRec = JintEnvironment.NewDeclarativeEnvironment(this, env);
  944. varEnv = varEnvRec;
  945. UpdateVariableEnvironment(varEnv);
  946. var varsToInitialize = configuration.VarsToInitialize!;
  947. for (var i = 0; i < varsToInitialize.Count; i++)
  948. {
  949. var pair = varsToInitialize[i];
  950. var initialValue = pair.InitialValue ?? env.GetBindingValue(pair.Name, strict: false);
  951. varEnvRec.CreateMutableBindingAndInitialize(pair.Name, canBeDeleted: false, initialValue);
  952. }
  953. }
  954. // NOTE: Annex B.3.3.1 adds additional steps at this point.
  955. // A https://tc39.es/ecma262/#sec-web-compat-functiondeclarationinstantiation
  956. Environment lexEnv;
  957. if (!strict)
  958. {
  959. lexEnv = JintEnvironment.NewDeclarativeEnvironment(this, varEnv);
  960. // NOTE: Non-strict functions use a separate lexical Environment Record for top-level lexical declarations
  961. // so that a direct eval can determine whether any var scoped declarations introduced by the eval code conflict
  962. // with pre-existing top-level lexically scoped declarations. This is not needed for strict functions
  963. // because a strict direct eval always places all declarations into a new Environment Record.
  964. }
  965. else
  966. {
  967. lexEnv = varEnv;
  968. }
  969. UpdateLexicalEnvironment(lexEnv);
  970. if (configuration.LexicalDeclarations.Length > 0)
  971. {
  972. foreach (var d in configuration.LexicalDeclarations)
  973. {
  974. for (var j = 0; j < d.BoundNames.Count; j++)
  975. {
  976. var dn = d.BoundNames[j];
  977. if (d.IsConstantDeclaration)
  978. {
  979. lexEnv.CreateImmutableBinding(dn, strict: true);
  980. }
  981. else
  982. {
  983. lexEnv.CreateMutableBinding(dn, canBeDeleted: false);
  984. }
  985. }
  986. }
  987. }
  988. if (configuration.FunctionsToInitialize != null)
  989. {
  990. var privateEnv = calleeContext.PrivateEnvironment;
  991. var realm = Realm;
  992. foreach (var f in configuration.FunctionsToInitialize)
  993. {
  994. var jintFunctionDefinition = new JintFunctionDefinition(f);
  995. var fn = jintFunctionDefinition.Name!;
  996. var fo = realm.Intrinsics.Function.InstantiateFunctionObject(jintFunctionDefinition, lexEnv, privateEnv);
  997. varEnv.SetMutableBinding(fn, fo, strict: false);
  998. }
  999. }
  1000. return ao;
  1001. }
  1002. private JsArguments CreateMappedArgumentsObject(
  1003. Function func,
  1004. Key[] formals,
  1005. JsValue[] argumentsList,
  1006. DeclarativeEnvironment envRec,
  1007. bool hasRestParameter)
  1008. {
  1009. return _argumentsInstancePool.Rent(func, formals, argumentsList, envRec, hasRestParameter);
  1010. }
  1011. private JsArguments CreateUnmappedArgumentsObject(JsValue[] argumentsList)
  1012. {
  1013. return _argumentsInstancePool.Rent(argumentsList);
  1014. }
  1015. /// <summary>
  1016. /// https://tc39.es/ecma262/#sec-evaldeclarationinstantiation
  1017. /// </summary>
  1018. internal void EvalDeclarationInstantiation(
  1019. Script script,
  1020. Environment varEnv,
  1021. Environment lexEnv,
  1022. PrivateEnvironment? privateEnv,
  1023. bool strict)
  1024. {
  1025. var hoistingScope = HoistingScope.GetProgramLevelDeclarations(script);
  1026. var lexEnvRec = (DeclarativeEnvironment) lexEnv;
  1027. var varEnvRec = varEnv;
  1028. var realm = Realm;
  1029. if (!strict && hoistingScope._variablesDeclarations != null)
  1030. {
  1031. if (varEnvRec is GlobalEnvironment globalEnvironmentRecord)
  1032. {
  1033. ref readonly var nodes = ref hoistingScope._variablesDeclarations;
  1034. for (var i = 0; i < nodes.Count; i++)
  1035. {
  1036. var variablesDeclaration = nodes[i];
  1037. var identifier = (Identifier) variablesDeclaration.Declarations[0].Id;
  1038. if (globalEnvironmentRecord.HasLexicalDeclaration(identifier.Name))
  1039. {
  1040. ExceptionHelper.ThrowSyntaxError(realm, "Identifier '" + identifier.Name + "' has already been declared");
  1041. }
  1042. }
  1043. }
  1044. var thisLex = lexEnv;
  1045. while (!ReferenceEquals(thisLex, varEnv))
  1046. {
  1047. var thisEnvRec = thisLex;
  1048. if (thisEnvRec is not ObjectEnvironment)
  1049. {
  1050. ref readonly var nodes = ref hoistingScope._variablesDeclarations;
  1051. for (var i = 0; i < nodes.Count; i++)
  1052. {
  1053. var variablesDeclaration = nodes[i];
  1054. var identifier = (Identifier) variablesDeclaration.Declarations[0].Id;
  1055. if (thisEnvRec!.HasBinding(identifier.Name))
  1056. {
  1057. ExceptionHelper.ThrowSyntaxError(realm);
  1058. }
  1059. }
  1060. }
  1061. thisLex = thisLex!._outerEnv;
  1062. }
  1063. }
  1064. HashSet<PrivateIdentifier>? privateIdentifiers = null;
  1065. var pointer = privateEnv;
  1066. while (pointer is not null)
  1067. {
  1068. foreach (var name in pointer.Names)
  1069. {
  1070. privateIdentifiers??= new HashSet<PrivateIdentifier>(PrivateIdentifierNameComparer._instance);
  1071. privateIdentifiers.Add(name.Key);
  1072. }
  1073. pointer = pointer.OuterPrivateEnvironment;
  1074. }
  1075. script.AllPrivateIdentifiersValid(realm, privateIdentifiers);
  1076. var functionDeclarations = hoistingScope._functionDeclarations;
  1077. var functionsToInitialize = new LinkedList<JintFunctionDefinition>();
  1078. var declaredFunctionNames = new HashSet<Key>();
  1079. if (functionDeclarations != null)
  1080. {
  1081. for (var i = functionDeclarations.Count - 1; i >= 0; i--)
  1082. {
  1083. var d = functionDeclarations[i];
  1084. Key fn = d.Id!.Name;
  1085. if (!declaredFunctionNames.Contains(fn))
  1086. {
  1087. if (varEnvRec is GlobalEnvironment ger)
  1088. {
  1089. var fnDefinable = ger.CanDeclareGlobalFunction(fn);
  1090. if (!fnDefinable)
  1091. {
  1092. ExceptionHelper.ThrowTypeError(realm);
  1093. }
  1094. }
  1095. declaredFunctionNames.Add(fn);
  1096. functionsToInitialize.AddFirst(new JintFunctionDefinition(d));
  1097. }
  1098. }
  1099. }
  1100. var boundNames = new List<Key>();
  1101. var declaredVarNames = new List<Key>();
  1102. var variableDeclarations = hoistingScope._variablesDeclarations;
  1103. var variableDeclarationsCount = variableDeclarations?.Count;
  1104. for (var i = 0; i < variableDeclarationsCount; i++)
  1105. {
  1106. var variableDeclaration = variableDeclarations![i];
  1107. boundNames.Clear();
  1108. variableDeclaration.GetBoundNames(boundNames);
  1109. for (var j = 0; j < boundNames.Count; j++)
  1110. {
  1111. var vn = boundNames[j];
  1112. if (!declaredFunctionNames.Contains(vn))
  1113. {
  1114. if (varEnvRec is GlobalEnvironment ger)
  1115. {
  1116. var vnDefinable = ger.CanDeclareGlobalFunction(vn);
  1117. if (!vnDefinable)
  1118. {
  1119. ExceptionHelper.ThrowTypeError(realm);
  1120. }
  1121. }
  1122. declaredVarNames.Add(vn);
  1123. }
  1124. }
  1125. }
  1126. var lexicalDeclarations = hoistingScope._lexicalDeclarations;
  1127. var lexicalDeclarationsCount = lexicalDeclarations?.Count;
  1128. for (var i = 0; i < lexicalDeclarationsCount; i++)
  1129. {
  1130. boundNames.Clear();
  1131. var d = lexicalDeclarations![i];
  1132. d.GetBoundNames(boundNames);
  1133. for (var j = 0; j < boundNames.Count; j++)
  1134. {
  1135. Key dn = boundNames[j];
  1136. if (d.IsConstantDeclaration())
  1137. {
  1138. lexEnvRec.CreateImmutableBinding(dn, strict: true);
  1139. }
  1140. else
  1141. {
  1142. lexEnvRec.CreateMutableBinding(dn, canBeDeleted: false);
  1143. }
  1144. }
  1145. }
  1146. foreach (var f in functionsToInitialize)
  1147. {
  1148. var fo = realm.Intrinsics.Function.InstantiateFunctionObject(f, lexEnv, privateEnv);
  1149. if (varEnvRec is GlobalEnvironment ger)
  1150. {
  1151. ger.CreateGlobalFunctionBinding(f.Name!, fo, canBeDeleted: true);
  1152. }
  1153. else
  1154. {
  1155. Key fn = f.Name!;
  1156. var bindingExists = varEnvRec.HasBinding(fn);
  1157. if (!bindingExists)
  1158. {
  1159. varEnvRec.CreateMutableBinding(fn, canBeDeleted: true);
  1160. varEnvRec.InitializeBinding(fn, fo);
  1161. }
  1162. else
  1163. {
  1164. varEnvRec.SetMutableBinding(fn, fo, strict: false);
  1165. }
  1166. }
  1167. }
  1168. foreach (var vn in declaredVarNames)
  1169. {
  1170. if (varEnvRec is GlobalEnvironment ger)
  1171. {
  1172. ger.CreateGlobalVarBinding(vn, true);
  1173. }
  1174. else
  1175. {
  1176. var bindingExists = varEnvRec.HasBinding(vn);
  1177. if (!bindingExists)
  1178. {
  1179. varEnvRec.CreateMutableBinding(vn, canBeDeleted: true);
  1180. varEnvRec.InitializeBinding(vn, JsValue.Undefined);
  1181. }
  1182. }
  1183. }
  1184. }
  1185. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1186. internal void UpdateLexicalEnvironment(Environment newEnv)
  1187. {
  1188. _executionContexts.ReplaceTopLexicalEnvironment(newEnv);
  1189. }
  1190. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1191. internal void UpdateVariableEnvironment(Environment newEnv)
  1192. {
  1193. _executionContexts.ReplaceTopVariableEnvironment(newEnv);
  1194. }
  1195. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1196. internal void UpdatePrivateEnvironment(PrivateEnvironment? newEnv)
  1197. {
  1198. _executionContexts.ReplaceTopPrivateEnvironment(newEnv);
  1199. }
  1200. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1201. internal ref readonly ExecutionContext UpdateGenerator(GeneratorInstance generator)
  1202. {
  1203. return ref _executionContexts.ReplaceTopGenerator(generator);
  1204. }
  1205. /// <summary>
  1206. /// Invokes the named callable and returns the resulting object.
  1207. /// </summary>
  1208. /// <param name="callableName">The name of the callable.</param>
  1209. /// <param name="arguments">The arguments of the call.</param>
  1210. /// <returns>The value returned by the call.</returns>
  1211. public JsValue Call(string callableName, params JsValue[] arguments)
  1212. {
  1213. var callable = Evaluate(callableName);
  1214. return Call(callable, arguments);
  1215. }
  1216. /// <summary>
  1217. /// Invokes the callable and returns the resulting object.
  1218. /// </summary>
  1219. /// <param name="callable">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(JsValue callable, params JsValue[] arguments)
  1223. => Call(callable, thisObject: JsValue.Undefined, arguments);
  1224. /// <summary>
  1225. /// Invokes the callable and returns the resulting object.
  1226. /// </summary>
  1227. /// <param name="callable">The callable.</param>
  1228. /// <param name="thisObject">Value bound as this.</param>
  1229. /// <param name="arguments">The arguments of the call.</param>
  1230. /// <returns>The value returned by the call.</returns>
  1231. public JsValue Call(JsValue callable, JsValue thisObject, JsValue[] arguments)
  1232. {
  1233. JsValue Callback()
  1234. {
  1235. if (!callable.IsCallable)
  1236. {
  1237. ExceptionHelper.ThrowArgumentException(callable + " is not callable");
  1238. }
  1239. return Call((ICallable) callable, thisObject, arguments, null);
  1240. }
  1241. return ExecuteWithConstraints(Options.Strict, Callback);
  1242. }
  1243. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1244. internal JsValue Call(ICallable callable, JsValue thisObject, JsValue[] arguments, JintExpression? expression)
  1245. {
  1246. if (callable is Function functionInstance)
  1247. {
  1248. return Call(functionInstance, thisObject, arguments, expression);
  1249. }
  1250. return callable.Call(thisObject, arguments);
  1251. }
  1252. /// <summary>
  1253. /// Calls the named constructor and returns the resulting object.
  1254. /// </summary>
  1255. /// <param name="constructorName">The name of the constructor to call.</param>
  1256. /// <param name="arguments">The arguments of the constructor call.</param>
  1257. /// <returns>The value returned by the constructor call.</returns>
  1258. public ObjectInstance Construct(string constructorName, params JsValue[] arguments)
  1259. {
  1260. var constructor = Evaluate(constructorName);
  1261. return Construct(constructor, arguments);
  1262. }
  1263. /// <summary>
  1264. /// Calls the constructor and returns the resulting object.
  1265. /// </summary>
  1266. /// <param name="constructor">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(JsValue constructor, params JsValue[] arguments)
  1270. {
  1271. ObjectInstance Callback()
  1272. {
  1273. if (!constructor.IsConstructor)
  1274. {
  1275. ExceptionHelper.ThrowArgumentException(constructor + " is not a constructor");
  1276. }
  1277. return Construct(constructor, arguments, constructor, null);
  1278. }
  1279. return ExecuteWithConstraints(Options.Strict, Callback);
  1280. }
  1281. internal ObjectInstance Construct(
  1282. JsValue constructor,
  1283. JsValue[] arguments,
  1284. JsValue newTarget,
  1285. JintExpression? expression)
  1286. {
  1287. if (constructor is Function functionInstance)
  1288. {
  1289. return Construct(functionInstance, arguments, newTarget, expression);
  1290. }
  1291. return ((IConstructor) constructor).Construct(arguments, newTarget);
  1292. }
  1293. internal JsValue Call(Function function, JsValue thisObject)
  1294. => Call(function, thisObject, Arguments.Empty, null);
  1295. internal JsValue Call(
  1296. Function function,
  1297. JsValue thisObject,
  1298. JsValue[] arguments,
  1299. JintExpression? expression)
  1300. {
  1301. // ensure logic is in sync between Call, Construct, engine.Invoke and JintCallExpression!
  1302. var recursionDepth = CallStack.Push(function, expression, ExecutionContext);
  1303. if (recursionDepth > Options.Constraints.MaxRecursionDepth)
  1304. {
  1305. // automatically pops the current element as it was never reached
  1306. ExceptionHelper.ThrowRecursionDepthOverflowException(CallStack);
  1307. }
  1308. JsValue result;
  1309. try
  1310. {
  1311. result = function.Call(thisObject, arguments);
  1312. }
  1313. finally
  1314. {
  1315. // if call stack was reset due to recursive call to engine or similar, we might not have it anymore
  1316. if (CallStack.Count > 0)
  1317. {
  1318. CallStack.Pop();
  1319. }
  1320. }
  1321. return result;
  1322. }
  1323. private ObjectInstance Construct(
  1324. Function function,
  1325. JsValue[] arguments,
  1326. JsValue newTarget,
  1327. JintExpression? expression)
  1328. {
  1329. // ensure logic is in sync between Call, Construct, engine.Invoke and JintCallExpression!
  1330. var recursionDepth = CallStack.Push(function, expression, ExecutionContext);
  1331. if (recursionDepth > Options.Constraints.MaxRecursionDepth)
  1332. {
  1333. // automatically pops the current element as it was never reached
  1334. ExceptionHelper.ThrowRecursionDepthOverflowException(CallStack);
  1335. }
  1336. ObjectInstance result;
  1337. try
  1338. {
  1339. result = ((IConstructor) function).Construct(arguments, newTarget);
  1340. }
  1341. finally
  1342. {
  1343. CallStack.Pop();
  1344. }
  1345. return result;
  1346. }
  1347. internal void SignalError(ErrorDispatchInfo error)
  1348. {
  1349. _error = error;
  1350. }
  1351. internal void RegisterTypeReference(TypeReference reference)
  1352. {
  1353. _typeReferences ??= new Dictionary<Type, TypeReference>();
  1354. _typeReferences[reference.ReferenceType] = reference;
  1355. }
  1356. internal ref readonly ExecutionContext GetExecutionContext(int fromTop)
  1357. {
  1358. return ref _executionContexts.Peek(fromTop);
  1359. }
  1360. public void Dispose()
  1361. {
  1362. if (_objectWrapperCache is null)
  1363. {
  1364. return;
  1365. }
  1366. #if SUPPORTS_WEAK_TABLE_CLEAR
  1367. _objectWrapperCache.Clear();
  1368. #else
  1369. // we can expect that reflection is OK as we've been generating object wrappers already
  1370. var clearMethod = _objectWrapperCache.GetType().GetMethod("Clear", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
  1371. clearMethod?.Invoke(_objectWrapperCache, Array.Empty<object>());
  1372. #endif
  1373. }
  1374. [DebuggerDisplay("Engine")]
  1375. private sealed class EngineDebugView
  1376. {
  1377. private readonly Engine _engine;
  1378. public EngineDebugView(Engine engine)
  1379. {
  1380. _engine = engine;
  1381. }
  1382. public ObjectInstance Globals => _engine.Realm.GlobalObject;
  1383. public Options Options => _engine.Options;
  1384. public Environment VariableEnvironment => _engine.ExecutionContext.VariableEnvironment;
  1385. public Environment LexicalEnvironment => _engine.ExecutionContext.LexicalEnvironment;
  1386. }
  1387. }
  1388. }