Engine.cs 46 KB

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