Engine.cs 58 KB

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