Engine.cs 57 KB

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