Engine.cs 60 KB

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