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