Engine.cs 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619
  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, thisObj: 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, thisObj: 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. // ensure logic is in sync between Call, Construct, engine.Invoke and JintCallExpression!
  640. JsValue result;
  641. var thisObject = JsValue.FromObject(this, thisObj);
  642. if (callable is FunctionInstance functionInstance)
  643. {
  644. var callStack = CallStack;
  645. callStack.Push(functionInstance, expression: null, ExecutionContext);
  646. try
  647. {
  648. result = functionInstance.Call(thisObject, items);
  649. }
  650. finally
  651. {
  652. // if call stack was reset due to recursive call to engine or similar, we might not have it anymore
  653. if (callStack.Count > 0)
  654. {
  655. callStack.Pop();
  656. }
  657. }
  658. }
  659. else
  660. {
  661. result = callable.Call(thisObject, items);
  662. }
  663. _jsValueArrayPool.ReturnArray(items);
  664. return result;
  665. }
  666. return ExecuteWithConstraints(Options.Strict, DoInvoke);
  667. }
  668. private T ExecuteWithConstraints<T>(bool strict, Func<T> callback)
  669. {
  670. ResetConstraints();
  671. var ownsContext = _activeEvaluationContext is null;
  672. _activeEvaluationContext ??= new EvaluationContext(this);
  673. try
  674. {
  675. using (new StrictModeScope(strict))
  676. {
  677. return callback();
  678. }
  679. }
  680. finally
  681. {
  682. if (ownsContext)
  683. {
  684. _activeEvaluationContext = null!;
  685. }
  686. ResetConstraints();
  687. _agent.ClearKeptObjects();
  688. }
  689. }
  690. /// <summary>
  691. /// https://tc39.es/ecma262/#sec-invoke
  692. /// </summary>
  693. internal JsValue Invoke(JsValue v, JsValue p, JsValue[] arguments)
  694. {
  695. var ownsContext = _activeEvaluationContext is null;
  696. _activeEvaluationContext ??= new EvaluationContext(this);
  697. try
  698. {
  699. var func = GetV(v, p);
  700. var callable = func as ICallable;
  701. if (callable is null)
  702. {
  703. ExceptionHelper.ThrowTypeErrorNoEngine("Can only invoke functions");
  704. }
  705. return callable.Call(v, arguments);
  706. }
  707. finally
  708. {
  709. if (ownsContext)
  710. {
  711. _activeEvaluationContext = null!;
  712. }
  713. }
  714. }
  715. /// <summary>
  716. /// https://tc39.es/ecma262/#sec-getv
  717. /// </summary>
  718. private JsValue GetV(JsValue v, JsValue p)
  719. {
  720. var o = TypeConverter.ToObject(Realm, v);
  721. return o.Get(p);
  722. }
  723. /// <summary>
  724. /// Gets a named value from the Global scope.
  725. /// </summary>
  726. /// <param name="propertyName">The name of the property to return.</param>
  727. public JsValue GetValue(string propertyName)
  728. {
  729. return GetValue(Realm.GlobalObject, new JsString(propertyName));
  730. }
  731. /// <summary>
  732. /// Gets the last evaluated <see cref="Node"/>.
  733. /// </summary>
  734. internal SyntaxElement GetLastSyntaxElement()
  735. {
  736. return _lastSyntaxElement!;
  737. }
  738. /// <summary>
  739. /// Gets a named value from the specified scope.
  740. /// </summary>
  741. /// <param name="scope">The scope to get the property from.</param>
  742. /// <param name="property">The name of the property to return.</param>
  743. public JsValue GetValue(JsValue scope, JsValue property)
  744. {
  745. var reference = _referencePool.Rent(scope, property, _isStrict, thisValue: null);
  746. var jsValue = GetValue(reference, false);
  747. _referencePool.Return(reference);
  748. return jsValue;
  749. }
  750. /// <summary>
  751. /// https://tc39.es/ecma262/#sec-resolvebinding
  752. /// </summary>
  753. internal Reference ResolveBinding(string name, EnvironmentRecord? env = null)
  754. {
  755. env ??= ExecutionContext.LexicalEnvironment;
  756. return GetIdentifierReference(env, name, StrictModeScope.IsStrictModeCode);
  757. }
  758. private static Reference GetIdentifierReference(EnvironmentRecord? env, string name, bool strict)
  759. {
  760. if (env is null)
  761. {
  762. return new Reference(JsValue.Undefined, name, strict);
  763. }
  764. var envRec = env;
  765. if (envRec.HasBinding(name))
  766. {
  767. return new Reference(envRec, name, strict);
  768. }
  769. return GetIdentifierReference(env._outerEnv, name, strict);
  770. }
  771. /// <summary>
  772. /// https://tc39.es/ecma262/#sec-getnewtarget
  773. /// </summary>
  774. internal JsValue GetNewTarget(EnvironmentRecord? thisEnvironment = null)
  775. {
  776. // we can take as argument if caller site has already determined the value, otherwise resolve
  777. thisEnvironment ??= ExecutionContext.GetThisEnvironment();
  778. return thisEnvironment.NewTarget ?? JsValue.Undefined;
  779. }
  780. /// <summary>
  781. /// https://tc39.es/ecma262/#sec-resolvethisbinding
  782. /// </summary>
  783. internal JsValue ResolveThisBinding()
  784. {
  785. var envRec = ExecutionContext.GetThisEnvironment();
  786. return envRec.GetThisBinding();
  787. }
  788. /// <summary>
  789. /// https://tc39.es/ecma262/#sec-globaldeclarationinstantiation
  790. /// </summary>
  791. private void GlobalDeclarationInstantiation(
  792. Script script,
  793. GlobalEnvironmentRecord env)
  794. {
  795. var hoistingScope = script.GetHoistingScope();
  796. var functionDeclarations = hoistingScope._functionDeclarations;
  797. var lexDeclarations = hoistingScope._lexicalDeclarations;
  798. var functionToInitialize = new List<JintFunctionDefinition>();
  799. var declaredFunctionNames = new HashSet<string>(StringComparer.Ordinal);
  800. var declaredVarNames = new List<string>();
  801. var realm = Realm;
  802. if (functionDeclarations != null)
  803. {
  804. for (var i = functionDeclarations.Count - 1; i >= 0; i--)
  805. {
  806. var d = functionDeclarations[i];
  807. var fn = d.Id!.Name;
  808. if (!declaredFunctionNames.Contains(fn))
  809. {
  810. var fnDefinable = env.CanDeclareGlobalFunction(fn);
  811. if (!fnDefinable)
  812. {
  813. ExceptionHelper.ThrowTypeError(realm, "Cannot declare global function " + fn);
  814. }
  815. declaredFunctionNames.Add(fn);
  816. functionToInitialize.Add(new JintFunctionDefinition(d));
  817. }
  818. }
  819. }
  820. var varNames = script.GetVarNames(hoistingScope);
  821. for (var j = 0; j < varNames.Count; j++)
  822. {
  823. var vn = varNames[j];
  824. if (env.HasLexicalDeclaration(vn))
  825. {
  826. ExceptionHelper.ThrowSyntaxError(realm, $"Identifier '{vn}' has already been declared");
  827. }
  828. if (!declaredFunctionNames.Contains(vn))
  829. {
  830. var vnDefinable = env.CanDeclareGlobalVar(vn);
  831. if (!vnDefinable)
  832. {
  833. ExceptionHelper.ThrowTypeError(realm);
  834. }
  835. declaredVarNames.Add(vn);
  836. }
  837. }
  838. PrivateEnvironmentRecord? privateEnv = null;
  839. var lexNames = script.GetLexNames(hoistingScope);
  840. for (var i = 0; i < lexNames.Count; i++)
  841. {
  842. var (dn, constant) = lexNames[i];
  843. if (env.HasVarDeclaration(dn) || env.HasLexicalDeclaration(dn) || env.HasRestrictedGlobalProperty(dn))
  844. {
  845. ExceptionHelper.ThrowSyntaxError(realm, $"Identifier '{dn}' has already been declared");
  846. }
  847. if (constant)
  848. {
  849. env.CreateImmutableBinding(dn, strict: true);
  850. }
  851. else
  852. {
  853. env.CreateMutableBinding(dn, canBeDeleted: false);
  854. }
  855. }
  856. // we need to go trough in reverse order to handle the hoisting correctly
  857. for (var i = functionToInitialize.Count - 1; i > -1; i--)
  858. {
  859. var f = functionToInitialize[i];
  860. var fn = f.Name!;
  861. if (env.HasLexicalDeclaration(fn))
  862. {
  863. ExceptionHelper.ThrowSyntaxError(realm, $"Identifier '{fn}' has already been declared");
  864. }
  865. var fo = realm.Intrinsics.Function.InstantiateFunctionObject(f, env, privateEnv);
  866. env.CreateGlobalFunctionBinding(fn, fo, canBeDeleted: false);
  867. }
  868. env.CreateGlobalVarBindings(declaredVarNames, canBeDeleted: false);
  869. }
  870. /// <summary>
  871. /// https://tc39.es/ecma262/#sec-functiondeclarationinstantiation
  872. /// </summary>
  873. internal ArgumentsInstance? FunctionDeclarationInstantiation(
  874. FunctionInstance functionInstance,
  875. JsValue[] argumentsList)
  876. {
  877. var calleeContext = ExecutionContext;
  878. var func = functionInstance._functionDefinition;
  879. var env = (FunctionEnvironmentRecord) ExecutionContext.LexicalEnvironment;
  880. var strict = _isStrict || StrictModeScope.IsStrictModeCode;
  881. var configuration = func.Initialize();
  882. var parameterNames = configuration.ParameterNames;
  883. var hasDuplicates = configuration.HasDuplicates;
  884. var simpleParameterList = configuration.IsSimpleParameterList;
  885. var hasParameterExpressions = configuration.HasParameterExpressions;
  886. var canInitializeParametersOnDeclaration = simpleParameterList && !configuration.HasDuplicates;
  887. var arguments = canInitializeParametersOnDeclaration ? argumentsList : null;
  888. env.InitializeParameters(parameterNames, hasDuplicates, arguments);
  889. ArgumentsInstance? ao = null;
  890. if (configuration.ArgumentsObjectNeeded || _isDebugMode)
  891. {
  892. if (strict || !simpleParameterList)
  893. {
  894. ao = CreateUnmappedArgumentsObject(argumentsList);
  895. }
  896. else
  897. {
  898. // NOTE: mapped argument object is only provided for non-strict functions that don't have a rest parameter,
  899. // any parameter default value initializers, or any destructured parameters.
  900. ao = CreateMappedArgumentsObject(functionInstance, parameterNames, argumentsList, env, configuration.HasRestParameter);
  901. }
  902. if (strict)
  903. {
  904. env.CreateImmutableBindingAndInitialize(KnownKeys.Arguments, strict: false, ao);
  905. }
  906. else
  907. {
  908. env.CreateMutableBindingAndInitialize(KnownKeys.Arguments, canBeDeleted: false, ao);
  909. }
  910. }
  911. if (!canInitializeParametersOnDeclaration)
  912. {
  913. // slower set
  914. env.AddFunctionParameters(_activeEvaluationContext!, func.Function, argumentsList);
  915. }
  916. // Let iteratorRecord be CreateListIteratorRecord(argumentsList).
  917. // If hasDuplicates is true, then
  918. // Perform ? IteratorBindingInitialization for formals with iteratorRecord and undefined as arguments.
  919. // Else,
  920. // Perform ? IteratorBindingInitialization for formals with iteratorRecord and env as arguments.
  921. EnvironmentRecord varEnv;
  922. if (!hasParameterExpressions)
  923. {
  924. // NOTE: Only a single lexical environment is needed for the parameters and top-level vars.
  925. var varsToInitialize = configuration.VarsToInitialize!;
  926. for (var i = 0; i < varsToInitialize.Count; i++)
  927. {
  928. var pair = varsToInitialize[i];
  929. env.CreateMutableBindingAndInitialize(pair.Name, canBeDeleted: false, JsValue.Undefined);
  930. }
  931. varEnv = env;
  932. }
  933. else
  934. {
  935. // NOTE: A separate Environment Record is needed to ensure that closures created by expressions
  936. // in the formal parameter list do not have visibility of declarations in the function body.
  937. var varEnvRec = JintEnvironment.NewDeclarativeEnvironment(this, env);
  938. varEnv = varEnvRec;
  939. UpdateVariableEnvironment(varEnv);
  940. var varsToInitialize = configuration.VarsToInitialize!;
  941. for (var i = 0; i < varsToInitialize.Count; i++)
  942. {
  943. var pair = varsToInitialize[i];
  944. var initialValue = pair.InitialValue ?? env.GetBindingValue(pair.Name, strict: false);
  945. varEnvRec.CreateMutableBindingAndInitialize(pair.Name, canBeDeleted: false, initialValue);
  946. }
  947. }
  948. // NOTE: Annex B.3.3.1 adds additional steps at this point.
  949. // A https://tc39.es/ecma262/#sec-web-compat-functiondeclarationinstantiation
  950. EnvironmentRecord lexEnv;
  951. if (!strict)
  952. {
  953. lexEnv = JintEnvironment.NewDeclarativeEnvironment(this, varEnv);
  954. // NOTE: Non-strict functions use a separate lexical Environment Record for top-level lexical declarations
  955. // so that a direct eval can determine whether any var scoped declarations introduced by the eval code conflict
  956. // with pre-existing top-level lexically scoped declarations. This is not needed for strict functions
  957. // because a strict direct eval always places all declarations into a new Environment Record.
  958. }
  959. else
  960. {
  961. lexEnv = varEnv;
  962. }
  963. UpdateLexicalEnvironment(lexEnv);
  964. if (configuration.LexicalDeclarations.Length > 0)
  965. {
  966. foreach (var d in configuration.LexicalDeclarations)
  967. {
  968. for (var j = 0; j < d.BoundNames.Count; j++)
  969. {
  970. var dn = d.BoundNames[j];
  971. if (d.IsConstantDeclaration)
  972. {
  973. lexEnv.CreateImmutableBinding(dn, strict: true);
  974. }
  975. else
  976. {
  977. lexEnv.CreateMutableBinding(dn, canBeDeleted: false);
  978. }
  979. }
  980. }
  981. }
  982. if (configuration.FunctionsToInitialize != null)
  983. {
  984. var privateEnv = calleeContext.PrivateEnvironment;
  985. var realm = Realm;
  986. foreach (var f in configuration.FunctionsToInitialize)
  987. {
  988. var jintFunctionDefinition = new JintFunctionDefinition(f);
  989. var fn = jintFunctionDefinition.Name!;
  990. var fo = realm.Intrinsics.Function.InstantiateFunctionObject(jintFunctionDefinition, lexEnv, privateEnv);
  991. varEnv.SetMutableBinding(fn, fo, strict: false);
  992. }
  993. }
  994. return ao;
  995. }
  996. private ArgumentsInstance CreateMappedArgumentsObject(
  997. FunctionInstance func,
  998. Key[] formals,
  999. JsValue[] argumentsList,
  1000. DeclarativeEnvironmentRecord envRec,
  1001. bool hasRestParameter)
  1002. {
  1003. return _argumentsInstancePool.Rent(func, formals, argumentsList, envRec, hasRestParameter);
  1004. }
  1005. private ArgumentsInstance CreateUnmappedArgumentsObject(JsValue[] argumentsList)
  1006. {
  1007. return _argumentsInstancePool.Rent(argumentsList);
  1008. }
  1009. /// <summary>
  1010. /// https://tc39.es/ecma262/#sec-evaldeclarationinstantiation
  1011. /// </summary>
  1012. internal void EvalDeclarationInstantiation(
  1013. Script script,
  1014. EnvironmentRecord varEnv,
  1015. EnvironmentRecord lexEnv,
  1016. PrivateEnvironmentRecord? privateEnv,
  1017. bool strict)
  1018. {
  1019. var hoistingScope = HoistingScope.GetProgramLevelDeclarations(script);
  1020. var lexEnvRec = (DeclarativeEnvironmentRecord) lexEnv;
  1021. var varEnvRec = varEnv;
  1022. var realm = Realm;
  1023. if (!strict && hoistingScope._variablesDeclarations != null)
  1024. {
  1025. if (varEnvRec is GlobalEnvironmentRecord globalEnvironmentRecord)
  1026. {
  1027. ref readonly var nodes = ref hoistingScope._variablesDeclarations;
  1028. for (var i = 0; i < nodes.Count; i++)
  1029. {
  1030. var variablesDeclaration = nodes[i];
  1031. var identifier = (Identifier) variablesDeclaration.Declarations[0].Id;
  1032. if (globalEnvironmentRecord.HasLexicalDeclaration(identifier.Name))
  1033. {
  1034. ExceptionHelper.ThrowSyntaxError(realm, "Identifier '" + identifier.Name + "' has already been declared");
  1035. }
  1036. }
  1037. }
  1038. var thisLex = lexEnv;
  1039. while (!ReferenceEquals(thisLex, varEnv))
  1040. {
  1041. var thisEnvRec = thisLex;
  1042. if (thisEnvRec is not ObjectEnvironmentRecord)
  1043. {
  1044. ref readonly var nodes = ref hoistingScope._variablesDeclarations;
  1045. for (var i = 0; i < nodes.Count; i++)
  1046. {
  1047. var variablesDeclaration = nodes[i];
  1048. var identifier = (Identifier) variablesDeclaration.Declarations[0].Id;
  1049. if (thisEnvRec!.HasBinding(identifier.Name))
  1050. {
  1051. ExceptionHelper.ThrowSyntaxError(realm);
  1052. }
  1053. }
  1054. }
  1055. thisLex = thisLex!._outerEnv;
  1056. }
  1057. }
  1058. HashSet<PrivateIdentifier>? privateIdentifiers = null;
  1059. var pointer = privateEnv;
  1060. while (pointer is not null)
  1061. {
  1062. foreach (var name in pointer.Names)
  1063. {
  1064. privateIdentifiers??= new HashSet<PrivateIdentifier>(PrivateIdentifierNameComparer._instance);
  1065. privateIdentifiers.Add(name.Key);
  1066. }
  1067. pointer = pointer.OuterPrivateEnvironment;
  1068. }
  1069. script.AllPrivateIdentifiersValid(realm, privateIdentifiers);
  1070. var functionDeclarations = hoistingScope._functionDeclarations;
  1071. var functionsToInitialize = new LinkedList<JintFunctionDefinition>();
  1072. var declaredFunctionNames = new HashSet<string>(StringComparer.Ordinal);
  1073. if (functionDeclarations != null)
  1074. {
  1075. for (var i = functionDeclarations.Count - 1; i >= 0; i--)
  1076. {
  1077. var d = functionDeclarations[i];
  1078. var fn = d.Id!.Name;
  1079. if (!declaredFunctionNames.Contains(fn))
  1080. {
  1081. if (varEnvRec is GlobalEnvironmentRecord ger)
  1082. {
  1083. var fnDefinable = ger.CanDeclareGlobalFunction(fn);
  1084. if (!fnDefinable)
  1085. {
  1086. ExceptionHelper.ThrowTypeError(realm);
  1087. }
  1088. }
  1089. declaredFunctionNames.Add(fn);
  1090. functionsToInitialize.AddFirst(new JintFunctionDefinition(d));
  1091. }
  1092. }
  1093. }
  1094. var boundNames = new List<string>();
  1095. var declaredVarNames = new List<string>();
  1096. var variableDeclarations = hoistingScope._variablesDeclarations;
  1097. var variableDeclarationsCount = variableDeclarations?.Count;
  1098. for (var i = 0; i < variableDeclarationsCount; i++)
  1099. {
  1100. var variableDeclaration = variableDeclarations![i];
  1101. boundNames.Clear();
  1102. variableDeclaration.GetBoundNames(boundNames);
  1103. for (var j = 0; j < boundNames.Count; j++)
  1104. {
  1105. var vn = boundNames[j];
  1106. if (!declaredFunctionNames.Contains(vn))
  1107. {
  1108. if (varEnvRec is GlobalEnvironmentRecord ger)
  1109. {
  1110. var vnDefinable = ger.CanDeclareGlobalFunction(vn);
  1111. if (!vnDefinable)
  1112. {
  1113. ExceptionHelper.ThrowTypeError(realm);
  1114. }
  1115. }
  1116. declaredVarNames.Add(vn);
  1117. }
  1118. }
  1119. }
  1120. var lexicalDeclarations = hoistingScope._lexicalDeclarations;
  1121. var lexicalDeclarationsCount = lexicalDeclarations?.Count;
  1122. for (var i = 0; i < lexicalDeclarationsCount; i++)
  1123. {
  1124. boundNames.Clear();
  1125. var d = lexicalDeclarations![i];
  1126. d.GetBoundNames(boundNames);
  1127. for (var j = 0; j < boundNames.Count; j++)
  1128. {
  1129. var dn = boundNames[j];
  1130. if (d.IsConstantDeclaration())
  1131. {
  1132. lexEnvRec.CreateImmutableBinding(dn, strict: true);
  1133. }
  1134. else
  1135. {
  1136. lexEnvRec.CreateMutableBinding(dn, canBeDeleted: false);
  1137. }
  1138. }
  1139. }
  1140. foreach (var f in functionsToInitialize)
  1141. {
  1142. var fn = f.Name!;
  1143. var fo = realm.Intrinsics.Function.InstantiateFunctionObject(f, lexEnv, privateEnv);
  1144. if (varEnvRec is GlobalEnvironmentRecord ger)
  1145. {
  1146. ger.CreateGlobalFunctionBinding(fn, fo, canBeDeleted: true);
  1147. }
  1148. else
  1149. {
  1150. var bindingExists = varEnvRec.HasBinding(fn);
  1151. if (!bindingExists)
  1152. {
  1153. varEnvRec.CreateMutableBinding(fn, canBeDeleted: true);
  1154. varEnvRec.InitializeBinding(fn, fo);
  1155. }
  1156. else
  1157. {
  1158. varEnvRec.SetMutableBinding(fn, fo, strict: false);
  1159. }
  1160. }
  1161. }
  1162. foreach (var vn in declaredVarNames)
  1163. {
  1164. if (varEnvRec is GlobalEnvironmentRecord ger)
  1165. {
  1166. ger.CreateGlobalVarBinding(vn, true);
  1167. }
  1168. else
  1169. {
  1170. var bindingExists = varEnvRec.HasBinding(vn);
  1171. if (!bindingExists)
  1172. {
  1173. varEnvRec.CreateMutableBinding(vn, canBeDeleted: true);
  1174. varEnvRec.InitializeBinding(vn, JsValue.Undefined);
  1175. }
  1176. }
  1177. }
  1178. }
  1179. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1180. internal void UpdateLexicalEnvironment(EnvironmentRecord newEnv)
  1181. {
  1182. _executionContexts.ReplaceTopLexicalEnvironment(newEnv);
  1183. }
  1184. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1185. internal void UpdateVariableEnvironment(EnvironmentRecord newEnv)
  1186. {
  1187. _executionContexts.ReplaceTopVariableEnvironment(newEnv);
  1188. }
  1189. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1190. internal void UpdatePrivateEnvironment(PrivateEnvironmentRecord? newEnv)
  1191. {
  1192. _executionContexts.ReplaceTopPrivateEnvironment(newEnv);
  1193. }
  1194. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1195. internal ref readonly ExecutionContext UpdateGenerator(GeneratorInstance generator)
  1196. {
  1197. return ref _executionContexts.ReplaceTopGenerator(generator);
  1198. }
  1199. /// <summary>
  1200. /// Invokes the named callable and returns the resulting object.
  1201. /// </summary>
  1202. /// <param name="callableName">The name of the callable.</param>
  1203. /// <param name="arguments">The arguments of the call.</param>
  1204. /// <returns>The value returned by the call.</returns>
  1205. public JsValue Call(string callableName, params JsValue[] arguments)
  1206. {
  1207. var callable = Evaluate(callableName);
  1208. return Call(callable, arguments);
  1209. }
  1210. /// <summary>
  1211. /// Invokes the callable and returns the resulting object.
  1212. /// </summary>
  1213. /// <param name="callable">The callable.</param>
  1214. /// <param name="arguments">The arguments of the call.</param>
  1215. /// <returns>The value returned by the call.</returns>
  1216. public JsValue Call(JsValue callable, params JsValue[] arguments)
  1217. => Call(callable, thisObject: JsValue.Undefined, arguments);
  1218. /// <summary>
  1219. /// Invokes the callable and returns the resulting object.
  1220. /// </summary>
  1221. /// <param name="callable">The callable.</param>
  1222. /// <param name="thisObject">Value bound as this.</param>
  1223. /// <param name="arguments">The arguments of the call.</param>
  1224. /// <returns>The value returned by the call.</returns>
  1225. public JsValue Call(JsValue callable, JsValue thisObject, JsValue[] arguments)
  1226. {
  1227. JsValue Callback()
  1228. {
  1229. if (!callable.IsCallable)
  1230. {
  1231. ExceptionHelper.ThrowArgumentException(callable + " is not callable");
  1232. }
  1233. return Call((ICallable) callable, thisObject, arguments, null);
  1234. }
  1235. return ExecuteWithConstraints(Options.Strict, Callback);
  1236. }
  1237. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1238. internal JsValue Call(ICallable callable, JsValue thisObject, JsValue[] arguments, JintExpression? expression)
  1239. {
  1240. if (callable is FunctionInstance functionInstance)
  1241. {
  1242. return Call(functionInstance, thisObject, arguments, expression);
  1243. }
  1244. return callable.Call(thisObject, arguments);
  1245. }
  1246. /// <summary>
  1247. /// Calls the named constructor and returns the resulting object.
  1248. /// </summary>
  1249. /// <param name="constructorName">The name of the constructor to call.</param>
  1250. /// <param name="arguments">The arguments of the constructor call.</param>
  1251. /// <returns>The value returned by the constructor call.</returns>
  1252. public ObjectInstance Construct(string constructorName, params JsValue[] arguments)
  1253. {
  1254. var constructor = Evaluate(constructorName);
  1255. return Construct(constructor, arguments);
  1256. }
  1257. /// <summary>
  1258. /// Calls the constructor and returns the resulting object.
  1259. /// </summary>
  1260. /// <param name="constructor">The name of the constructor to call.</param>
  1261. /// <param name="arguments">The arguments of the constructor call.</param>
  1262. /// <returns>The value returned by the constructor call.</returns>
  1263. public ObjectInstance Construct(JsValue constructor, params JsValue[] arguments)
  1264. {
  1265. ObjectInstance Callback()
  1266. {
  1267. if (!constructor.IsConstructor)
  1268. {
  1269. ExceptionHelper.ThrowArgumentException(constructor + " is not a constructor");
  1270. }
  1271. return Construct(constructor, arguments, constructor, null);
  1272. }
  1273. return ExecuteWithConstraints(Options.Strict, Callback);
  1274. }
  1275. internal ObjectInstance Construct(
  1276. JsValue constructor,
  1277. JsValue[] arguments,
  1278. JsValue newTarget,
  1279. JintExpression? expression)
  1280. {
  1281. if (constructor is FunctionInstance functionInstance)
  1282. {
  1283. return Construct(functionInstance, arguments, newTarget, expression);
  1284. }
  1285. return ((IConstructor) constructor).Construct(arguments, newTarget);
  1286. }
  1287. internal JsValue Call(FunctionInstance functionInstance, JsValue thisObject)
  1288. => Call(functionInstance, thisObject, Arguments.Empty, null);
  1289. internal JsValue Call(
  1290. FunctionInstance functionInstance,
  1291. JsValue thisObject,
  1292. JsValue[] arguments,
  1293. JintExpression? expression)
  1294. {
  1295. // ensure logic is in sync between Call, Construct, engine.Invoke and JintCallExpression!
  1296. var recursionDepth = CallStack.Push(functionInstance, expression, ExecutionContext);
  1297. if (recursionDepth > Options.Constraints.MaxRecursionDepth)
  1298. {
  1299. // automatically pops the current element as it was never reached
  1300. ExceptionHelper.ThrowRecursionDepthOverflowException(CallStack);
  1301. }
  1302. JsValue result;
  1303. try
  1304. {
  1305. result = functionInstance.Call(thisObject, arguments);
  1306. }
  1307. finally
  1308. {
  1309. // if call stack was reset due to recursive call to engine or similar, we might not have it anymore
  1310. if (CallStack.Count > 0)
  1311. {
  1312. CallStack.Pop();
  1313. }
  1314. }
  1315. return result;
  1316. }
  1317. private ObjectInstance Construct(
  1318. FunctionInstance functionInstance,
  1319. JsValue[] arguments,
  1320. JsValue newTarget,
  1321. JintExpression? expression)
  1322. {
  1323. // ensure logic is in sync between Call, Construct, engine.Invoke and JintCallExpression!
  1324. var recursionDepth = CallStack.Push(functionInstance, expression, ExecutionContext);
  1325. if (recursionDepth > Options.Constraints.MaxRecursionDepth)
  1326. {
  1327. // automatically pops the current element as it was never reached
  1328. ExceptionHelper.ThrowRecursionDepthOverflowException(CallStack);
  1329. }
  1330. ObjectInstance result;
  1331. try
  1332. {
  1333. result = ((IConstructor) functionInstance).Construct(arguments, newTarget);
  1334. }
  1335. finally
  1336. {
  1337. CallStack.Pop();
  1338. }
  1339. return result;
  1340. }
  1341. internal void SignalError(ErrorDispatchInfo error)
  1342. {
  1343. _error = error;
  1344. }
  1345. internal void RegisterTypeReference(TypeReference reference)
  1346. {
  1347. _typeReferences ??= new Dictionary<Type, TypeReference>();
  1348. _typeReferences[reference.ReferenceType] = reference;
  1349. }
  1350. internal ref readonly ExecutionContext GetExecutionContext(int fromTop)
  1351. {
  1352. return ref _executionContexts.Peek(fromTop);
  1353. }
  1354. public void Dispose()
  1355. {
  1356. if (_objectWrapperCache is null)
  1357. {
  1358. return;
  1359. }
  1360. #if SUPPORTS_WEAK_TABLE_CLEAR
  1361. _objectWrapperCache.Clear();
  1362. #else
  1363. // we can expect that reflection is OK as we've been generating object wrappers already
  1364. var clearMethod = _objectWrapperCache.GetType().GetMethod("Clear", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
  1365. clearMethod?.Invoke(_objectWrapperCache, Array.Empty<object>());
  1366. #endif
  1367. }
  1368. [DebuggerDisplay("Engine")]
  1369. private sealed class EngineDebugView
  1370. {
  1371. private readonly Engine _engine;
  1372. public EngineDebugView(Engine engine)
  1373. {
  1374. _engine = engine;
  1375. }
  1376. public ObjectInstance Globals => _engine.Realm.GlobalObject;
  1377. public Options Options => _engine.Options;
  1378. public EnvironmentRecord VariableEnvironment => _engine.ExecutionContext.VariableEnvironment;
  1379. public EnvironmentRecord LexicalEnvironment => _engine.ExecutionContext.LexicalEnvironment;
  1380. }
  1381. }
  1382. }