Engine.cs 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.CompilerServices;
  4. using Esprima;
  5. using Esprima.Ast;
  6. using Jint.Native;
  7. using Jint.Native.Argument;
  8. using Jint.Native.Function;
  9. using Jint.Native.Object;
  10. using Jint.Native.Promise;
  11. using Jint.Native.Symbol;
  12. using Jint.Pooling;
  13. using Jint.Runtime;
  14. using Jint.Runtime.CallStack;
  15. using Jint.Runtime.Debugger;
  16. using Jint.Runtime.Descriptors;
  17. using Jint.Runtime.Environments;
  18. using Jint.Runtime.Interop;
  19. using Jint.Runtime.Interop.Reflection;
  20. using Jint.Runtime.Interpreter;
  21. using Jint.Runtime.Interpreter.Expressions;
  22. using Jint.Runtime.References;
  23. namespace Jint
  24. {
  25. public partial class Engine
  26. {
  27. private static readonly ParserOptions DefaultParserOptions = new("<anonymous>")
  28. {
  29. AdaptRegexp = true,
  30. Tolerant = true
  31. };
  32. private readonly ExecutionContextStack _executionContexts;
  33. private JsValue _completionValue = JsValue.Undefined;
  34. internal EvaluationContext _activeEvaluationContext;
  35. private readonly EventLoop _eventLoop = new();
  36. // lazy properties
  37. private DebugHandler _debugHandler;
  38. // cached access
  39. internal readonly IObjectConverter[] _objectConverters;
  40. private readonly IConstraint[] _constraints;
  41. internal readonly bool _isDebugMode;
  42. internal bool _isStrict;
  43. internal readonly IReferenceResolver _referenceResolver;
  44. internal readonly ReferencePool _referencePool;
  45. internal readonly ArgumentsInstancePool _argumentsInstancePool;
  46. internal readonly JsValueArrayPool _jsValueArrayPool;
  47. internal readonly ExtensionMethodCache _extensionMethods;
  48. public ITypeConverter ClrTypeConverter { get; internal set; }
  49. // cache of types used when resolving CLR type names
  50. internal readonly Dictionary<string, Type> TypeCache = new();
  51. // shared frozen version
  52. internal readonly PropertyDescriptor _callerCalleeArgumentsThrowerConfigurable;
  53. internal readonly PropertyDescriptor _callerCalleeArgumentsThrowerNonConfigurable;
  54. internal readonly JintCallStack CallStack;
  55. // needed in initial engine setup, for example CLR function construction
  56. internal Intrinsics _originalIntrinsics;
  57. internal Host _host;
  58. /// <summary>
  59. /// Constructs a new engine instance.
  60. /// </summary>
  61. public Engine() : this((Action<Options>) null)
  62. {
  63. }
  64. /// <summary>
  65. /// Constructs a new engine instance and allows customizing options.
  66. /// </summary>
  67. public Engine(Action<Options> options)
  68. : this((engine, opts) => options?.Invoke(opts))
  69. {
  70. }
  71. /// <summary>
  72. /// Constructs a new engine with a custom <see cref="Options"/> instance.
  73. /// </summary>
  74. public Engine(Options options) : this((e, o) => e.Options = options)
  75. {
  76. }
  77. /// <summary>
  78. /// Constructs a new engine instance and allows customizing options.
  79. /// </summary>
  80. /// <remarks>The provided engine instance in callback is not guaranteed to be fully configured</remarks>
  81. public Engine(Action<Engine, Options> options)
  82. {
  83. _executionContexts = new ExecutionContextStack(2);
  84. _callerCalleeArgumentsThrowerConfigurable = new GetSetPropertyDescriptor.ThrowerPropertyDescriptor(this,
  85. PropertyFlag.Configurable | PropertyFlag.CustomJsValue,
  86. "'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them");
  87. _callerCalleeArgumentsThrowerNonConfigurable = new GetSetPropertyDescriptor.ThrowerPropertyDescriptor(this,
  88. PropertyFlag.CustomJsValue,
  89. "'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them");
  90. Options = new Options();
  91. options?.Invoke(this, Options);
  92. _extensionMethods = ExtensionMethodCache.Build(Options.Interop.ExtensionMethodTypes);
  93. Reset();
  94. // gather some options as fields for faster checks
  95. _isDebugMode = Options.Debugger.Enabled;
  96. _isStrict = Options.Strict;
  97. _objectConverters = Options.Interop.ObjectConverters.Count > 0
  98. ? Options.Interop.ObjectConverters.ToArray()
  99. : null;
  100. _constraints = Options.Constraints.Constraints.ToArray();
  101. _referenceResolver = Options.ReferenceResolver;
  102. CallStack = new JintCallStack(Options.Constraints.MaxRecursionDepth >= 0);
  103. _referencePool = new ReferencePool();
  104. _argumentsInstancePool = new ArgumentsInstancePool(this);
  105. _jsValueArrayPool = new JsValueArrayPool();
  106. Options.Apply(this);
  107. }
  108. private void Reset()
  109. {
  110. _host = Options.Host.Factory(this);
  111. _host.Initialize(this);
  112. }
  113. internal ref readonly ExecutionContext ExecutionContext
  114. {
  115. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  116. get => ref _executionContexts.Peek();
  117. }
  118. // temporary state for realm so that we can easily pass it to functions while still not
  119. // having a proper execution context established
  120. internal Realm _realmInConstruction;
  121. public Realm Realm => _realmInConstruction ?? ExecutionContext.Realm;
  122. internal GlobalSymbolRegistry GlobalSymbolRegistry { get; } = new();
  123. internal long CurrentMemoryUsage { get; private set; }
  124. internal Options Options
  125. {
  126. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  127. get;
  128. private set;
  129. }
  130. public DebugHandler DebugHandler => _debugHandler ??= new DebugHandler(this);
  131. internal ExecutionContext EnterExecutionContext(
  132. EnvironmentRecord lexicalEnvironment,
  133. EnvironmentRecord variableEnvironment,
  134. Realm realm,
  135. PrivateEnvironmentRecord privateEnvironment)
  136. {
  137. var context = new ExecutionContext(
  138. lexicalEnvironment,
  139. variableEnvironment,
  140. privateEnvironment,
  141. realm,
  142. null);
  143. _executionContexts.Push(context);
  144. return context;
  145. }
  146. internal ExecutionContext EnterExecutionContext(ExecutionContext context)
  147. {
  148. _executionContexts.Push(context);
  149. return context;
  150. }
  151. public Engine SetValue(JsValue name, Delegate value)
  152. {
  153. Realm.GlobalObject.FastAddProperty(name, new DelegateWrapper(this, value), true, false, true);
  154. return this;
  155. }
  156. public Engine SetValue(JsValue name, string value)
  157. {
  158. return SetValue(name, new JsString(value));
  159. }
  160. public Engine SetValue(JsValue name, double value)
  161. {
  162. return SetValue(name, JsNumber.Create(value));
  163. }
  164. public Engine SetValue(JsValue name, int value)
  165. {
  166. return SetValue(name, JsNumber.Create(value));
  167. }
  168. public Engine SetValue(JsValue name, bool value)
  169. {
  170. return SetValue(name, value ? JsBoolean.True : JsBoolean.False);
  171. }
  172. public Engine SetValue(JsValue name, JsValue value)
  173. {
  174. Realm.GlobalObject.Set(name, value);
  175. return this;
  176. }
  177. public Engine SetValue(JsValue name, object obj)
  178. {
  179. var value = obj is Type t
  180. ? TypeReference.CreateTypeReference(this, t)
  181. : JsValue.FromObject(this, obj);
  182. return SetValue(name, value);
  183. }
  184. internal void LeaveExecutionContext()
  185. {
  186. _executionContexts.Pop();
  187. }
  188. /// <summary>
  189. /// Initializes the statements count
  190. /// </summary>
  191. public void ResetConstraints()
  192. {
  193. foreach (var constraint in _constraints)
  194. {
  195. constraint.Reset();
  196. }
  197. }
  198. /// <summary>
  199. /// Initializes list of references of called functions
  200. /// </summary>
  201. public void ResetCallStack()
  202. {
  203. CallStack.Clear();
  204. }
  205. public JsValue Evaluate(string source)
  206. => Execute(source, DefaultParserOptions)._completionValue;
  207. public JsValue Evaluate(string source, ParserOptions parserOptions)
  208. => Execute(source, parserOptions)._completionValue;
  209. public JsValue Evaluate(Script script)
  210. => Execute(script)._completionValue;
  211. public Engine Execute(string source)
  212. => Execute(source, DefaultParserOptions);
  213. public Engine Execute(string source, ParserOptions parserOptions)
  214. => Execute(new JavaScriptParser(source, parserOptions).ParseScript());
  215. public Engine Execute(Script script)
  216. {
  217. Engine DoInvoke()
  218. {
  219. GlobalDeclarationInstantiation(
  220. script,
  221. Realm.GlobalEnv);
  222. var list = new JintStatementList(null, script.Body);
  223. Completion result;
  224. try
  225. {
  226. result = list.Execute(_activeEvaluationContext);
  227. }
  228. catch
  229. {
  230. // unhandled exception
  231. ResetCallStack();
  232. throw;
  233. }
  234. if (result.Type == CompletionType.Throw)
  235. {
  236. var ex = new JavaScriptException(result.GetValueOrDefault()).SetCallstack(this, result.Location);
  237. ResetCallStack();
  238. throw ex;
  239. }
  240. // TODO what about callstack and thrown exceptions?
  241. RunAvailableContinuations(_eventLoop);
  242. _completionValue = result.GetValueOrDefault();
  243. return this;
  244. }
  245. var strict = _isStrict | script.Strict;
  246. ExecuteWithConstraints(strict, DoInvoke);
  247. return this;
  248. }
  249. /// <summary>
  250. /// EXPERIMENTAL! Subject to change.
  251. ///
  252. /// Registers a promise within the currently running EventLoop (has to be called within "ExecuteWithEventLoop" call).
  253. /// Note that ExecuteWithEventLoop will not trigger "onFinished" callback until ALL manual promises are settled.
  254. ///
  255. /// NOTE: that resolve and reject need to be called withing the same thread as "ExecuteWithEventLoop".
  256. /// The API assumes that the Engine is called from a single thread.
  257. /// </summary>
  258. /// <returns>a Promise instance and functions to either resolve or reject it</returns>
  259. public ManualPromise RegisterPromise()
  260. {
  261. var promise = new PromiseInstance(this)
  262. {
  263. _prototype = Realm.Intrinsics.Promise.PrototypeObject
  264. };
  265. var (resolve, reject) = promise.CreateResolvingFunctions();
  266. Action<JsValue> SettleWith(FunctionInstance settle) => value =>
  267. {
  268. settle.Call(JsValue.Undefined, new[] {value});
  269. RunAvailableContinuations(_eventLoop);
  270. };
  271. return new ManualPromise(promise, SettleWith(resolve), SettleWith(reject));
  272. }
  273. internal void AddToEventLoop(Action continuation)
  274. {
  275. _eventLoop.Events.Enqueue(continuation);
  276. }
  277. private static void RunAvailableContinuations(EventLoop loop)
  278. {
  279. var queue = loop.Events;
  280. while (true)
  281. {
  282. if (queue.Count == 0)
  283. {
  284. return;
  285. }
  286. var nextContinuation = queue.Dequeue();
  287. // note that continuation can enqueue new events
  288. nextContinuation();
  289. }
  290. }
  291. internal void RunBeforeExecuteStatementChecks(Statement statement)
  292. {
  293. // Avoid allocating the enumerator because we run this loop very often.
  294. foreach (var constraint in _constraints)
  295. {
  296. constraint.Check();
  297. }
  298. if (_isDebugMode)
  299. {
  300. DebugHandler.OnStep(statement);
  301. }
  302. }
  303. /// <summary>
  304. /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.7.1
  305. /// </summary>
  306. public JsValue GetValue(object value)
  307. {
  308. return GetValue(value, false);
  309. }
  310. internal JsValue GetValue(object value, bool returnReferenceToPool)
  311. {
  312. if (value is JsValue jsValue)
  313. {
  314. return jsValue;
  315. }
  316. if (value is not Reference reference)
  317. {
  318. return ((Completion) value).Value;
  319. }
  320. return GetValue(reference, returnReferenceToPool);
  321. }
  322. internal JsValue GetValue(Reference reference, bool returnReferenceToPool)
  323. {
  324. var baseValue = reference.GetBase();
  325. if (baseValue.IsUndefined())
  326. {
  327. if (_referenceResolver.TryUnresolvableReference(this, reference, out JsValue val))
  328. {
  329. return val;
  330. }
  331. ExceptionHelper.ThrowReferenceError(Realm, reference);
  332. }
  333. if ((baseValue._type & InternalTypes.ObjectEnvironmentRecord) == 0
  334. && _referenceResolver.TryPropertyReference(this, reference, ref baseValue))
  335. {
  336. return baseValue;
  337. }
  338. if (reference.IsPropertyReference())
  339. {
  340. var property = reference.GetReferencedName();
  341. if (returnReferenceToPool)
  342. {
  343. _referencePool.Return(reference);
  344. }
  345. if (baseValue.IsObject())
  346. {
  347. var o = TypeConverter.ToObject(Realm, baseValue);
  348. var v = o.Get(property, reference.GetThisValue());
  349. return v;
  350. }
  351. else
  352. {
  353. // check if we are accessing a string, boxing operation can be costly to do index access
  354. // we have good chance to have fast path with integer or string indexer
  355. ObjectInstance o = null;
  356. if ((property._type & (InternalTypes.String | InternalTypes.Integer)) != 0
  357. && baseValue is JsString s
  358. && TryHandleStringValue(property, s, ref o, out var jsValue))
  359. {
  360. return jsValue;
  361. }
  362. if (o is null)
  363. {
  364. o = TypeConverter.ToObject(Realm, baseValue);
  365. }
  366. var desc = o.GetProperty(property);
  367. if (desc == PropertyDescriptor.Undefined)
  368. {
  369. return JsValue.Undefined;
  370. }
  371. if (desc.IsDataDescriptor())
  372. {
  373. return desc.Value;
  374. }
  375. var getter = desc.Get;
  376. if (getter.IsUndefined())
  377. {
  378. return Undefined.Instance;
  379. }
  380. var callable = (ICallable) getter.AsObject();
  381. return callable.Call(baseValue, Arguments.Empty);
  382. }
  383. }
  384. var record = baseValue as EnvironmentRecord;
  385. if (record is null)
  386. {
  387. ExceptionHelper.ThrowArgumentException();
  388. }
  389. var bindingValue = record.GetBindingValue(reference.GetReferencedName().ToString(), reference.IsStrictReference());
  390. if (returnReferenceToPool)
  391. {
  392. _referencePool.Return(reference);
  393. }
  394. return bindingValue;
  395. }
  396. private bool TryHandleStringValue(JsValue property, JsString s, ref ObjectInstance o, out JsValue jsValue)
  397. {
  398. if (property == CommonProperties.Length)
  399. {
  400. jsValue = JsNumber.Create((uint) s.Length);
  401. return true;
  402. }
  403. if (property is JsNumber number && number.IsInteger())
  404. {
  405. var index = number.AsInteger();
  406. var str = s._value;
  407. if (index < 0 || index >= str.Length)
  408. {
  409. jsValue = JsValue.Undefined;
  410. return true;
  411. }
  412. jsValue = JsString.Create(str[index]);
  413. return true;
  414. }
  415. if (property is JsString propertyString
  416. && propertyString._value.Length > 0
  417. && char.IsLower(propertyString._value[0]))
  418. {
  419. // trying to find property that's always in prototype
  420. o = Realm.Intrinsics.String.PrototypeObject;
  421. }
  422. jsValue = JsValue.Undefined;
  423. return false;
  424. }
  425. /// <summary>
  426. /// https://tc39.es/ecma262/#sec-putvalue
  427. /// </summary>
  428. internal void PutValue(Reference reference, JsValue value)
  429. {
  430. var baseValue = reference.GetBase();
  431. if (reference.IsUnresolvableReference())
  432. {
  433. if (reference.IsStrictReference())
  434. {
  435. ExceptionHelper.ThrowReferenceError(Realm, reference);
  436. }
  437. Realm.GlobalObject.Set(reference.GetReferencedName(), value, throwOnError: false);
  438. }
  439. else if (reference.IsPropertyReference())
  440. {
  441. if (reference.HasPrimitiveBase())
  442. {
  443. baseValue = TypeConverter.ToObject(Realm, baseValue);
  444. }
  445. var succeeded = baseValue.Set(reference.GetReferencedName(), value, reference.GetThisValue());
  446. if (!succeeded && reference.IsStrictReference())
  447. {
  448. ExceptionHelper.ThrowTypeError(Realm);
  449. }
  450. }
  451. else
  452. {
  453. ((EnvironmentRecord) baseValue).SetMutableBinding(TypeConverter.ToString(reference.GetReferencedName()),
  454. value, reference.IsStrictReference());
  455. }
  456. }
  457. /// <summary>
  458. /// http://www.ecma-international.org/ecma-262/6.0/#sec-initializereferencedbinding
  459. /// </summary>
  460. public void InitializeReferenceBinding(Reference reference, JsValue value)
  461. {
  462. var baseValue = (EnvironmentRecord) reference.GetBase();
  463. baseValue.InitializeBinding(TypeConverter.ToString(reference.GetReferencedName()), value);
  464. }
  465. /// <summary>
  466. /// Invoke the current value as function.
  467. /// </summary>
  468. /// <param name="propertyName">The name of the function to call.</param>
  469. /// <param name="arguments">The arguments of the function call.</param>
  470. /// <returns>The value returned by the function call.</returns>
  471. public JsValue Invoke(string propertyName, params object[] arguments)
  472. {
  473. return Invoke(propertyName, null, arguments);
  474. }
  475. /// <summary>
  476. /// Invoke the current value as function.
  477. /// </summary>
  478. /// <param name="propertyName">The name of the function to call.</param>
  479. /// <param name="thisObj">The this value inside the function call.</param>
  480. /// <param name="arguments">The arguments of the function call.</param>
  481. /// <returns>The value returned by the function call.</returns>
  482. public JsValue Invoke(string propertyName, object thisObj, object[] arguments)
  483. {
  484. var value = GetValue(propertyName);
  485. return Invoke(value, thisObj, arguments);
  486. }
  487. /// <summary>
  488. /// Invoke the current value as function.
  489. /// </summary>
  490. /// <param name="value">The function to call.</param>
  491. /// <param name="arguments">The arguments of the function call.</param>
  492. /// <returns>The value returned by the function call.</returns>
  493. public JsValue Invoke(JsValue value, params object[] arguments)
  494. {
  495. return Invoke(value, null, arguments);
  496. }
  497. /// <summary>
  498. /// Invoke the current value as function.
  499. /// </summary>
  500. /// <param name="value">The function to call.</param>
  501. /// <param name="thisObj">The this value inside the function call.</param>
  502. /// <param name="arguments">The arguments of the function call.</param>
  503. /// <returns>The value returned by the function call.</returns>
  504. public JsValue Invoke(JsValue value, object thisObj, object[] arguments)
  505. {
  506. var callable = value as ICallable;
  507. if (callable is null)
  508. {
  509. ExceptionHelper.ThrowTypeError(Realm, "Can only invoke functions");
  510. }
  511. JsValue DoInvoke()
  512. {
  513. var items = _jsValueArrayPool.RentArray(arguments.Length);
  514. for (var i = 0; i < arguments.Length; ++i)
  515. {
  516. items[i] = JsValue.FromObject(this, arguments[i]);
  517. }
  518. var result = callable.Call(JsValue.FromObject(this, thisObj), items);
  519. _jsValueArrayPool.ReturnArray(items);
  520. return result;
  521. }
  522. return ExecuteWithConstraints(Options.Strict, DoInvoke);
  523. }
  524. private T ExecuteWithConstraints<T>(bool strict, Func<T> callback)
  525. {
  526. ResetConstraints();
  527. var ownsContext = _activeEvaluationContext is null;
  528. _activeEvaluationContext ??= new EvaluationContext(this);
  529. var oldStrict = _isStrict;
  530. try
  531. {
  532. _isStrict = strict;
  533. using (new StrictModeScope(_isStrict))
  534. {
  535. return callback();
  536. }
  537. }
  538. finally
  539. {
  540. if (ownsContext)
  541. {
  542. _activeEvaluationContext = null;
  543. }
  544. _isStrict = oldStrict;
  545. ResetConstraints();
  546. }
  547. }
  548. /// <summary>
  549. /// https://tc39.es/ecma262/#sec-invoke
  550. /// </summary>
  551. internal JsValue Invoke(JsValue v, JsValue p, JsValue[] arguments)
  552. {
  553. var ownsContext = _activeEvaluationContext is null;
  554. _activeEvaluationContext ??= new EvaluationContext(this);
  555. try
  556. {
  557. var func = GetV(v, p);
  558. var callable = func as ICallable;
  559. if (callable is null)
  560. {
  561. ExceptionHelper.ThrowTypeErrorNoEngine("Can only invoke functions");
  562. }
  563. return callable.Call(v, arguments);
  564. }
  565. finally
  566. {
  567. if (ownsContext)
  568. {
  569. _activeEvaluationContext = null;
  570. }
  571. }
  572. }
  573. /// <summary>
  574. /// https://tc39.es/ecma262/#sec-getv
  575. /// </summary>
  576. private JsValue GetV(JsValue v, JsValue p)
  577. {
  578. var o = TypeConverter.ToObject(Realm, v);
  579. return o.Get(p);
  580. }
  581. /// <summary>
  582. /// Gets a named value from the Global scope.
  583. /// </summary>
  584. /// <param name="propertyName">The name of the property to return.</param>
  585. public JsValue GetValue(string propertyName)
  586. {
  587. return GetValue(Realm.GlobalObject, new JsString(propertyName));
  588. }
  589. /// <summary>
  590. /// Gets the last evaluated <see cref="Node"/>.
  591. /// </summary>
  592. internal Node GetLastSyntaxNode()
  593. {
  594. return _activeEvaluationContext?.LastSyntaxNode;
  595. }
  596. /// <summary>
  597. /// Gets a named value from the specified scope.
  598. /// </summary>
  599. /// <param name="scope">The scope to get the property from.</param>
  600. /// <param name="property">The name of the property to return.</param>
  601. public JsValue GetValue(JsValue scope, JsValue property)
  602. {
  603. var reference = _referencePool.Rent(scope, property, _isStrict, thisValue: null);
  604. var jsValue = GetValue(reference, false);
  605. _referencePool.Return(reference);
  606. return jsValue;
  607. }
  608. /// <summary>
  609. /// https://tc39.es/ecma262/#sec-resolvebinding
  610. /// </summary>
  611. internal Reference ResolveBinding(string name, EnvironmentRecord env = null)
  612. {
  613. env ??= ExecutionContext.LexicalEnvironment;
  614. return GetIdentifierReference(env, name, StrictModeScope.IsStrictModeCode);
  615. }
  616. private static Reference GetIdentifierReference(EnvironmentRecord env, string name, bool strict)
  617. {
  618. if (env is null)
  619. {
  620. return new Reference(JsValue.Undefined, name, strict);
  621. }
  622. var envRec = env;
  623. if (envRec.HasBinding(name))
  624. {
  625. return new Reference(envRec, name, strict);
  626. }
  627. return GetIdentifierReference(env._outerEnv, name, strict);
  628. }
  629. /// <summary>
  630. /// https://tc39.es/ecma262/#sec-getnewtarget
  631. /// </summary>
  632. internal JsValue GetNewTarget(EnvironmentRecord thisEnvironment = null)
  633. {
  634. // we can take as argument if caller site has already determined the value, otherwise resolve
  635. thisEnvironment ??= ExecutionContext.GetThisEnvironment();
  636. return thisEnvironment.NewTarget;
  637. }
  638. /// <summary>
  639. /// https://tc39.es/ecma262/#sec-resolvethisbinding
  640. /// </summary>
  641. internal JsValue ResolveThisBinding()
  642. {
  643. var envRec = ExecutionContext.GetThisEnvironment();
  644. return envRec.GetThisBinding();
  645. }
  646. /// <summary>
  647. /// https://tc39.es/ecma262/#sec-globaldeclarationinstantiation
  648. /// </summary>
  649. private void GlobalDeclarationInstantiation(
  650. Script script,
  651. GlobalEnvironmentRecord env)
  652. {
  653. var hoistingScope = HoistingScope.GetProgramLevelDeclarations(script);
  654. var functionDeclarations = hoistingScope._functionDeclarations;
  655. var varDeclarations = hoistingScope._variablesDeclarations;
  656. var lexDeclarations = hoistingScope._lexicalDeclarations;
  657. var functionToInitialize = new LinkedList<JintFunctionDefinition>();
  658. var declaredFunctionNames = new HashSet<string>();
  659. var declaredVarNames = new List<string>();
  660. var realm = Realm;
  661. if (functionDeclarations != null)
  662. {
  663. for (var i = functionDeclarations.Count - 1; i >= 0; i--)
  664. {
  665. var d = functionDeclarations[i];
  666. var fn = d.Id.Name;
  667. if (!declaredFunctionNames.Contains(fn))
  668. {
  669. var fnDefinable = env.CanDeclareGlobalFunction(fn);
  670. if (!fnDefinable)
  671. {
  672. ExceptionHelper.ThrowTypeError(realm);
  673. }
  674. declaredFunctionNames.Add(fn);
  675. functionToInitialize.AddFirst(new JintFunctionDefinition(this, d));
  676. }
  677. }
  678. }
  679. var boundNames = new List<string>();
  680. if (varDeclarations != null)
  681. {
  682. for (var i = 0; i < varDeclarations.Count; i++)
  683. {
  684. var d = varDeclarations[i];
  685. boundNames.Clear();
  686. d.GetBoundNames(boundNames);
  687. for (var j = 0; j < boundNames.Count; j++)
  688. {
  689. var vn = boundNames[j];
  690. if (env.HasLexicalDeclaration(vn))
  691. {
  692. ExceptionHelper.ThrowSyntaxError(realm, $"Identifier '{vn}' has already been declared");
  693. }
  694. if (!declaredFunctionNames.Contains(vn))
  695. {
  696. var vnDefinable = env.CanDeclareGlobalVar(vn);
  697. if (!vnDefinable)
  698. {
  699. ExceptionHelper.ThrowTypeError(realm);
  700. }
  701. declaredVarNames.Add(vn);
  702. }
  703. }
  704. }
  705. }
  706. if (lexDeclarations != null)
  707. {
  708. for (var i = 0; i < lexDeclarations.Count; i++)
  709. {
  710. var d = lexDeclarations[i];
  711. boundNames.Clear();
  712. d.GetBoundNames(boundNames);
  713. for (var j = 0; j < boundNames.Count; j++)
  714. {
  715. var dn = boundNames[j];
  716. if (env.HasVarDeclaration(dn)
  717. || env.HasLexicalDeclaration(dn)
  718. || env.HasRestrictedGlobalProperty(dn))
  719. {
  720. ExceptionHelper.ThrowSyntaxError(realm, $"Identifier '{dn}' has already been declared");
  721. }
  722. if (d.Kind == VariableDeclarationKind.Const)
  723. {
  724. env.CreateImmutableBinding(dn, strict: true);
  725. }
  726. else
  727. {
  728. env.CreateMutableBinding(dn, canBeDeleted: false);
  729. }
  730. }
  731. }
  732. }
  733. foreach (var f in functionToInitialize)
  734. {
  735. var fn = f.Name;
  736. if (env.HasLexicalDeclaration(fn))
  737. {
  738. ExceptionHelper.ThrowSyntaxError(realm, $"Identifier '{fn}' has already been declared");
  739. }
  740. var fo = realm.Intrinsics.Function.InstantiateFunctionObject(f, env);
  741. env.CreateGlobalFunctionBinding(fn, fo, canBeDeleted: false);
  742. }
  743. for (var i = 0; i < declaredVarNames.Count; i++)
  744. {
  745. var vn = declaredVarNames[i];
  746. env.CreateGlobalVarBinding(vn, canBeDeleted: false);
  747. }
  748. }
  749. /// <summary>
  750. /// https://tc39.es/ecma262/#sec-functiondeclarationinstantiation
  751. /// </summary>
  752. internal ArgumentsInstance FunctionDeclarationInstantiation(
  753. FunctionInstance functionInstance,
  754. JsValue[] argumentsList)
  755. {
  756. var calleeContext = ExecutionContext;
  757. var func = functionInstance._functionDefinition;
  758. var env = (FunctionEnvironmentRecord) ExecutionContext.LexicalEnvironment;
  759. var strict = StrictModeScope.IsStrictModeCode;
  760. var configuration = func.Initialize(functionInstance);
  761. var parameterNames = configuration.ParameterNames;
  762. var hasDuplicates = configuration.HasDuplicates;
  763. var simpleParameterList = configuration.IsSimpleParameterList;
  764. var hasParameterExpressions = configuration.HasParameterExpressions;
  765. var canInitializeParametersOnDeclaration = simpleParameterList && !configuration.HasDuplicates;
  766. env.InitializeParameters(parameterNames, hasDuplicates,
  767. canInitializeParametersOnDeclaration ? argumentsList : null);
  768. ArgumentsInstance ao = null;
  769. if (configuration.ArgumentsObjectNeeded)
  770. {
  771. if (strict || !simpleParameterList)
  772. {
  773. ao = CreateUnmappedArgumentsObject(argumentsList);
  774. }
  775. else
  776. {
  777. // NOTE: mapped argument object is only provided for non-strict functions that don't have a rest parameter,
  778. // any parameter default value initializers, or any destructured parameters.
  779. ao = CreateMappedArgumentsObject(functionInstance, parameterNames, argumentsList, env, configuration.HasRestParameter);
  780. }
  781. if (strict)
  782. {
  783. env.CreateImmutableBindingAndInitialize(KnownKeys.Arguments, strict: false, ao);
  784. }
  785. else
  786. {
  787. env.CreateMutableBindingAndInitialize(KnownKeys.Arguments, canBeDeleted: false, ao);
  788. }
  789. }
  790. if (!canInitializeParametersOnDeclaration)
  791. {
  792. // slower set
  793. env.AddFunctionParameters(_activeEvaluationContext, func.Function, argumentsList);
  794. }
  795. // Let iteratorRecord be CreateListIteratorRecord(argumentsList).
  796. // If hasDuplicates is true, then
  797. // Perform ? IteratorBindingInitialization for formals with iteratorRecord and undefined as arguments.
  798. // Else,
  799. // Perform ? IteratorBindingInitialization for formals with iteratorRecord and env as arguments.
  800. EnvironmentRecord varEnv;
  801. if (!hasParameterExpressions)
  802. {
  803. // NOTE: Only a single lexical environment is needed for the parameters and top-level vars.
  804. for (var i = 0; i < configuration.VarsToInitialize.Count; i++)
  805. {
  806. var pair = configuration.VarsToInitialize[i];
  807. env.CreateMutableBindingAndInitialize(pair.Name, canBeDeleted: false, JsValue.Undefined);
  808. }
  809. varEnv = env;
  810. }
  811. else
  812. {
  813. // NOTE: A separate Environment Record is needed to ensure that closures created by expressions
  814. // in the formal parameter list do not have visibility of declarations in the function body.
  815. var varEnvRec = JintEnvironment.NewDeclarativeEnvironment(this, env);
  816. varEnv = varEnvRec;
  817. UpdateVariableEnvironment(varEnv);
  818. for (var i = 0; i < configuration.VarsToInitialize.Count; i++)
  819. {
  820. var pair = configuration.VarsToInitialize[i];
  821. var initialValue = pair.InitialValue ?? env.GetBindingValue(pair.Name, strict: false);
  822. varEnvRec.CreateMutableBindingAndInitialize(pair.Name, canBeDeleted: false, initialValue);
  823. }
  824. }
  825. // NOTE: Annex B.3.3.1 adds additional steps at this point.
  826. // A https://tc39.es/ecma262/#sec-web-compat-functiondeclarationinstantiation
  827. EnvironmentRecord lexEnv;
  828. if (!strict)
  829. {
  830. lexEnv = JintEnvironment.NewDeclarativeEnvironment(this, varEnv);
  831. // NOTE: Non-strict functions use a separate lexical Environment Record for top-level lexical declarations
  832. // so that a direct eval can determine whether any var scoped declarations introduced by the eval code conflict
  833. // with pre-existing top-level lexically scoped declarations. This is not needed for strict functions
  834. // because a strict direct eval always places all declarations into a new Environment Record.
  835. }
  836. else
  837. {
  838. lexEnv = varEnv;
  839. }
  840. UpdateLexicalEnvironment(lexEnv);
  841. if (configuration.LexicalDeclarations.Length > 0)
  842. {
  843. foreach (var d in configuration.LexicalDeclarations)
  844. {
  845. for (var j = 0; j < d.BoundNames.Count; j++)
  846. {
  847. var dn = d.BoundNames[j];
  848. if (d.Kind == VariableDeclarationKind.Const)
  849. {
  850. lexEnv.CreateImmutableBinding(dn, strict: true);
  851. }
  852. else
  853. {
  854. lexEnv.CreateMutableBinding(dn, canBeDeleted: false);
  855. }
  856. }
  857. }
  858. }
  859. if (configuration.FunctionsToInitialize != null)
  860. {
  861. var privateEnv = calleeContext.PrivateEnvironment;
  862. var realm = Realm;
  863. foreach (var f in configuration.FunctionsToInitialize)
  864. {
  865. var fn = f.Name;
  866. var fo = realm.Intrinsics.Function.InstantiateFunctionObject(f, lexEnv);
  867. varEnv.SetMutableBinding(fn, fo, strict: false);
  868. }
  869. }
  870. return ao;
  871. }
  872. private ArgumentsInstance CreateMappedArgumentsObject(
  873. FunctionInstance func,
  874. Key[] formals,
  875. JsValue[] argumentsList,
  876. DeclarativeEnvironmentRecord envRec,
  877. bool hasRestParameter)
  878. {
  879. return _argumentsInstancePool.Rent(func, formals, argumentsList, envRec, hasRestParameter);
  880. }
  881. private ArgumentsInstance CreateUnmappedArgumentsObject(JsValue[] argumentsList)
  882. {
  883. return _argumentsInstancePool.Rent(argumentsList);
  884. }
  885. /// <summary>
  886. /// https://tc39.es/ecma262/#sec-evaldeclarationinstantiation
  887. /// </summary>
  888. internal void EvalDeclarationInstantiation(
  889. Script script,
  890. EnvironmentRecord varEnv,
  891. EnvironmentRecord lexEnv,
  892. PrivateEnvironmentRecord privateEnv,
  893. bool strict)
  894. {
  895. var hoistingScope = HoistingScope.GetProgramLevelDeclarations(script);
  896. var lexEnvRec = (DeclarativeEnvironmentRecord) lexEnv;
  897. var varEnvRec = varEnv;
  898. var realm = Realm;
  899. if (!strict && hoistingScope._variablesDeclarations != null)
  900. {
  901. if (varEnvRec is GlobalEnvironmentRecord globalEnvironmentRecord)
  902. {
  903. ref readonly var nodes = ref hoistingScope._variablesDeclarations;
  904. for (var i = 0; i < nodes.Count; i++)
  905. {
  906. var variablesDeclaration = nodes[i];
  907. var identifier = (Identifier) variablesDeclaration.Declarations[0].Id;
  908. if (globalEnvironmentRecord.HasLexicalDeclaration(identifier.Name))
  909. {
  910. ExceptionHelper.ThrowSyntaxError(realm, "Identifier '" + identifier.Name + "' has already been declared");
  911. }
  912. }
  913. }
  914. var thisLex = lexEnv;
  915. while (!ReferenceEquals(thisLex, varEnv))
  916. {
  917. var thisEnvRec = thisLex;
  918. if (!(thisEnvRec is ObjectEnvironmentRecord))
  919. {
  920. ref readonly var nodes = ref hoistingScope._variablesDeclarations;
  921. for (var i = 0; i < nodes.Count; i++)
  922. {
  923. var variablesDeclaration = nodes[i];
  924. var identifier = (Identifier) variablesDeclaration.Declarations[0].Id;
  925. if (thisEnvRec.HasBinding(identifier.Name))
  926. {
  927. ExceptionHelper.ThrowSyntaxError(realm);
  928. }
  929. }
  930. }
  931. thisLex = thisLex._outerEnv;
  932. }
  933. }
  934. var functionDeclarations = hoistingScope._functionDeclarations;
  935. var functionsToInitialize = new LinkedList<JintFunctionDefinition>();
  936. var declaredFunctionNames = new HashSet<string>();
  937. if (functionDeclarations != null)
  938. {
  939. for (var i = functionDeclarations.Count - 1; i >= 0; i--)
  940. {
  941. var d = functionDeclarations[i];
  942. var fn = d.Id.Name;
  943. if (!declaredFunctionNames.Contains(fn))
  944. {
  945. if (varEnvRec is GlobalEnvironmentRecord ger)
  946. {
  947. var fnDefinable = ger.CanDeclareGlobalFunction(fn);
  948. if (!fnDefinable)
  949. {
  950. ExceptionHelper.ThrowTypeError(realm);
  951. }
  952. }
  953. declaredFunctionNames.Add(fn);
  954. functionsToInitialize.AddFirst(new JintFunctionDefinition(this, d));
  955. }
  956. }
  957. }
  958. var boundNames = new List<string>();
  959. var declaredVarNames = new List<string>();
  960. var variableDeclarations = hoistingScope._variablesDeclarations;
  961. var variableDeclarationsCount = variableDeclarations?.Count;
  962. for (var i = 0; i < variableDeclarationsCount; i++)
  963. {
  964. var variableDeclaration = variableDeclarations[i];
  965. boundNames.Clear();
  966. variableDeclaration.GetBoundNames(boundNames);
  967. for (var j = 0; j < boundNames.Count; j++)
  968. {
  969. var vn = boundNames[j];
  970. if (!declaredFunctionNames.Contains(vn))
  971. {
  972. if (varEnvRec is GlobalEnvironmentRecord ger)
  973. {
  974. var vnDefinable = ger.CanDeclareGlobalFunction(vn);
  975. if (!vnDefinable)
  976. {
  977. ExceptionHelper.ThrowTypeError(realm);
  978. }
  979. }
  980. declaredVarNames.Add(vn);
  981. }
  982. }
  983. }
  984. var lexicalDeclarations = hoistingScope._lexicalDeclarations;
  985. var lexicalDeclarationsCount = lexicalDeclarations?.Count;
  986. for (var i = 0; i < lexicalDeclarationsCount; i++)
  987. {
  988. boundNames.Clear();
  989. var d = lexicalDeclarations[i];
  990. d.GetBoundNames(boundNames);
  991. for (var j = 0; j < boundNames.Count; j++)
  992. {
  993. var dn = boundNames[j];
  994. if (d.Kind == VariableDeclarationKind.Const)
  995. {
  996. lexEnvRec.CreateImmutableBinding(dn, strict: true);
  997. }
  998. else
  999. {
  1000. lexEnvRec.CreateMutableBinding(dn, canBeDeleted: false);
  1001. }
  1002. }
  1003. }
  1004. foreach (var f in functionsToInitialize)
  1005. {
  1006. var fn = f.Name;
  1007. var fo = realm.Intrinsics.Function.InstantiateFunctionObject(f, lexEnv);
  1008. if (varEnvRec is GlobalEnvironmentRecord ger)
  1009. {
  1010. ger.CreateGlobalFunctionBinding(fn, fo, canBeDeleted: true);
  1011. }
  1012. else
  1013. {
  1014. var bindingExists = varEnvRec.HasBinding(fn);
  1015. if (!bindingExists)
  1016. {
  1017. varEnvRec.CreateMutableBinding(fn, canBeDeleted: true);
  1018. varEnvRec.InitializeBinding(fn, fo);
  1019. }
  1020. else
  1021. {
  1022. varEnvRec.SetMutableBinding(fn, fo, strict: false);
  1023. }
  1024. }
  1025. }
  1026. foreach (var vn in declaredVarNames)
  1027. {
  1028. if (varEnvRec is GlobalEnvironmentRecord ger)
  1029. {
  1030. ger.CreateGlobalVarBinding(vn, true);
  1031. }
  1032. else
  1033. {
  1034. var bindingExists = varEnvRec.HasBinding(vn);
  1035. if (!bindingExists)
  1036. {
  1037. varEnvRec.CreateMutableBinding(vn, canBeDeleted: true);
  1038. varEnvRec.InitializeBinding(vn, JsValue.Undefined);
  1039. }
  1040. }
  1041. }
  1042. }
  1043. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1044. internal void UpdateLexicalEnvironment(EnvironmentRecord newEnv)
  1045. {
  1046. _executionContexts.ReplaceTopLexicalEnvironment(newEnv);
  1047. }
  1048. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1049. internal void UpdateVariableEnvironment(EnvironmentRecord newEnv)
  1050. {
  1051. _executionContexts.ReplaceTopVariableEnvironment(newEnv);
  1052. }
  1053. internal JsValue Call(ICallable callable, JsValue thisObject, JsValue[] arguments, JintExpression expression)
  1054. {
  1055. if (callable is FunctionInstance functionInstance)
  1056. {
  1057. return Call(functionInstance, thisObject, arguments, expression);
  1058. }
  1059. return callable.Call(thisObject, arguments);
  1060. }
  1061. internal JsValue Construct(IConstructor constructor, JsValue[] arguments, JsValue newTarget,
  1062. JintExpression expression)
  1063. {
  1064. if (constructor is FunctionInstance functionInstance)
  1065. {
  1066. return Construct(functionInstance, arguments, newTarget, expression);
  1067. }
  1068. return constructor.Construct(arguments, newTarget);
  1069. }
  1070. internal JsValue Call(
  1071. FunctionInstance functionInstance,
  1072. JsValue thisObject,
  1073. JsValue[] arguments,
  1074. JintExpression expression)
  1075. {
  1076. var callStackElement = new CallStackElement(functionInstance, expression, ExecutionContext);
  1077. var recursionDepth = CallStack.Push(callStackElement);
  1078. if (recursionDepth > Options.Constraints.MaxRecursionDepth)
  1079. {
  1080. // pop the current element as it was never reached
  1081. CallStack.Pop();
  1082. ExceptionHelper.ThrowRecursionDepthOverflowException(CallStack, callStackElement.ToString());
  1083. }
  1084. var result = functionInstance.Call(thisObject, arguments);
  1085. CallStack.Pop();
  1086. return result;
  1087. }
  1088. internal JsValue Construct(
  1089. FunctionInstance functionInstance,
  1090. JsValue[] arguments,
  1091. JsValue newTarget,
  1092. JintExpression expression)
  1093. {
  1094. var callStackElement = new CallStackElement(functionInstance, expression, ExecutionContext);
  1095. var recursionDepth = CallStack.Push(callStackElement);
  1096. if (recursionDepth > Options.Constraints.MaxRecursionDepth)
  1097. {
  1098. // pop the current element as it was never reached
  1099. CallStack.Pop();
  1100. ExceptionHelper.ThrowRecursionDepthOverflowException(CallStack, callStackElement.ToString());
  1101. }
  1102. var result = ((IConstructor) functionInstance).Construct(arguments, newTarget);
  1103. CallStack.Pop();
  1104. return result;
  1105. }
  1106. }
  1107. }