12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406 |
- using System;
- using System.Collections.Generic;
- using System.Runtime.CompilerServices;
- using Esprima;
- using Esprima.Ast;
- using Jint.Native;
- using Jint.Native.Argument;
- using Jint.Native.Function;
- using Jint.Native.Object;
- using Jint.Native.Promise;
- using Jint.Native.Symbol;
- using Jint.Pooling;
- using Jint.Runtime;
- using Jint.Runtime.CallStack;
- using Jint.Runtime.Debugger;
- using Jint.Runtime.Descriptors;
- using Jint.Runtime.Environments;
- using Jint.Runtime.Interop;
- using Jint.Runtime.Interop.Reflection;
- using Jint.Runtime.Interpreter;
- using Jint.Runtime.Interpreter.Expressions;
- using Jint.Runtime.References;
- namespace Jint
- {
- public sealed partial class Engine : IDisposable
- {
- private static readonly ParserOptions DefaultParserOptions = new("<anonymous>")
- {
- AdaptRegexp = true,
- Tolerant = true
- };
- private readonly ExecutionContextStack _executionContexts;
- private JsValue _completionValue = JsValue.Undefined;
- internal EvaluationContext _activeEvaluationContext;
- private readonly EventLoop _eventLoop = new();
- // lazy properties
- private DebugHandler _debugHandler;
- // cached access
- internal readonly IObjectConverter[] _objectConverters;
- private readonly IConstraint[] _constraints;
- internal readonly bool _isDebugMode;
- internal bool _isStrict;
- internal readonly IReferenceResolver _referenceResolver;
- internal readonly ReferencePool _referencePool;
- internal readonly ArgumentsInstancePool _argumentsInstancePool;
- internal readonly JsValueArrayPool _jsValueArrayPool;
- internal readonly ExtensionMethodCache _extensionMethods;
- public ITypeConverter ClrTypeConverter { get; internal set; }
- // cache of types used when resolving CLR type names
- internal readonly Dictionary<string, Type> TypeCache = new();
- // cache for already wrapped CLR objects to keep object identity
- internal readonly ConditionalWeakTable<object, ObjectWrapper> _objectWrapperCache = new();
- internal readonly JintCallStack CallStack;
- // needed in initial engine setup, for example CLR function construction
- internal Intrinsics _originalIntrinsics;
- internal Host _host;
- /// <summary>
- /// Constructs a new engine instance.
- /// </summary>
- public Engine() : this((Action<Options>) null)
- {
- }
- /// <summary>
- /// Constructs a new engine instance and allows customizing options.
- /// </summary>
- public Engine(Action<Options> options)
- : this((engine, opts) => options?.Invoke(opts))
- {
- }
- /// <summary>
- /// Constructs a new engine with a custom <see cref="Options"/> instance.
- /// </summary>
- public Engine(Options options) : this((e, o) => e.Options = options)
- {
- }
- /// <summary>
- /// Constructs a new engine instance and allows customizing options.
- /// </summary>
- /// <remarks>The provided engine instance in callback is not guaranteed to be fully configured</remarks>
- public Engine(Action<Engine, Options> options)
- {
- _executionContexts = new ExecutionContextStack(2);
- Options = new Options();
- options?.Invoke(this, Options);
- _extensionMethods = ExtensionMethodCache.Build(Options.Interop.ExtensionMethodTypes);
- Reset();
- // gather some options as fields for faster checks
- _isDebugMode = Options.Debugger.Enabled;
- _isStrict = Options.Strict;
- _objectConverters = Options.Interop.ObjectConverters.Count > 0
- ? Options.Interop.ObjectConverters.ToArray()
- : null;
- _constraints = Options.Constraints.Constraints.ToArray();
- _referenceResolver = Options.ReferenceResolver;
- CallStack = new JintCallStack(Options.Constraints.MaxRecursionDepth >= 0);
- _referencePool = new ReferencePool();
- _argumentsInstancePool = new ArgumentsInstancePool(this);
- _jsValueArrayPool = new JsValueArrayPool();
- Options.Apply(this);
- }
- private void Reset()
- {
- _host = Options.Host.Factory(this);
- _host.Initialize(this);
- }
- internal ref readonly ExecutionContext ExecutionContext
- {
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- get => ref _executionContexts.Peek();
- }
- // temporary state for realm so that we can easily pass it to functions while still not
- // having a proper execution context established
- internal Realm _realmInConstruction;
- public Realm Realm => _realmInConstruction ?? ExecutionContext.Realm;
- internal GlobalSymbolRegistry GlobalSymbolRegistry { get; } = new();
- internal long CurrentMemoryUsage { get; private set; }
- internal Options Options
- {
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- get;
- private set;
- }
- public DebugHandler DebugHandler => _debugHandler ??= new DebugHandler(this, Options.Debugger.InitialStepMode);
- internal ExecutionContext EnterExecutionContext(
- EnvironmentRecord lexicalEnvironment,
- EnvironmentRecord variableEnvironment,
- Realm realm,
- PrivateEnvironmentRecord privateEnvironment)
- {
- var context = new ExecutionContext(
- null,
- lexicalEnvironment,
- variableEnvironment,
- privateEnvironment,
- realm,
- null);
- _executionContexts.Push(context);
- return context;
- }
- internal ExecutionContext EnterExecutionContext(ExecutionContext context)
- {
- _executionContexts.Push(context);
- return context;
- }
- public Engine SetValue(JsValue name, Delegate value)
- {
- Realm.GlobalObject.FastAddProperty(name, new DelegateWrapper(this, value), true, false, true);
- return this;
- }
- public Engine SetValue(JsValue name, string value)
- {
- return SetValue(name, new JsString(value));
- }
- public Engine SetValue(JsValue name, double value)
- {
- return SetValue(name, JsNumber.Create(value));
- }
- public Engine SetValue(JsValue name, int value)
- {
- return SetValue(name, JsNumber.Create(value));
- }
- public Engine SetValue(JsValue name, bool value)
- {
- return SetValue(name, value ? JsBoolean.True : JsBoolean.False);
- }
- public Engine SetValue(JsValue name, JsValue value)
- {
- Realm.GlobalObject.Set(name, value);
- return this;
- }
- public Engine SetValue(JsValue name, object obj)
- {
- var value = obj is Type t
- ? TypeReference.CreateTypeReference(this, t)
- : JsValue.FromObject(this, obj);
- return SetValue(name, value);
- }
- internal void LeaveExecutionContext()
- {
- _executionContexts.Pop();
- }
- /// <summary>
- /// Initializes the statements count
- /// </summary>
- public void ResetConstraints()
- {
- foreach (var constraint in _constraints)
- {
- constraint.Reset();
- }
- }
- /// <summary>
- /// Initializes list of references of called functions
- /// </summary>
- public void ResetCallStack()
- {
- CallStack.Clear();
- }
- public JsValue Evaluate(string source)
- => Evaluate(source, DefaultParserOptions);
- public JsValue Evaluate(string source, ParserOptions parserOptions)
- => Evaluate(new JavaScriptParser(source, parserOptions).ParseScript());
- public JsValue Evaluate(Script script)
- => Execute(script)._completionValue;
- public Engine Execute(string source)
- => Execute(source, DefaultParserOptions);
- public Engine Execute(string source, ParserOptions parserOptions)
- {
- var parser = new JavaScriptParser(source, parserOptions);
- var script = parser.ParseScript();
- return Execute(script);
- }
- public Engine Execute(Script script)
- {
- var strict = _isStrict || script.Strict;
- ExecuteWithConstraints(strict, () => ScriptEvaluation(new ScriptRecord(Realm, script, string.Empty)));
- return this;
- }
- /// <summary>
- /// https://tc39.es/ecma262/#sec-runtime-semantics-scriptevaluation
- /// </summary>
- private Engine ScriptEvaluation(ScriptRecord scriptRecord)
- {
- var globalEnv = Realm.GlobalEnv;
- var scriptContext = new ExecutionContext(
- scriptRecord,
- lexicalEnvironment: globalEnv,
- variableEnvironment: globalEnv,
- privateEnvironment: null,
- Realm);
- EnterExecutionContext(scriptContext);
- try
- {
- var script = scriptRecord.EcmaScriptCode;
- GlobalDeclarationInstantiation(script, globalEnv);
- var list = new JintStatementList(null, script.Body);
- Completion result;
- try
- {
- result = list.Execute(_activeEvaluationContext);
- }
- catch
- {
- // unhandled exception
- ResetCallStack();
- throw;
- }
- if (result.Type == CompletionType.Throw)
- {
- var ex = new JavaScriptException(result.GetValueOrDefault()).SetJavaScriptCallstack(this, result.Location);
- ResetCallStack();
- throw ex;
- }
- // TODO what about callstack and thrown exceptions?
- RunAvailableContinuations();
- _completionValue = result.GetValueOrDefault();
- return this;
- }
- finally
- {
- LeaveExecutionContext();
- }
- }
- /// <summary>
- /// EXPERIMENTAL! Subject to change.
- ///
- /// Registers a promise within the currently running EventLoop (has to be called within "ExecuteWithEventLoop" call).
- /// Note that ExecuteWithEventLoop will not trigger "onFinished" callback until ALL manual promises are settled.
- ///
- /// NOTE: that resolve and reject need to be called withing the same thread as "ExecuteWithEventLoop".
- /// The API assumes that the Engine is called from a single thread.
- /// </summary>
- /// <returns>a Promise instance and functions to either resolve or reject it</returns>
- public ManualPromise RegisterPromise()
- {
- var promise = new PromiseInstance(this)
- {
- _prototype = Realm.Intrinsics.Promise.PrototypeObject
- };
- var (resolve, reject) = promise.CreateResolvingFunctions();
- Action<JsValue> SettleWith(FunctionInstance settle) => value =>
- {
- settle.Call(JsValue.Undefined, new[] {value});
- RunAvailableContinuations();
- };
- return new ManualPromise(promise, SettleWith(resolve), SettleWith(reject));
- }
- internal void AddToEventLoop(Action continuation)
- {
- _eventLoop.Events.Enqueue(continuation);
- }
- internal void RunAvailableContinuations()
- {
- var queue = _eventLoop.Events;
- while (true)
- {
- if (queue.Count == 0)
- {
- return;
- }
- var nextContinuation = queue.Dequeue();
- // note that continuation can enqueue new events
- nextContinuation();
- }
- }
- internal void RunBeforeExecuteStatementChecks(Statement statement)
- {
- // Avoid allocating the enumerator because we run this loop very often.
- foreach (var constraint in _constraints)
- {
- constraint.Check();
- }
- if (_isDebugMode && statement != null && statement.Type != Nodes.BlockStatement)
- {
- DebugHandler.OnStep(statement);
- }
- }
- /// <summary>
- /// http://www.ecma-international.org/ecma-262/5.1/#sec-8.7.1
- /// </summary>
- public JsValue GetValue(object value)
- {
- return GetValue(value, false);
- }
- internal JsValue GetValue(object value, bool returnReferenceToPool)
- {
- if (value is JsValue jsValue)
- {
- return jsValue;
- }
- if (value is not Reference reference)
- {
- return ((Completion) value).Value;
- }
- return GetValue(reference, returnReferenceToPool);
- }
- internal JsValue GetValue(Reference reference, bool returnReferenceToPool)
- {
- var baseValue = reference.GetBase();
- if (baseValue.IsUndefined())
- {
- if (_referenceResolver.TryUnresolvableReference(this, reference, out var val))
- {
- return val;
- }
- ExceptionHelper.ThrowReferenceError(Realm, reference);
- }
- if ((baseValue._type & InternalTypes.ObjectEnvironmentRecord) == 0
- && _referenceResolver.TryPropertyReference(this, reference, ref baseValue))
- {
- return baseValue;
- }
- if (reference.IsPropertyReference())
- {
- var property = reference.GetReferencedName();
- if (returnReferenceToPool)
- {
- _referencePool.Return(reference);
- }
- if (baseValue.IsObject())
- {
- var o = TypeConverter.ToObject(Realm, baseValue);
- var v = o.Get(property, reference.GetThisValue());
- return v;
- }
- else
- {
- // check if we are accessing a string, boxing operation can be costly to do index access
- // we have good chance to have fast path with integer or string indexer
- ObjectInstance o = null;
- if ((property._type & (InternalTypes.String | InternalTypes.Integer)) != 0
- && baseValue is JsString s
- && TryHandleStringValue(property, s, ref o, out var jsValue))
- {
- return jsValue;
- }
- if (o is null)
- {
- o = TypeConverter.ToObject(Realm, baseValue);
- }
- var desc = o.GetProperty(property);
- if (desc == PropertyDescriptor.Undefined)
- {
- return JsValue.Undefined;
- }
- if (desc.IsDataDescriptor())
- {
- return desc.Value;
- }
- var getter = desc.Get;
- if (getter.IsUndefined())
- {
- return Undefined.Instance;
- }
- var callable = (ICallable) getter.AsObject();
- return callable.Call(baseValue, Arguments.Empty);
- }
- }
- var record = baseValue as EnvironmentRecord;
- if (record is null)
- {
- ExceptionHelper.ThrowArgumentException();
- }
- var bindingValue = record.GetBindingValue(reference.GetReferencedName().ToString(), reference.IsStrictReference());
- if (returnReferenceToPool)
- {
- _referencePool.Return(reference);
- }
- return bindingValue;
- }
- private bool TryHandleStringValue(JsValue property, JsString s, ref ObjectInstance o, out JsValue jsValue)
- {
- if (property == CommonProperties.Length)
- {
- jsValue = JsNumber.Create((uint) s.Length);
- return true;
- }
- if (property is JsNumber number && number.IsInteger())
- {
- var index = number.AsInteger();
- var str = s._value;
- if (index < 0 || index >= str.Length)
- {
- jsValue = JsValue.Undefined;
- return true;
- }
- jsValue = JsString.Create(str[index]);
- return true;
- }
- if (property is JsString propertyString
- && propertyString._value.Length > 0
- && char.IsLower(propertyString._value[0]))
- {
- // trying to find property that's always in prototype
- o = Realm.Intrinsics.String.PrototypeObject;
- }
- jsValue = JsValue.Undefined;
- return false;
- }
- /// <summary>
- /// https://tc39.es/ecma262/#sec-putvalue
- /// </summary>
- internal void PutValue(Reference reference, JsValue value)
- {
- var baseValue = reference.GetBase();
- if (reference.IsUnresolvableReference())
- {
- if (reference.IsStrictReference())
- {
- ExceptionHelper.ThrowReferenceError(Realm, reference);
- }
- Realm.GlobalObject.Set(reference.GetReferencedName(), value, throwOnError: false);
- }
- else if (reference.IsPropertyReference())
- {
- if (reference.HasPrimitiveBase())
- {
- baseValue = TypeConverter.ToObject(Realm, baseValue);
- }
- var succeeded = baseValue.Set(reference.GetReferencedName(), value, reference.GetThisValue());
- if (!succeeded && reference.IsStrictReference())
- {
- ExceptionHelper.ThrowTypeError(Realm);
- }
- }
- else
- {
- ((EnvironmentRecord) baseValue).SetMutableBinding(TypeConverter.ToString(reference.GetReferencedName()),
- value, reference.IsStrictReference());
- }
- }
- /// <summary>
- /// Invoke the current value as function.
- /// </summary>
- /// <param name="propertyName">The name of the function to call.</param>
- /// <param name="arguments">The arguments of the function call.</param>
- /// <returns>The value returned by the function call.</returns>
- public JsValue Invoke(string propertyName, params object[] arguments)
- {
- return Invoke(propertyName, null, arguments);
- }
- /// <summary>
- /// Invoke the current value as function.
- /// </summary>
- /// <param name="propertyName">The name of the function to call.</param>
- /// <param name="thisObj">The this value inside the function call.</param>
- /// <param name="arguments">The arguments of the function call.</param>
- /// <returns>The value returned by the function call.</returns>
- public JsValue Invoke(string propertyName, object thisObj, object[] arguments)
- {
- var value = GetValue(propertyName);
- return Invoke(value, thisObj, arguments);
- }
- /// <summary>
- /// Invoke the current value as function.
- /// </summary>
- /// <param name="value">The function to call.</param>
- /// <param name="arguments">The arguments of the function call.</param>
- /// <returns>The value returned by the function call.</returns>
- public JsValue Invoke(JsValue value, params object[] arguments)
- {
- return Invoke(value, null, arguments);
- }
- /// <summary>
- /// Invoke the current value as function.
- /// </summary>
- /// <param name="value">The function to call.</param>
- /// <param name="thisObj">The this value inside the function call.</param>
- /// <param name="arguments">The arguments of the function call.</param>
- /// <returns>The value returned by the function call.</returns>
- public JsValue Invoke(JsValue value, object thisObj, object[] arguments)
- {
- var callable = value as ICallable;
- if (callable is null)
- {
- ExceptionHelper.ThrowJavaScriptException(Realm.Intrinsics.TypeError, "Can only invoke functions");
- }
- JsValue DoInvoke()
- {
- var items = _jsValueArrayPool.RentArray(arguments.Length);
- for (var i = 0; i < arguments.Length; ++i)
- {
- items[i] = JsValue.FromObject(this, arguments[i]);
- }
- var result = callable.Call(JsValue.FromObject(this, thisObj), items);
- _jsValueArrayPool.ReturnArray(items);
- return result;
- }
- return ExecuteWithConstraints(Options.Strict, DoInvoke);
- }
- private T ExecuteWithConstraints<T>(bool strict, Func<T> callback)
- {
- ResetConstraints();
- var ownsContext = _activeEvaluationContext is null;
- _activeEvaluationContext ??= new EvaluationContext(this);
- var oldStrict = _isStrict;
- try
- {
- _isStrict = strict;
- using (new StrictModeScope(_isStrict))
- {
- return callback();
- }
- }
- finally
- {
- if (ownsContext)
- {
- _activeEvaluationContext = null;
- }
- _isStrict = oldStrict;
- ResetConstraints();
- }
- }
- /// <summary>
- /// https://tc39.es/ecma262/#sec-invoke
- /// </summary>
- internal JsValue Invoke(JsValue v, JsValue p, JsValue[] arguments)
- {
- var ownsContext = _activeEvaluationContext is null;
- _activeEvaluationContext ??= new EvaluationContext(this);
- try
- {
- var func = GetV(v, p);
- var callable = func as ICallable;
- if (callable is null)
- {
- ExceptionHelper.ThrowTypeErrorNoEngine("Can only invoke functions");
- }
- return callable.Call(v, arguments);
- }
- finally
- {
- if (ownsContext)
- {
- _activeEvaluationContext = null;
- }
- }
- }
- /// <summary>
- /// https://tc39.es/ecma262/#sec-getv
- /// </summary>
- private JsValue GetV(JsValue v, JsValue p)
- {
- var o = TypeConverter.ToObject(Realm, v);
- return o.Get(p);
- }
- /// <summary>
- /// Gets a named value from the Global scope.
- /// </summary>
- /// <param name="propertyName">The name of the property to return.</param>
- public JsValue GetValue(string propertyName)
- {
- return GetValue(Realm.GlobalObject, new JsString(propertyName));
- }
- /// <summary>
- /// Gets the last evaluated <see cref="Node"/>.
- /// </summary>
- internal Node GetLastSyntaxNode()
- {
- return _activeEvaluationContext?.LastSyntaxNode;
- }
- /// <summary>
- /// Gets a named value from the specified scope.
- /// </summary>
- /// <param name="scope">The scope to get the property from.</param>
- /// <param name="property">The name of the property to return.</param>
- public JsValue GetValue(JsValue scope, JsValue property)
- {
- var reference = _referencePool.Rent(scope, property, _isStrict, thisValue: null);
- var jsValue = GetValue(reference, false);
- _referencePool.Return(reference);
- return jsValue;
- }
- /// <summary>
- /// https://tc39.es/ecma262/#sec-resolvebinding
- /// </summary>
- internal Reference ResolveBinding(string name, EnvironmentRecord env = null)
- {
- env ??= ExecutionContext.LexicalEnvironment;
- return GetIdentifierReference(env, name, StrictModeScope.IsStrictModeCode);
- }
- private static Reference GetIdentifierReference(EnvironmentRecord env, string name, bool strict)
- {
- if (env is null)
- {
- return new Reference(JsValue.Undefined, name, strict);
- }
- var envRec = env;
- if (envRec.HasBinding(name))
- {
- return new Reference(envRec, name, strict);
- }
- return GetIdentifierReference(env._outerEnv, name, strict);
- }
- /// <summary>
- /// https://tc39.es/ecma262/#sec-getnewtarget
- /// </summary>
- internal JsValue GetNewTarget(EnvironmentRecord thisEnvironment = null)
- {
- // we can take as argument if caller site has already determined the value, otherwise resolve
- thisEnvironment ??= ExecutionContext.GetThisEnvironment();
- return thisEnvironment.NewTarget;
- }
- /// <summary>
- /// https://tc39.es/ecma262/#sec-resolvethisbinding
- /// </summary>
- internal JsValue ResolveThisBinding()
- {
- var envRec = ExecutionContext.GetThisEnvironment();
- return envRec.GetThisBinding();
- }
- /// <summary>
- /// https://tc39.es/ecma262/#sec-globaldeclarationinstantiation
- /// </summary>
- private void GlobalDeclarationInstantiation(
- Script script,
- GlobalEnvironmentRecord env)
- {
- var hoistingScope = HoistingScope.GetProgramLevelDeclarations(script);
- var functionDeclarations = hoistingScope._functionDeclarations;
- var varDeclarations = hoistingScope._variablesDeclarations;
- var lexDeclarations = hoistingScope._lexicalDeclarations;
- var functionToInitialize = new LinkedList<JintFunctionDefinition>();
- var declaredFunctionNames = new HashSet<string>();
- var declaredVarNames = new List<string>();
- var realm = Realm;
- if (functionDeclarations != null)
- {
- for (var i = functionDeclarations.Count - 1; i >= 0; i--)
- {
- var d = functionDeclarations[i];
- var fn = d.Id.Name;
- if (!declaredFunctionNames.Contains(fn))
- {
- var fnDefinable = env.CanDeclareGlobalFunction(fn);
- if (!fnDefinable)
- {
- ExceptionHelper.ThrowTypeError(realm, "Cannot declare global function " + fn);
- }
- declaredFunctionNames.Add(fn);
- functionToInitialize.AddFirst(new JintFunctionDefinition(this, d));
- }
- }
- }
- var boundNames = new List<string>();
- if (varDeclarations != null)
- {
- for (var i = 0; i < varDeclarations.Count; i++)
- {
- var d = varDeclarations[i];
- boundNames.Clear();
- d.GetBoundNames(boundNames);
- for (var j = 0; j < boundNames.Count; j++)
- {
- var vn = boundNames[j];
- if (env.HasLexicalDeclaration(vn))
- {
- ExceptionHelper.ThrowSyntaxError(realm, $"Identifier '{vn}' has already been declared");
- }
- if (!declaredFunctionNames.Contains(vn))
- {
- var vnDefinable = env.CanDeclareGlobalVar(vn);
- if (!vnDefinable)
- {
- ExceptionHelper.ThrowTypeError(realm);
- }
- declaredVarNames.Add(vn);
- }
- }
- }
- }
- PrivateEnvironmentRecord privateEnv = null;
- if (lexDeclarations != null)
- {
- for (var i = 0; i < lexDeclarations.Count; i++)
- {
- var d = lexDeclarations[i];
- boundNames.Clear();
- d.GetBoundNames(boundNames);
- for (var j = 0; j < boundNames.Count; j++)
- {
- var dn = boundNames[j];
- if (env.HasVarDeclaration(dn)
- || env.HasLexicalDeclaration(dn)
- || env.HasRestrictedGlobalProperty(dn))
- {
- ExceptionHelper.ThrowSyntaxError(realm, $"Identifier '{dn}' has already been declared");
- }
- if (d.IsConstantDeclaration())
- {
- env.CreateImmutableBinding(dn, strict: true);
- }
- else
- {
- env.CreateMutableBinding(dn, canBeDeleted: false);
- }
- }
- }
- }
- foreach (var f in functionToInitialize)
- {
- var fn = f.Name;
- if (env.HasLexicalDeclaration(fn))
- {
- ExceptionHelper.ThrowSyntaxError(realm, $"Identifier '{fn}' has already been declared");
- }
- var fo = realm.Intrinsics.Function.InstantiateFunctionObject(f, env, privateEnv);
- env.CreateGlobalFunctionBinding(fn, fo, canBeDeleted: false);
- }
- for (var i = 0; i < declaredVarNames.Count; i++)
- {
- var vn = declaredVarNames[i];
- env.CreateGlobalVarBinding(vn, canBeDeleted: false);
- }
- }
- /// <summary>
- /// https://tc39.es/ecma262/#sec-functiondeclarationinstantiation
- /// </summary>
- internal ArgumentsInstance FunctionDeclarationInstantiation(
- FunctionInstance functionInstance,
- JsValue[] argumentsList)
- {
- var calleeContext = ExecutionContext;
- var func = functionInstance._functionDefinition;
- var env = (FunctionEnvironmentRecord) ExecutionContext.LexicalEnvironment;
- var strict = StrictModeScope.IsStrictModeCode;
- var configuration = func.Initialize(functionInstance);
- var parameterNames = configuration.ParameterNames;
- var hasDuplicates = configuration.HasDuplicates;
- var simpleParameterList = configuration.IsSimpleParameterList;
- var hasParameterExpressions = configuration.HasParameterExpressions;
- var canInitializeParametersOnDeclaration = simpleParameterList && !configuration.HasDuplicates;
- var arguments = canInitializeParametersOnDeclaration ? argumentsList : null;
- env.InitializeParameters(parameterNames, hasDuplicates, arguments);
- ArgumentsInstance ao = null;
- if (configuration.ArgumentsObjectNeeded)
- {
- if (strict || !simpleParameterList)
- {
- ao = CreateUnmappedArgumentsObject(argumentsList);
- }
- else
- {
- // NOTE: mapped argument object is only provided for non-strict functions that don't have a rest parameter,
- // any parameter default value initializers, or any destructured parameters.
- ao = CreateMappedArgumentsObject(functionInstance, parameterNames, argumentsList, env, configuration.HasRestParameter);
- }
- if (strict)
- {
- env.CreateImmutableBindingAndInitialize(KnownKeys.Arguments, strict: false, ao);
- }
- else
- {
- env.CreateMutableBindingAndInitialize(KnownKeys.Arguments, canBeDeleted: false, ao);
- }
- }
- if (!canInitializeParametersOnDeclaration)
- {
- // slower set
- env.AddFunctionParameters(_activeEvaluationContext, func.Function, argumentsList);
- }
- // Let iteratorRecord be CreateListIteratorRecord(argumentsList).
- // If hasDuplicates is true, then
- // Perform ? IteratorBindingInitialization for formals with iteratorRecord and undefined as arguments.
- // Else,
- // Perform ? IteratorBindingInitialization for formals with iteratorRecord and env as arguments.
- EnvironmentRecord varEnv;
- if (!hasParameterExpressions)
- {
- // NOTE: Only a single lexical environment is needed for the parameters and top-level vars.
- for (var i = 0; i < configuration.VarsToInitialize.Count; i++)
- {
- var pair = configuration.VarsToInitialize[i];
- env.CreateMutableBindingAndInitialize(pair.Name, canBeDeleted: false, JsValue.Undefined);
- }
- varEnv = env;
- }
- else
- {
- // NOTE: A separate Environment Record is needed to ensure that closures created by expressions
- // in the formal parameter list do not have visibility of declarations in the function body.
- var varEnvRec = JintEnvironment.NewDeclarativeEnvironment(this, env);
- varEnv = varEnvRec;
- UpdateVariableEnvironment(varEnv);
- for (var i = 0; i < configuration.VarsToInitialize.Count; i++)
- {
- var pair = configuration.VarsToInitialize[i];
- var initialValue = pair.InitialValue ?? env.GetBindingValue(pair.Name, strict: false);
- varEnvRec.CreateMutableBindingAndInitialize(pair.Name, canBeDeleted: false, initialValue);
- }
- }
- // NOTE: Annex B.3.3.1 adds additional steps at this point.
- // A https://tc39.es/ecma262/#sec-web-compat-functiondeclarationinstantiation
- EnvironmentRecord lexEnv;
- if (!strict)
- {
- lexEnv = JintEnvironment.NewDeclarativeEnvironment(this, varEnv);
- // NOTE: Non-strict functions use a separate lexical Environment Record for top-level lexical declarations
- // so that a direct eval can determine whether any var scoped declarations introduced by the eval code conflict
- // with pre-existing top-level lexically scoped declarations. This is not needed for strict functions
- // because a strict direct eval always places all declarations into a new Environment Record.
- }
- else
- {
- lexEnv = varEnv;
- }
- UpdateLexicalEnvironment(lexEnv);
- if (configuration.LexicalDeclarations.Length > 0)
- {
- foreach (var d in configuration.LexicalDeclarations)
- {
- for (var j = 0; j < d.BoundNames.Count; j++)
- {
- var dn = d.BoundNames[j];
- if (d.IsConstantDeclaration)
- {
- lexEnv.CreateImmutableBinding(dn, strict: true);
- }
- else
- {
- lexEnv.CreateMutableBinding(dn, canBeDeleted: false);
- }
- }
- }
- }
- if (configuration.FunctionsToInitialize != null)
- {
- var privateEnv = calleeContext.PrivateEnvironment;
- var realm = Realm;
- foreach (var f in configuration.FunctionsToInitialize)
- {
- var fn = f.Name;
- var fo = realm.Intrinsics.Function.InstantiateFunctionObject(f, lexEnv, privateEnv);
- varEnv.SetMutableBinding(fn, fo, strict: false);
- }
- }
- return ao;
- }
- private ArgumentsInstance CreateMappedArgumentsObject(
- FunctionInstance func,
- Key[] formals,
- JsValue[] argumentsList,
- DeclarativeEnvironmentRecord envRec,
- bool hasRestParameter)
- {
- return _argumentsInstancePool.Rent(func, formals, argumentsList, envRec, hasRestParameter);
- }
- private ArgumentsInstance CreateUnmappedArgumentsObject(JsValue[] argumentsList)
- {
- return _argumentsInstancePool.Rent(argumentsList);
- }
- /// <summary>
- /// https://tc39.es/ecma262/#sec-evaldeclarationinstantiation
- /// </summary>
- internal void EvalDeclarationInstantiation(
- Script script,
- EnvironmentRecord varEnv,
- EnvironmentRecord lexEnv,
- PrivateEnvironmentRecord privateEnv,
- bool strict)
- {
- var hoistingScope = HoistingScope.GetProgramLevelDeclarations(script);
- var lexEnvRec = (DeclarativeEnvironmentRecord) lexEnv;
- var varEnvRec = varEnv;
- var realm = Realm;
- if (!strict && hoistingScope._variablesDeclarations != null)
- {
- if (varEnvRec is GlobalEnvironmentRecord globalEnvironmentRecord)
- {
- ref readonly var nodes = ref hoistingScope._variablesDeclarations;
- for (var i = 0; i < nodes.Count; i++)
- {
- var variablesDeclaration = nodes[i];
- var identifier = (Identifier) variablesDeclaration.Declarations[0].Id;
- if (globalEnvironmentRecord.HasLexicalDeclaration(identifier.Name))
- {
- ExceptionHelper.ThrowSyntaxError(realm, "Identifier '" + identifier.Name + "' has already been declared");
- }
- }
- }
- var thisLex = lexEnv;
- while (!ReferenceEquals(thisLex, varEnv))
- {
- var thisEnvRec = thisLex;
- if (!(thisEnvRec is ObjectEnvironmentRecord))
- {
- ref readonly var nodes = ref hoistingScope._variablesDeclarations;
- for (var i = 0; i < nodes.Count; i++)
- {
- var variablesDeclaration = nodes[i];
- var identifier = (Identifier) variablesDeclaration.Declarations[0].Id;
- if (thisEnvRec.HasBinding(identifier.Name))
- {
- ExceptionHelper.ThrowSyntaxError(realm);
- }
- }
- }
- thisLex = thisLex._outerEnv;
- }
- }
- var functionDeclarations = hoistingScope._functionDeclarations;
- var functionsToInitialize = new LinkedList<JintFunctionDefinition>();
- var declaredFunctionNames = new HashSet<string>();
- if (functionDeclarations != null)
- {
- for (var i = functionDeclarations.Count - 1; i >= 0; i--)
- {
- var d = functionDeclarations[i];
- var fn = d.Id.Name;
- if (!declaredFunctionNames.Contains(fn))
- {
- if (varEnvRec is GlobalEnvironmentRecord ger)
- {
- var fnDefinable = ger.CanDeclareGlobalFunction(fn);
- if (!fnDefinable)
- {
- ExceptionHelper.ThrowTypeError(realm);
- }
- }
- declaredFunctionNames.Add(fn);
- functionsToInitialize.AddFirst(new JintFunctionDefinition(this, d));
- }
- }
- }
- var boundNames = new List<string>();
- var declaredVarNames = new List<string>();
- var variableDeclarations = hoistingScope._variablesDeclarations;
- var variableDeclarationsCount = variableDeclarations?.Count;
- for (var i = 0; i < variableDeclarationsCount; i++)
- {
- var variableDeclaration = variableDeclarations[i];
- boundNames.Clear();
- variableDeclaration.GetBoundNames(boundNames);
- for (var j = 0; j < boundNames.Count; j++)
- {
- var vn = boundNames[j];
- if (!declaredFunctionNames.Contains(vn))
- {
- if (varEnvRec is GlobalEnvironmentRecord ger)
- {
- var vnDefinable = ger.CanDeclareGlobalFunction(vn);
- if (!vnDefinable)
- {
- ExceptionHelper.ThrowTypeError(realm);
- }
- }
- declaredVarNames.Add(vn);
- }
- }
- }
- var lexicalDeclarations = hoistingScope._lexicalDeclarations;
- var lexicalDeclarationsCount = lexicalDeclarations?.Count;
- for (var i = 0; i < lexicalDeclarationsCount; i++)
- {
- boundNames.Clear();
- var d = lexicalDeclarations[i];
- d.GetBoundNames(boundNames);
- for (var j = 0; j < boundNames.Count; j++)
- {
- var dn = boundNames[j];
- if (d.IsConstantDeclaration())
- {
- lexEnvRec.CreateImmutableBinding(dn, strict: true);
- }
- else
- {
- lexEnvRec.CreateMutableBinding(dn, canBeDeleted: false);
- }
- }
- }
- foreach (var f in functionsToInitialize)
- {
- var fn = f.Name;
- var fo = realm.Intrinsics.Function.InstantiateFunctionObject(f, lexEnv, privateEnv);
- if (varEnvRec is GlobalEnvironmentRecord ger)
- {
- ger.CreateGlobalFunctionBinding(fn, fo, canBeDeleted: true);
- }
- else
- {
- var bindingExists = varEnvRec.HasBinding(fn);
- if (!bindingExists)
- {
- varEnvRec.CreateMutableBinding(fn, canBeDeleted: true);
- varEnvRec.InitializeBinding(fn, fo);
- }
- else
- {
- varEnvRec.SetMutableBinding(fn, fo, strict: false);
- }
- }
- }
- foreach (var vn in declaredVarNames)
- {
- if (varEnvRec is GlobalEnvironmentRecord ger)
- {
- ger.CreateGlobalVarBinding(vn, true);
- }
- else
- {
- var bindingExists = varEnvRec.HasBinding(vn);
- if (!bindingExists)
- {
- varEnvRec.CreateMutableBinding(vn, canBeDeleted: true);
- varEnvRec.InitializeBinding(vn, JsValue.Undefined);
- }
- }
- }
- }
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal void UpdateLexicalEnvironment(EnvironmentRecord newEnv)
- {
- _executionContexts.ReplaceTopLexicalEnvironment(newEnv);
- }
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal void UpdateVariableEnvironment(EnvironmentRecord newEnv)
- {
- _executionContexts.ReplaceTopVariableEnvironment(newEnv);
- }
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal void UpdatePrivateEnvironment(PrivateEnvironmentRecord newEnv)
- {
- _executionContexts.ReplaceTopPrivateEnvironment(newEnv);
- }
- /// <summary>
- /// Invokes the named callable and returns the resulting object.
- /// </summary>
- /// <param name="callableName">The name of the callable.</param>
- /// <param name="arguments">The arguments of the call.</param>
- /// <returns>The value returned by the call.</returns>
- public JsValue Call(string callableName, params JsValue[] arguments)
- {
- var callable = Evaluate(callableName);
- return Call(callable, arguments);
- }
- /// <summary>
- /// Invokes the callable and returns the resulting object.
- /// </summary>
- /// <param name="callable">The callable.</param>
- /// <param name="arguments">The arguments of the call.</param>
- /// <returns>The value returned by the call.</returns>
- public JsValue Call(JsValue callable, params JsValue[] arguments)
- => Call(callable, thisObject: JsValue.Undefined, arguments);
- /// <summary>
- /// Invokes the callable and returns the resulting object.
- /// </summary>
- /// <param name="callable">The callable.</param>
- /// <param name="thisObject">Value bound as this.</param>
- /// <param name="arguments">The arguments of the call.</param>
- /// <returns>The value returned by the call.</returns>
- public JsValue Call(JsValue callable, JsValue thisObject, JsValue[] arguments)
- {
- JsValue Callback()
- {
- if (!callable.IsCallable)
- {
- ExceptionHelper.ThrowArgumentException(callable + " is not callable");
- }
- return Call((ICallable) callable, thisObject, arguments, null);
- }
- return ExecuteWithConstraints(Options.Strict, Callback);
- }
- internal JsValue Call(ICallable callable, JsValue thisObject, JsValue[] arguments, JintExpression expression)
- {
- if (callable is FunctionInstance functionInstance)
- {
- return Call(functionInstance, thisObject, arguments, expression);
- }
- return callable.Call(thisObject, arguments);
- }
- /// <summary>
- /// Calls the named constructor and returns the resulting object.
- /// </summary>
- /// <param name="constructorName">The name of the constructor to call.</param>
- /// <param name="arguments">The arguments of the constructor call.</param>
- /// <returns>The value returned by the constructor call.</returns>
- public ObjectInstance Construct(string constructorName, params JsValue[] arguments)
- {
- var constructor = Evaluate(constructorName);
- return Construct(constructor, arguments);
- }
- /// <summary>
- /// Calls the constructor and returns the resulting object.
- /// </summary>
- /// <param name="constructor">The name of the constructor to call.</param>
- /// <param name="arguments">The arguments of the constructor call.</param>
- /// <returns>The value returned by the constructor call.</returns>
- public ObjectInstance Construct(JsValue constructor, params JsValue[] arguments)
- {
- ObjectInstance Callback()
- {
- if (!constructor.IsConstructor)
- {
- ExceptionHelper.ThrowArgumentException(constructor + " is not a constructor");
- }
- return Construct(constructor, arguments, constructor, null);
- }
- return ExecuteWithConstraints(Options.Strict, Callback);
- }
- internal ObjectInstance Construct(
- JsValue constructor,
- JsValue[] arguments,
- JsValue newTarget,
- JintExpression expression)
- {
- if (constructor is FunctionInstance functionInstance)
- {
- return Construct(functionInstance, arguments, newTarget, expression);
- }
- return ((IConstructor) constructor).Construct(arguments, newTarget);
- }
- internal JsValue Call(
- FunctionInstance functionInstance,
- JsValue thisObject,
- JsValue[] arguments,
- JintExpression expression)
- {
- var callStackElement = new CallStackElement(functionInstance, expression, ExecutionContext);
- var recursionDepth = CallStack.Push(callStackElement);
- if (recursionDepth > Options.Constraints.MaxRecursionDepth)
- {
- // pop the current element as it was never reached
- CallStack.Pop();
- ExceptionHelper.ThrowRecursionDepthOverflowException(CallStack, callStackElement.ToString());
- }
- JsValue result;
- try
- {
- result = functionInstance.Call(thisObject, arguments);
- }
- finally
- {
- CallStack.Pop();
- }
- return result;
- }
- private ObjectInstance Construct(
- FunctionInstance functionInstance,
- JsValue[] arguments,
- JsValue newTarget,
- JintExpression expression)
- {
- var callStackElement = new CallStackElement(functionInstance, expression, ExecutionContext);
- var recursionDepth = CallStack.Push(callStackElement);
- if (recursionDepth > Options.Constraints.MaxRecursionDepth)
- {
- // pop the current element as it was never reached
- CallStack.Pop();
- ExceptionHelper.ThrowRecursionDepthOverflowException(CallStack, callStackElement.ToString());
- }
- ObjectInstance result;
- try
- {
- result = ((IConstructor) functionInstance).Construct(arguments, newTarget);
- }
- finally
- {
- CallStack.Pop();
- }
- return result;
- }
- public void Dispose()
- {
- // no-op for now
- }
- }
- }
|