Engine.cs 58 KB

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