Engine.cs 58 KB

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