Engine.cs 47 KB

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