/// <summary> /// Pushes the value of the reference onto the stack. /// </summary> /// <param name="generator"> The generator to output the CIL to. </param> /// <param name="optimizationInfo"> Information about any optimizations that should be performed. </param> /// <param name="throwIfUnresolvable"> <c>true</c> to throw a ReferenceError exception if /// the name is unresolvable; <c>false</c> to output <c>null</c> instead. </param> public void GenerateGet(ILGenerator generator, OptimizationInfo optimizationInfo, bool throwIfUnresolvable) { // If we have allocated an IL variable, use it. var variableInfo = Scope.FindStaticVariable(Name); if (variableInfo != null && variableInfo.Store != null) { generator.LoadVariable(variableInfo.Store); if (variableInfo.Keyword != KeywordToken.Var) { var afterIf = generator.CreateLabel(); generator.Duplicate(); generator.BranchIfNotNull(afterIf); EmitHelpers.EmitThrow(generator, ErrorType.ReferenceError, $"Cannot access '{Name}' before initialization."); generator.DefineLabelPosition(afterIf); } return; } // Fallback: call RuntimeScope.GetValue() or RuntimeScope.GetValueNoThrow(). Scope.GenerateReference(generator, optimizationInfo); generator.LoadString(Name); generator.LoadInt32(optimizationInfo.SourceSpan.StartLine); generator.LoadStringOrNull(optimizationInfo.Source.Path); generator.Call(throwIfUnresolvable ? ReflectionHelpers.RuntimeScope_GetValue : ReflectionHelpers.RuntimeScope_GetValueNoThrow); }
/// <summary> /// Generates IL for the script. /// </summary> /// <param name="generator"> The generator to output the CIL to. </param> /// <param name="optimizationInfo"> Information about any optimizations that should be performed. </param> protected override void GenerateCode(ILGenerator generator, OptimizationInfo optimizationInfo) { // Declare a variable to store the eval result. optimizationInfo.EvalResult = generator.DeclareVariable(typeof(object)); if (this.StrictMode == true) { // Create a new scope. this.InitialScope.GenerateScopeCreation(generator, optimizationInfo); } // Initialize any declarations. this.InitialScope.GenerateDeclarations(generator, optimizationInfo); // Generate the main body of code. this.AbstractSyntaxTree.GenerateCode(generator, optimizationInfo); // Make the return value from the method the eval result. generator.LoadVariable(optimizationInfo.EvalResult); // If the result is null, convert it to undefined. var end = generator.CreateLabel(); generator.Duplicate(); generator.BranchIfNotNull(end); generator.Pop(); EmitHelpers.EmitUndefined(generator); generator.DefineLabelPosition(end); }
/// <summary> /// Pushes the value of the reference onto the stack. /// </summary> /// <param name="generator"> The generator to output the CIL to. </param> /// <param name="optimizationInfo"> Information about any optimizations that should be performed. </param> /// <param name="throwIfUnresolvable"> <c>true</c> to throw a ReferenceError exception if /// the name is unresolvable; <c>false</c> to output <c>null</c> instead. </param> public void GenerateGet(ILGenerator generator, OptimizationInfo optimizationInfo, bool throwIfUnresolvable) { string propertyName = null; TypeOfMemberAccess memberAccessType = DetermineTypeOfMemberAccess(optimizationInfo, out propertyName); if (memberAccessType == TypeOfMemberAccess.ArrayIndex) { // Array indexer // ------------- // xxx = object[index] // Call the indexer. generator.Call(ReflectionHelpers.ObjectInstance_Indexer_UInt); } else if (memberAccessType == TypeOfMemberAccess.Static) { // Named property access (e.g. x = y.property) // ------------------------------------------- // Use a PropertyReference to speed up access if we are inside a loop. if (optimizationInfo.InsideLoop) { // C# // if (propertyReference != null) // propertyReference = new PropertyReference("property"); // value = object.GetPropertyValue(propertyReference) ILLocalVariable propertyReference = optimizationInfo.GetPropertyReferenceVariable(generator, propertyName); generator.LoadVariable(propertyReference); generator.Duplicate(); var afterIf = generator.CreateLabel(); generator.BranchIfNotNull(afterIf); generator.Pop(); generator.LoadString(propertyName); generator.NewObject(ReflectionHelpers.PropertyName_Constructor); generator.Duplicate(); generator.StoreVariable(propertyReference); generator.DefineLabelPosition(afterIf); generator.Call(ReflectionHelpers.ObjectInstance_GetPropertyValue_PropertyReference); } else { // C# // value = object.GetPropertyValue("property") generator.LoadString(propertyName); generator.Call(ReflectionHelpers.ObjectInstance_Indexer_Object); } } else { // Dynamic property access // ----------------------- // x = y.GetPropertyValue("property") generator.Call(ReflectionHelpers.ObjectInstance_Indexer_Object); } }
/// <summary> /// Generates CIL for the in operator. /// </summary> /// <param name="generator"> The generator to output the CIL to. </param> /// <param name="optimizationInfo"> Information about any optimizations that should be performed. </param> private void GenerateIn(ILGenerator generator, OptimizationInfo optimizationInfo) { // Emit the left-hand side expression and convert it to a string. this.Left.GenerateCode(generator, optimizationInfo); EmitConversion.ToString(generator, this.Left.ResultType); // Store the left-hand side expression in a temporary variable. var temp = generator.CreateTemporaryVariable(typeof(string)); generator.StoreVariable(temp); // Emit the right-hand side expression. this.Right.GenerateCode(generator, optimizationInfo); EmitConversion.ToAny(generator, this.Right.ResultType); // Check the right-hand side is a javascript object - if not, throw an exception. generator.Duplicate(); generator.IsInstance(typeof(Library.ObjectInstance)); var endOfTypeCheck = generator.CreateLabel(); generator.BranchIfNotNull(endOfTypeCheck); // Throw an nicely formatted exception. var rightValue = generator.CreateTemporaryVariable(typeof(object)); generator.StoreVariable(rightValue); EmitHelpers.LoadScriptEngine(generator); generator.LoadInt32((int)ErrorType.TypeError); generator.LoadString("The in operator expected an object, but found '{0}' instead"); generator.LoadInt32(1); generator.NewArray(typeof(object)); generator.Duplicate(); generator.LoadInt32(0); generator.LoadVariable(rightValue); generator.Call(ReflectionHelpers.TypeUtilities_TypeOf); generator.StoreArrayElement(typeof(object)); generator.Call(ReflectionHelpers.String_Format); generator.LoadInt32(optimizationInfo.SourceSpan.StartLine); generator.LoadStringOrNull(optimizationInfo.Source.Path); generator.LoadStringOrNull(optimizationInfo.FunctionName); generator.NewObject(ReflectionHelpers.JavaScriptException_Constructor_Error); generator.Throw(); generator.DefineLabelPosition(endOfTypeCheck); generator.ReleaseTemporaryVariable(rightValue); // Load the left-hand side expression from the temporary variable. generator.LoadVariable(temp); // Call ObjectInstance.HasProperty(object) generator.Call(ReflectionHelpers.ObjectInstance_HasProperty); // Allow the temporary variable to be reused. generator.ReleaseTemporaryVariable(temp); }
/// <summary> /// Generates CIL for the expression. /// </summary> /// <param name="generator"> The generator to output the CIL to. </param> /// <param name="optimizationInfo"> Information about any optimizations that should be performed. </param> public override void GenerateCode(ILGenerator generator, OptimizationInfo optimizationInfo) { // Note: we use GetRawOperand() so that grouping operators are not ignored. var operand = this.GetRawOperand(0); // There is only one operand, and it can be either a reference or a function call. // We need to split the operand into a function and some arguments. // If the operand is a reference, it is equivalent to a function call with no arguments. if (operand is FunctionCallExpression) { // Emit the function instance first. var function = ((FunctionCallExpression)operand).Target; function.GenerateCode(generator, optimizationInfo); EmitConversion.ToAny(generator, function.ResultType); } else { // Emit the function instance first. operand.GenerateCode(generator, optimizationInfo); EmitConversion.ToAny(generator, operand.ResultType); } // Check the object really is a function - if not, throw an exception. generator.IsInstance(typeof(Library.FunctionInstance)); generator.Duplicate(); var endOfTypeCheck = generator.CreateLabel(); generator.BranchIfNotNull(endOfTypeCheck); // Throw an nicely formatted exception. var targetValue = generator.CreateTemporaryVariable(typeof(object)); generator.StoreVariable(targetValue); EmitHelpers.LoadScriptEngine(generator); generator.LoadString("TypeError"); generator.LoadString("The new operator requires a function, found a '{0}' instead"); generator.LoadInt32(1); generator.NewArray(typeof(object)); generator.Duplicate(); generator.LoadInt32(0); generator.LoadVariable(targetValue); generator.Call(ReflectionHelpers.TypeUtilities_TypeOf); generator.StoreArrayElement(typeof(object)); generator.Call(ReflectionHelpers.String_Format); generator.LoadInt32(optimizationInfo.SourceSpan.StartLine); generator.LoadStringOrNull(optimizationInfo.Source.Path); generator.LoadStringOrNull(optimizationInfo.FunctionName); generator.NewObject(ReflectionHelpers.JavaScriptException_Constructor_Error); generator.Throw(); generator.DefineLabelPosition(endOfTypeCheck); generator.ReleaseTemporaryVariable(targetValue); if (operand is FunctionCallExpression) { // Emit an array containing the function arguments. ((FunctionCallExpression)operand).GenerateArgumentsArray(generator, optimizationInfo); } else { // Emit an empty array. generator.LoadInt32(0); generator.NewArray(typeof(object)); } // Call FunctionInstance.ConstructLateBound(argumentValues) generator.Call(ReflectionHelpers.FunctionInstance_ConstructLateBound); }
/// <summary> /// Stores the value on the top of the stack in the reference. /// </summary> /// <param name="generator"> The generator to output the CIL to. </param> /// <param name="optimizationInfo"> Information about any optimizations that should be performed. </param> /// <param name="valueType"> The primitive type of the value that is on the top of the stack. </param> public void GenerateSet(ILGenerator generator, OptimizationInfo optimizationInfo, PrimitiveType valueType) { string propertyName = null; TypeOfMemberAccess memberAccessType = DetermineTypeOfMemberAccess(optimizationInfo, out propertyName); if (memberAccessType == TypeOfMemberAccess.ArrayIndex) { // Array indexer // ------------- // xxx = object[index] // Call the indexer. EmitConversion.ToAny(generator, valueType); generator.LoadBoolean(optimizationInfo.StrictMode); generator.Call(ReflectionHelpers.ObjectInstance_SetPropertyValue_Int); generator.Pop(); } else if (memberAccessType == TypeOfMemberAccess.Static) { // Named property modification (e.g. object.property = value) // ---------------------------------------------------------- // object.SetPropertyValue(property, value, strictMode) // Convert the value to an object and store it in a temporary variable. var value = generator.CreateTemporaryVariable(typeof(object)); EmitConversion.ToAny(generator, valueType); generator.StoreVariable(value); // Use a PropertyReference to speed up access if we are inside a loop. if (optimizationInfo.InsideLoop) { ILLocalVariable propertyReference = optimizationInfo.GetPropertyReferenceVariable(generator, propertyName); generator.LoadVariable(propertyReference); generator.Duplicate(); var afterIf = generator.CreateLabel(); generator.BranchIfNotNull(afterIf); generator.Pop(); generator.LoadString(propertyName); generator.NewObject(ReflectionHelpers.PropertyName_Constructor); generator.Duplicate(); generator.StoreVariable(propertyReference); generator.DefineLabelPosition(afterIf); generator.LoadVariable(value); generator.LoadBoolean(optimizationInfo.StrictMode); generator.Call(ReflectionHelpers.ObjectInstance_SetPropertyValue_PropertyReference); generator.Pop(); } else { generator.LoadString(propertyName); generator.LoadVariable(value); generator.LoadBoolean(optimizationInfo.StrictMode); generator.Call(ReflectionHelpers.ObjectInstance_SetPropertyValue_Object); generator.Pop(); } generator.ReleaseTemporaryVariable(value); } else { // Dynamic property access // ----------------------- // object.SetPropertyValue(property, value, strictMode) EmitConversion.ToAny(generator, valueType); generator.LoadBoolean(optimizationInfo.StrictMode); generator.Call(ReflectionHelpers.ObjectInstance_SetPropertyValue_Object); generator.Pop(); } }
/// <summary> /// Generates CIL for the in operator. /// </summary> /// <param name="generator"> The generator to output the CIL to. </param> /// <param name="optimizationInfo"> Information about any optimizations that should be performed. </param> private void GenerateIn(ILGenerator generator, OptimizationInfo optimizationInfo) { // Emit the left-hand side expression and convert it to a string. this.Left.GenerateCode(generator, optimizationInfo); EmitConversion.ToString(generator, this.Left.ResultType); // Store the left-hand side expression in a temporary variable. var temp = generator.CreateTemporaryVariable(typeof(string)); generator.StoreVariable(temp); // Emit the right-hand side expression. this.Right.GenerateCode(generator, optimizationInfo); EmitConversion.ToAny(generator, this.Right.ResultType); // Check the right-hand side is a javascript object - if not, throw an exception. generator.IsInstance(typeof(Library.ObjectInstance)); generator.Duplicate(); var endOfTypeCheck = generator.CreateLabel(); generator.BranchIfNotNull(endOfTypeCheck); // Throw an nicely formatted exception. var rightValue = generator.CreateTemporaryVariable(typeof(object)); generator.StoreVariable(rightValue); EmitHelpers.LoadScriptEngine(generator); generator.LoadString("TypeError"); generator.LoadString("The in operator expected an object, but found '{0}' instead"); generator.LoadInt32(1); generator.NewArray(typeof(object)); generator.Duplicate(); generator.LoadInt32(0); generator.LoadVariable(rightValue); generator.Call(ReflectionHelpers.TypeUtilities_TypeOf); generator.StoreArrayElement(typeof(object)); generator.Call(ReflectionHelpers.String_Format); generator.LoadInt32(optimizationInfo.SourceSpan.StartLine); generator.LoadStringOrNull(optimizationInfo.Source.Path); generator.LoadStringOrNull(optimizationInfo.FunctionName); generator.NewObject(ReflectionHelpers.JavaScriptException_Constructor_Error); generator.Throw(); generator.DefineLabelPosition(endOfTypeCheck); generator.ReleaseTemporaryVariable(rightValue); // Load the left-hand side expression from the temporary variable. generator.LoadVariable(temp); // Call ObjectInstance.HasProperty(object) generator.Call(ReflectionHelpers.ObjectInstance_HasProperty); // Allow the temporary variable to be reused. generator.ReleaseTemporaryVariable(temp); }
/// <summary> /// Generates a method that does type conversion and calls the bound method. /// </summary> /// <param name="generator"> The ILGenerator used to output the body of the method. </param> /// <param name="argumentCount"> The number of arguments that will be passed to the delegate. </param> /// <returns> A delegate that does type conversion and calls the method represented by this /// object. </returns> protected override void GenerateStub(ILGenerator generator, int argumentCount) { // Here is what we are going to generate. //private static object SampleBinder(ScriptEngine engine, object thisObject, object[] arguments) //{ // // Target function signature: int (bool, int, string, object). // bool param1; // int param2; // string param3; // object param4; // param1 = arguments[0] != 0; // param2 = TypeConverter.ToInt32(arguments[1]); // param3 = TypeConverter.ToString(arguments[2]); // param4 = Undefined.Value; // return thisObject.targetMethod(param1, param2, param3, param4); //} // Find the target method. var binderMethod = this.buckets[Math.Min(argumentCount, this.buckets.Length - 1)]; // Constrain the number of apparent arguments to within the required bounds. int minArgumentCount = binderMethod.RequiredParameterCount; int maxArgumentCount = binderMethod.RequiredParameterCount + binderMethod.OptionalParameterCount; if (binderMethod.HasParamArray == true) { maxArgumentCount = int.MaxValue; } foreach (var argument in binderMethod.GenerateArguments(generator, Math.Min(Math.Max(argumentCount, minArgumentCount), maxArgumentCount))) { switch (argument.Source) { case BinderArgumentSource.ScriptEngine: // Load the "engine" parameter passed by the client. generator.LoadArgument(0); break; case BinderArgumentSource.ThisValue: // Load the "this" parameter passed by the client. generator.LoadArgument(1); bool inheritsFromObjectInstance = typeof(ObjectInstance).IsAssignableFrom(argument.Type); if (argument.Type.IsClass == true && inheritsFromObjectInstance == false && argument.Type != typeof(string) && argument.Type != typeof(object)) { // If the "this" object is an unsupported class, pass it through unmodified. generator.CastClass(argument.Type); } else { if (argument.Type != typeof(object)) { // If the target "this" object type is not of type object, throw an error if // the value is undefined or null. generator.Duplicate(); var temp = generator.CreateTemporaryVariable(typeof(object)); generator.StoreVariable(temp); generator.LoadArgument(0); generator.LoadVariable(temp); generator.LoadString(binderMethod.Name); generator.Call(ReflectionHelpers.TypeUtilities_VerifyThisObject); generator.ReleaseTemporaryVariable(temp); } // Convert to the target type. EmitTypeConversion(generator, typeof(object), argument.Type); if (argument.Type != typeof(ObjectInstance) && inheritsFromObjectInstance == true) { // EmitConversionToObjectInstance can emit null if the toType is derived from ObjectInstance. // Therefore, if the value emitted is null it means that the "thisObject" is a type derived // from ObjectInstance (e.g. FunctionInstance) and the value provided is a different type // (e.g. ArrayInstance). In this case, throw an exception explaining that the function is // not generic. var endOfThrowLabel = generator.CreateLabel(); generator.Duplicate(); generator.BranchIfNotNull(endOfThrowLabel); generator.LoadArgument(0); EmitHelpers.EmitThrow(generator, "TypeError", string.Format("The method '{0}' is not generic", binderMethod.Name)); generator.DefineLabelPosition(endOfThrowLabel); } } break; case BinderArgumentSource.InputParameter: if (argument.InputParameterIndex < argumentCount) { // Load the argument onto the stack. generator.LoadArgument(2); generator.LoadInt32(argument.InputParameterIndex); generator.LoadArrayElement(typeof(object)); // Get some flags that apply to the parameter. var parameterFlags = JSParameterFlags.None; var parameterAttribute = argument.GetCustomAttribute <JSParameterAttribute>(); if (parameterAttribute != null) { if (argument.Type != typeof(ObjectInstance)) { throw new NotImplementedException("[JSParameter] is only supported for arguments of type ObjectInstance."); } parameterFlags = parameterAttribute.Flags; } if ((parameterFlags & JSParameterFlags.DoNotConvert) == 0) { // Convert the input parameter to the correct type. EmitTypeConversion(generator, typeof(object), argument); } else { // Don't do argument conversion. /*var endOfThrowLabel = generator.CreateLabel(); * generator.IsInstance(typeof(ObjectInstance)); * generator.Duplicate(); * generator.BranchIfNotNull(endOfThrowLabel); * EmitHelpers.EmitThrow(generator, "TypeError", string.Format("Parameter {1} parameter of '{0}' must be an object", binderMethod.Name, argument.InputParameterIndex)); * generator.DefineLabelPosition(endOfThrowLabel);*/ } } else { // The target method has more parameters than we have input values. EmitUndefined(generator, argument); } break; } } // Emit the call. binderMethod.GenerateCall(generator); // Convert the return value. if (binderMethod.ReturnType == typeof(void)) { EmitHelpers.EmitUndefined(generator); } else { EmitTypeConversion(generator, binderMethod.ReturnType, typeof(object)); // Convert a null return value to Null.Value or Undefined.Value. var endOfSpecialCaseLabel = generator.CreateLabel(); generator.Duplicate(); generator.BranchIfNotNull(endOfSpecialCaseLabel); generator.Pop(); if ((binderMethod.Flags & JSFunctionFlags.ConvertNullReturnValueToUndefined) != 0) { EmitHelpers.EmitUndefined(generator); } else { EmitHelpers.EmitNull(generator); } generator.DefineLabelPosition(endOfSpecialCaseLabel); } // End the IL. generator.Complete(); }
/// <summary> /// Pushes the value of the reference onto the stack. /// </summary> /// <param name="generator"> The generator to output the CIL to. </param> /// <param name="optimizationInfo"> Information about any optimizations that should be performed. </param> /// <param name="throwIfUnresolvable"> <c>true</c> to throw a ReferenceError exception if /// the name is unresolvable; <c>false</c> to output <c>null</c> instead. </param> public void GenerateGet(ILGenerator generator, OptimizationInfo optimizationInfo, bool throwIfUnresolvable) { // This method generates code to retrieve the value of a variable, given the name of // variable and scope in which the variable is being referenced. The variable was // not necessary declared in this scope - it might be declared in any of the parent // scopes (together called a scope chain). The general algorithm is to start at the // head of the chain and search backwards until the variable is found. There are // two types of scopes: declarative scopes and object scopes. Object scopes are hard - // it cannot be known at compile time whether the variable exists or not so runtime // checks have to be inserted. Declarative scopes are easier - variables have to be // declared and cannot be deleted. There is one tricky bit: new variables can be // introduced into a declarative scope at runtime by a non-strict eval() statement. // Even worse, variables that were introduced by means of an eval() *can* be deleted. var scope = this.Scope; ILLocalVariable scopeVariable = null; var endOfGet = generator.CreateLabel(); do { if (scope is DeclarativeScope) { // The variable was declared in this scope. var variable = scope.GetDeclaredVariable(this.Name); if (variable != null) { if (scope.ExistsAtRuntime == false) { // The scope has been optimized away. The value of the variable is stored // in an ILVariable. // Declare an IL local variable if no storage location has been allocated yet. if (variable.Store == null) variable.Store = generator.DeclareVariable(typeof(object), variable.Name); // Load the value from the variable. generator.LoadVariable(variable.Store); // Ensure that we match ResultType. EmitConversion.Convert(generator, variable.Type, this.ResultType, optimizationInfo); } else { // scope.Values[index] if (scopeVariable == null) EmitHelpers.LoadScope(generator); else generator.LoadVariable(scopeVariable); generator.CastClass(typeof(DeclarativeScope)); generator.Call(ReflectionHelpers.DeclarativeScope_Values); generator.LoadInt32(variable.Index); generator.LoadArrayElement(typeof(object)); } // The variable was found - no need to search any more parent scopes. break; } else { // The variable was not defined at compile time, but may have been // introduced by an eval() statement. if (optimizationInfo.MethodOptimizationHints.HasEval == true) { // Check the variable exists: if (scope.HasValue(variableName) == true) { if (scopeVariable == null) EmitHelpers.LoadScope(generator); else generator.LoadVariable(scopeVariable); generator.CastClass(typeof(DeclarativeScope)); generator.LoadString(this.Name); generator.Call(ReflectionHelpers.Scope_HasValue); var hasValueClause = generator.CreateLabel(); generator.BranchIfFalse(hasValueClause); // Load the value of the variable. if (scopeVariable == null) EmitHelpers.LoadScope(generator); else generator.LoadVariable(scopeVariable); generator.CastClass(typeof(DeclarativeScope)); generator.LoadString(this.Name); generator.Call(ReflectionHelpers.Scope_GetValue); generator.Branch(endOfGet); // } generator.DefineLabelPosition(hasValueClause); } } } else { if (scope.ParentScope == null) { // Global variable access // ------------------------------------------- // __object_cacheKey = null; // __object_property_cachedIndex = 0; // ... // if (__object_cacheKey != object.InlineCacheKey) // xxx = object.InlineGetPropertyValue("variable", out __object_property_cachedIndex, out __object_cacheKey) // else // xxx = object.InlinePropertyValues[__object_property_cachedIndex]; // Get a reference to the global object. if (scopeVariable == null) EmitHelpers.LoadScope(generator); else generator.LoadVariable(scopeVariable); generator.CastClass(typeof(ObjectScope)); generator.Call(ReflectionHelpers.ObjectScope_ScopeObject); // TODO: share these variables somehow. var cacheKey = generator.DeclareVariable(typeof(object)); var cachedIndex = generator.DeclareVariable(typeof(int)); // Store the object into a temp variable. var objectInstance = generator.DeclareVariable(PrimitiveType.Object); generator.StoreVariable(objectInstance); // if (__object_cacheKey != object.InlineCacheKey) generator.LoadVariable(cacheKey); generator.LoadVariable(objectInstance); generator.Call(ReflectionHelpers.ObjectInstance_InlineCacheKey); var elseClause = generator.CreateLabel(); generator.BranchIfEqual(elseClause); // value = object.InlineGetProperty("property", out __object_property_cachedIndex, out __object_cacheKey) generator.LoadVariable(objectInstance); generator.LoadString(this.Name); generator.LoadAddressOfVariable(cachedIndex); generator.LoadAddressOfVariable(cacheKey); generator.Call(ReflectionHelpers.ObjectInstance_InlineGetPropertyValue); var endOfIf = generator.CreateLabel(); generator.Branch(endOfIf); // else generator.DefineLabelPosition(elseClause); // value = object.InlinePropertyValues[__object_property_cachedIndex]; generator.LoadVariable(objectInstance); generator.Call(ReflectionHelpers.ObjectInstance_InlinePropertyValues); generator.LoadVariable(cachedIndex); generator.LoadArrayElement(typeof(object)); // End of the if statement generator.DefineLabelPosition(endOfIf); // Check if the value is null. generator.Duplicate(); generator.BranchIfNotNull(endOfGet); if (scope.ParentScope != null) generator.Pop(); } else { // Gets the value of a variable in an object scope. if (scopeVariable == null) EmitHelpers.LoadScope(generator); else generator.LoadVariable(scopeVariable); generator.CastClass(typeof(ObjectScope)); generator.Call(ReflectionHelpers.ObjectScope_ScopeObject); generator.LoadString(this.Name); generator.Call(ReflectionHelpers.ObjectInstance_GetPropertyValue_Object); // Check if the value is null. generator.Duplicate(); generator.BranchIfNotNull(endOfGet); if (scope.ParentScope != null) generator.Pop(); } } // Try the parent scope. if (scope.ParentScope != null && scope.ExistsAtRuntime == true) { if (scopeVariable == null) { scopeVariable = generator.CreateTemporaryVariable(typeof(Scope)); EmitHelpers.LoadScope(generator); } else { generator.LoadVariable(scopeVariable); } generator.Call(ReflectionHelpers.Scope_ParentScope); generator.StoreVariable(scopeVariable); } scope = scope.ParentScope; } while (scope != null); // Throw an error if the name does not exist and throwIfUnresolvable is true. if (scope == null && throwIfUnresolvable == true) EmitHelpers.EmitThrow(generator, ErrorType.ReferenceError, this.Name + " is not defined", optimizationInfo); // Release the temporary variable. if (scopeVariable != null) generator.ReleaseTemporaryVariable(scopeVariable); // Define a label at the end. generator.DefineLabelPosition(endOfGet); // Object scope references may have side-effects (because of getters) so if the value // is to be ignored we evaluate the value then pop the value from the stack. //if (optimizationInfo.SuppressReturnValue == true) // generator.Pop(); }
/// <summary> /// Generates an array containing the argument values for a tagged template literal. /// </summary> /// <param name="generator"> The generator to output the CIL to. </param> /// <param name="optimizationInfo"> Information about any optimizations that should be performed. </param> /// <param name="templateLiteral"> The template literal expression containing the parameter /// values. </param> internal void GenerateTemplateArgumentsArray(ILGenerator generator, OptimizationInfo optimizationInfo, TemplateLiteralExpression templateLiteral) { // Generate an array containing the value of each argument. generator.LoadInt32(templateLiteral.Values.Count + 1); generator.NewArray(typeof(object)); // Load the first parameter. generator.Duplicate(); generator.LoadInt32(0); // Generate a unique integer that is used as the cache key. int callSiteId = System.Threading.Interlocked.Increment(ref templateCallSiteId); // Call GetCachedTemplateStringsArray(ScriptEngine engine, int callSiteId) EmitHelpers.LoadScriptEngine(generator); generator.LoadInt32(callSiteId); generator.CallStatic(ReflectionHelpers.ReflectionHelpers_GetCachedTemplateStringsArray); // If that's null, do it the long way. var afterCreateTemplateStringsArray = generator.CreateLabel(); generator.Duplicate(); generator.BranchIfNotNull(afterCreateTemplateStringsArray); generator.Pop(); // Start emitting arguments for CreateTemplateStringsArray. EmitHelpers.LoadScriptEngine(generator); // int callSiteId generator.LoadInt32(callSiteId); // string[] strings generator.LoadInt32(templateLiteral.Strings.Count); generator.NewArray(typeof(string)); for (int i = 0; i < templateLiteral.Strings.Count; i++) { // strings[i] = templateLiteral.Strings[i] generator.Duplicate(); generator.LoadInt32(i); generator.LoadString(templateLiteral.Strings[i]); generator.StoreArrayElement(typeof(string)); } // string[] raw generator.LoadInt32(templateLiteral.RawStrings.Count); generator.NewArray(typeof(string)); for (int i = 0; i < templateLiteral.RawStrings.Count; i++) { // raw[i] = templateLiteral.RawStrings[i] generator.Duplicate(); generator.LoadInt32(i); generator.LoadString(templateLiteral.RawStrings[i]); generator.StoreArrayElement(typeof(string)); } // CreateTemplateStringsArray(ScriptEngine engine, int callSiteId, object[] strings, object[] rawStrings) generator.CallStatic(ReflectionHelpers.ReflectionHelpers_CreateTemplateStringsArray); generator.DefineLabelPosition(afterCreateTemplateStringsArray); // Store in the array. generator.StoreArrayElement(typeof(object)); // Values are passed as subsequent parameters. for (int i = 0; i < templateLiteral.Values.Count; i++) { generator.Duplicate(); generator.LoadInt32(i + 1); templateLiteral.Values[i].GenerateCode(generator, optimizationInfo); EmitConversion.ToAny(generator, templateLiteral.Values[i].ResultType); generator.StoreArrayElement(typeof(object)); } }
/// <summary> /// Generates CIL for the expression. /// </summary> /// <param name="generator"> The generator to output the CIL to. </param> /// <param name="optimizationInfo"> Information about any optimizations that should be performed. </param> public override void GenerateCode(ILGenerator generator, OptimizationInfo optimizationInfo) { // Note: we use GetRawOperand() so that grouping operators are not ignored. var operand = this.GetRawOperand(0); // There is only one operand, and it can be either a reference or a function call. // We need to split the operand into a function and some arguments. // If the operand is a reference, it is equivalent to a function call with no arguments. if (operand is FunctionCallExpression) { // Emit the function instance first. var function = ((FunctionCallExpression)operand).Target; function.GenerateCode(generator, optimizationInfo); EmitConversion.ToAny(generator, function.ResultType); } else { // Emit the function instance first. operand.GenerateCode(generator, optimizationInfo); EmitConversion.ToAny(generator, operand.ResultType); } // Check the object really is a function - if not, throw an exception. generator.IsInstance(typeof(Library.FunctionInstance)); generator.Duplicate(); var endOfTypeCheck = generator.CreateLabel(); generator.BranchIfNotNull(endOfTypeCheck); // Throw an nicely formatted exception. var targetValue = generator.CreateTemporaryVariable(typeof(object)); generator.StoreVariable(targetValue); EmitHelpers.LoadScriptEngine(generator); generator.LoadString("TypeError"); generator.LoadString("The new operator requires a function, found a '{0}' instead"); generator.LoadInt32(1); generator.NewArray(typeof(object)); generator.Duplicate(); generator.LoadInt32(0); generator.LoadVariable(targetValue); generator.Call(ReflectionHelpers.TypeUtilities_TypeOf); generator.StoreArrayElement(typeof(object)); generator.Call(ReflectionHelpers.String_Format); generator.NewObject(ReflectionHelpers.JavaScriptException_Constructor_Error); generator.Throw(); generator.DefineLabelPosition(endOfTypeCheck); generator.ReleaseTemporaryVariable(targetValue); if (operand is FunctionCallExpression) { // Emit an array containing the function arguments. ((FunctionCallExpression)operand).GenerateArgumentsArray(generator, optimizationInfo); } else { // Emit an empty array. generator.LoadInt32(0); generator.NewArray(typeof(object)); } // Call FunctionInstance.ConstructLateBound(argumentValues) generator.Call(ReflectionHelpers.FunctionInstance_ConstructLateBound); }
/// <summary> /// Generates CIL for the expression. /// </summary> /// <param name="generator"> The generator to output the CIL to. </param> /// <param name="optimizationInfo"> Information about any optimizations that should be performed. </param> public override void GenerateCode(ILGenerator generator, OptimizationInfo optimizationInfo) { // Check if this is a direct call to eval(). if (this.Target is NameExpression && ((NameExpression)this.Target).Name == "eval") { GenerateEval(generator, optimizationInfo); return; } // Emit the function instance first. ILLocalVariable targetBase = null; if (this.Target is MemberAccessExpression) { // The function is a member access expression (e.g. "Math.cos()"). // Evaluate the left part of the member access expression. var baseExpression = ((MemberAccessExpression)this.Target).Base; baseExpression.GenerateCode(generator, optimizationInfo); EmitConversion.ToAny(generator, baseExpression.ResultType); targetBase = generator.CreateTemporaryVariable(typeof(object)); generator.StoreVariable(targetBase); // Evaluate the right part of the member access expression. var memberAccessExpression = new MemberAccessExpression(((MemberAccessExpression)this.Target).Operator); memberAccessExpression.Push(new TemporaryVariableExpression(targetBase)); memberAccessExpression.Push(((MemberAccessExpression)this.Target).GetOperand(1)); memberAccessExpression.GenerateCode(generator, optimizationInfo); EmitConversion.ToAny(generator, this.Target.ResultType); } else { // Something else (e.g. "eval()"). this.Target.GenerateCode(generator, optimizationInfo); EmitConversion.ToAny(generator, this.Target.ResultType); } // Check the object really is a function - if not, throw an exception. generator.IsInstance(typeof(Library.FunctionInstance)); generator.Duplicate(); var endOfTypeCheck = generator.CreateLabel(); generator.BranchIfNotNull(endOfTypeCheck); // Throw an nicely formatted exception. generator.Pop(); EmitHelpers.EmitThrow(generator, "TypeError", string.Format("'{0}' is not a function", this.Target.ToString())); generator.DefineLabelPosition(endOfTypeCheck); // Pass in the path, function name and line. generator.LoadStringOrNull(optimizationInfo.Source.Path); generator.LoadStringOrNull(optimizationInfo.FunctionName); generator.LoadInt32(optimizationInfo.SourceSpan.StartLine); // Generate code to produce the "this" value. There are three cases. if (this.Target is NameExpression) { // 1. The function is a name expression (e.g. "parseInt()"). // In this case this = scope.ImplicitThisValue, if there is one, otherwise undefined. ((NameExpression)this.Target).GenerateThis(generator); } else if (this.Target is MemberAccessExpression) { // 2. The function is a member access expression (e.g. "Math.cos()"). // In this case this = Math. //var baseExpression = ((MemberAccessExpression)this.Target).Base; //baseExpression.GenerateCode(generator, optimizationInfo); //EmitConversion.ToAny(generator, baseExpression.ResultType); generator.LoadVariable(targetBase); } else { // 3. Neither of the above (e.g. "(function() { return 5 })()") // In this case this = undefined. EmitHelpers.EmitUndefined(generator); } // Emit an array containing the function arguments. GenerateArgumentsArray(generator, optimizationInfo); // Call FunctionInstance.CallLateBound(thisValue, argumentValues) generator.Call(ReflectionHelpers.FunctionInstance_CallWithStackTrace); // Allow reuse of the temporary variable. if (targetBase != null) generator.ReleaseTemporaryVariable(targetBase); }
/// <summary> /// Stores the value on the top of the stack in the reference. /// </summary> /// <param name="generator"> The generator to output the CIL to. </param> /// <param name="optimizationInfo"> Information about any optimizations that should be performed. </param> /// <param name="valueType"> The primitive type of the value that is on the top of the stack. </param> /// <param name="throwIfUnresolvable"> <c>true</c> to throw a ReferenceError exception if /// the name is unresolvable; <c>false</c> to create a new property instead. </param> public void GenerateSet(ILGenerator generator, OptimizationInfo optimizationInfo, PrimitiveType valueType, bool throwIfUnresolvable) { // The value is initially on the top of the stack but is stored in this variable // at the last possible moment. ILLocalVariable value = null; var scope = this.Scope; ILLocalVariable scopeVariable = null; var endOfSet = generator.CreateLabel(); do { if (scope is DeclarativeScope) { // Get information about the variable. var variable = scope.GetDeclaredVariable(this.Name); if (variable != null) { // The variable was declared in this scope. if (scope.ExistsAtRuntime == false) { // The scope has been optimized away. The value of the variable is stored // in an ILVariable. // Declare an IL local variable if no storage location has been allocated yet. if (variable.Store == null) { variable.Store = generator.DeclareVariable(typeof(object), variable.Name); } if (value == null) { // The value to store is on the top of the stack - convert it to the // storage type of the variable. EmitConversion.Convert(generator, valueType, variable.Type, optimizationInfo); } else { // The value to store is in a temporary variable. generator.LoadVariable(value); EmitConversion.Convert(generator, PrimitiveType.Any, variable.Type, optimizationInfo); } // Store the value in the variable. generator.StoreVariable(variable.Store); } else if (variable.Writable == true) { if (value == null) { // The value to store is on the top of the stack - convert it to an // object and store it in a temporary variable. EmitConversion.Convert(generator, valueType, PrimitiveType.Any, optimizationInfo); value = generator.CreateTemporaryVariable(typeof(object)); generator.StoreVariable(value); } // scope.Values[index] = value if (scopeVariable == null) { EmitHelpers.LoadScope(generator); } else { generator.LoadVariable(scopeVariable); } generator.CastClass(typeof(DeclarativeScope)); generator.Call(ReflectionHelpers.DeclarativeScope_Values); generator.LoadInt32(variable.Index); generator.LoadVariable(value); generator.StoreArrayElement(typeof(object)); } else { // The variable exists, but is read-only. // Pop the value off the stack (if it is still there). if (value == null) { generator.Pop(); } } // The variable was found - no need to search any more parent scopes. break; } else { // The variable was not defined at compile time, but may have been // introduced by an eval() statement. if (optimizationInfo.MethodOptimizationHints.HasEval == true) { if (value == null) { // The value to store is on the top of the stack - convert it to an // object and store it in a temporary variable. EmitConversion.Convert(generator, valueType, PrimitiveType.Any, optimizationInfo); value = generator.CreateTemporaryVariable(typeof(object)); generator.StoreVariable(value); } // Check the variable exists: if (scope.HasValue(variableName) == true) { if (scopeVariable == null) { EmitHelpers.LoadScope(generator); } else { generator.LoadVariable(scopeVariable); } generator.CastClass(typeof(DeclarativeScope)); generator.LoadString(this.Name); generator.Call(ReflectionHelpers.Scope_HasValue); var hasValueClause = generator.CreateLabel(); generator.BranchIfFalse(hasValueClause); // Set the value of the variable. if (scopeVariable == null) { EmitHelpers.LoadScope(generator); } else { generator.LoadVariable(scopeVariable); } generator.CastClass(typeof(DeclarativeScope)); generator.LoadString(this.Name); generator.LoadVariable(value); generator.Call(ReflectionHelpers.Scope_SetValue); generator.Branch(endOfSet); // } generator.DefineLabelPosition(hasValueClause); } } } else { if (value == null) { // The value to store is on the top of the stack - convert it to an // object and store it in a temporary variable. EmitConversion.Convert(generator, valueType, PrimitiveType.Any, optimizationInfo); value = generator.CreateTemporaryVariable(typeof(object)); generator.StoreVariable(value); } if (scopeVariable == null) { EmitHelpers.LoadScope(generator); } else { generator.LoadVariable(scopeVariable); } generator.CastClass(typeof(ObjectScope)); generator.Call(ReflectionHelpers.ObjectScope_ScopeObject); if (scope.ParentScope == null && throwIfUnresolvable == false) { // Sets the value of a global variable. // JS: object.property = value // C# ==> // if (propertyName == null) // propertyName = new PropertyName("property"); // object.SetPropertyValue(propertyName, value, strictMode); ILLocalVariable propertyName = optimizationInfo.GetGlobalPropertyReferenceVariable(generator, this.Name); generator.LoadVariable(propertyName); generator.Duplicate(); var afterIf = generator.CreateLabel(); generator.BranchIfNotNull(afterIf); generator.Pop(); generator.LoadString(this.Name); generator.NewObject(ReflectionHelpers.PropertyName_Constructor); generator.Duplicate(); generator.StoreVariable(propertyName); generator.DefineLabelPosition(afterIf); generator.LoadVariable(value); generator.LoadBoolean(optimizationInfo.StrictMode); generator.Call(ReflectionHelpers.ObjectInstance_SetPropertyValue_PropertyReference); } else { // Setting a variable within a "with" scope. generator.LoadString(this.Name); generator.LoadVariable(value); generator.LoadBoolean(optimizationInfo.StrictMode); // Set the property value if the property exists. generator.Call(ReflectionHelpers.ObjectInstance_SetPropertyValueIfExists); // The return value is true if the property was defined, and false if it wasn't. generator.BranchIfTrue(endOfSet); } } // Try the parent scope. if (scope.ParentScope != null && scope.ExistsAtRuntime == true) { if (scopeVariable == null) { scopeVariable = generator.CreateTemporaryVariable(typeof(Scope)); EmitHelpers.LoadScope(generator); } else { generator.LoadVariable(scopeVariable); } generator.Call(ReflectionHelpers.Scope_ParentScope); generator.StoreVariable(scopeVariable); } scope = scope.ParentScope; } while (scope != null); // The value might be still on top of the stack. if (value == null && scope == null) { generator.Pop(); } // Throw an error if the name does not exist and throwIfUnresolvable is true. if (scope == null && throwIfUnresolvable == true) { EmitHelpers.EmitThrow(generator, ErrorType.ReferenceError, this.Name + " is not defined", optimizationInfo); } // Release the temporary variables. if (value != null) { generator.ReleaseTemporaryVariable(value); } if (scopeVariable != null) { generator.ReleaseTemporaryVariable(scopeVariable); } // Define a label at the end. generator.DefineLabelPosition(endOfSet); }
/// <summary> /// Pops the value on the stack, converts it to an object, then pushes the result onto the /// stack. /// </summary> /// <param name="generator"> The IL generator. </param> /// <param name="fromType"> The type to convert from. </param> internal static void EmitConversionToObject(ILGenerator generator, Type fromType) { // If the from type is a reference type, check for null. ILLabel endOfNullCheck = null; if (fromType.IsValueType == false) { var startOfElse = generator.CreateLabel(); endOfNullCheck = generator.CreateLabel(); generator.Duplicate(); generator.BranchIfNotNull(startOfElse); generator.Pop(); EmitHelpers.EmitNull(generator); generator.Branch(endOfNullCheck); generator.DefineLabelPosition(startOfElse); } switch (Type.GetTypeCode(fromType)) { case TypeCode.Boolean: generator.Box(typeof(bool)); break; case TypeCode.Byte: generator.Box(typeof(int)); break; case TypeCode.Char: generator.LoadInt32(1); generator.NewObject(ReflectionHelpers.String_Constructor_Char_Int); break; case TypeCode.DBNull: throw new NotSupportedException("DBNull is not a supported return type."); case TypeCode.Decimal: generator.Call(ReflectionHelpers.Decimal_ToDouble); generator.Box(typeof(double)); break; case TypeCode.Double: generator.Box(typeof(double)); break; case TypeCode.Empty: throw new NotSupportedException("Empty is not a supported return type."); case TypeCode.Int16: generator.Box(typeof(int)); break; case TypeCode.Int32: generator.Box(typeof(int)); break; case TypeCode.Int64: generator.ConvertToDouble(); generator.Box(typeof(double)); break; case TypeCode.DateTime: case TypeCode.Object: // Check if the type must be wrapped with a ClrInstanceWrapper. // Note: if the type is a value type it cannot be a primitive or it would // have been handled elsewhere in the switch. ILLabel endOfWrapCheck = null; if (fromType.IsValueType == false) { generator.Duplicate(); generator.Call(ReflectionHelpers.TypeUtilities_IsPrimitiveOrObject); endOfWrapCheck = generator.CreateLabel(); generator.BranchIfTrue(endOfWrapCheck); } // The type must be wrapped. var temp = generator.CreateTemporaryVariable(fromType); generator.StoreVariable(temp); generator.LoadArgument(0); generator.LoadVariable(temp); if (fromType.IsValueType == true) generator.Box(fromType); generator.ReleaseTemporaryVariable(temp); generator.NewObject(ReflectionHelpers.ClrInstanceWrapper_Constructor); // End of wrap check. if (fromType.IsValueType == false) generator.DefineLabelPosition(endOfWrapCheck); break; case TypeCode.SByte: generator.Box(typeof(int)); break; case TypeCode.Single: generator.Box(typeof(double)); break; case TypeCode.String: break; case TypeCode.UInt16: generator.Box(typeof(int)); break; case TypeCode.UInt32: generator.Box(typeof(uint)); break; case TypeCode.UInt64: generator.ConvertUnsignedToDouble(); generator.Box(typeof(double)); break; } // Label the end of the null check. if (fromType.IsValueType == false) generator.DefineLabelPosition(endOfNullCheck); }
/// <summary> /// Pops the value on the stack, converts it to an object, then pushes the result onto the /// stack. /// </summary> /// <param name="generator"> The IL generator. </param> /// <param name="fromType"> The type to convert from. </param> internal static void EmitConversionToObject(ILGenerator generator, Type fromType) { // If the from type is a reference type, check for null. ILLabel endOfNullCheck = null; if (fromType.IsValueType == false) { var startOfElse = generator.CreateLabel(); endOfNullCheck = generator.CreateLabel(); generator.Duplicate(); generator.BranchIfNotNull(startOfElse); generator.Pop(); EmitHelpers.EmitNull(generator); generator.Branch(endOfNullCheck); generator.DefineLabelPosition(startOfElse); } // Handle Nullable<>. var isNullable = fromType.IsGenericType && fromType.GetGenericTypeDefinition() == typeof(Nullable <>); if (isNullable) { endOfNullCheck = generator.CreateLabel(); var v = generator.CreateTemporaryVariable(fromType); generator.StoreVariable(v); generator.LoadAddressOfVariable(v); var hasValue = ReflectionHelpers.GetInstanceMethod(fromType, "get_HasValue"); generator.Call(hasValue); generator.BranchIfTrue(endOfNullCheck); // Return null. generator.LoadNull(); generator.Return(); // Jump here if it was NOT null. generator.DefineLabelPosition(endOfNullCheck); // Get the underlying value. generator.LoadAddressOfVariable(v); var getValue = ReflectionHelpers.GetInstanceMethod(fromType, "get_Value"); generator.Call(getValue); // Now let the normal conversion work. fromType = fromType.GenericTypeArguments[0]; } switch (Type.GetTypeCode(fromType)) { case TypeCode.Boolean: generator.Box(typeof(bool)); break; case TypeCode.Byte: generator.Box(typeof(int)); break; case TypeCode.Char: generator.LoadInt32(1); generator.NewObject(ReflectionHelpers.String_Constructor_Char_Int); break; case TypeCode.DBNull: throw new NotSupportedException("DBNull is not a supported return type."); case TypeCode.Decimal: generator.Call(ReflectionHelpers.Decimal_ToDouble); generator.Box(typeof(double)); break; case TypeCode.Double: generator.Box(typeof(double)); break; case TypeCode.Empty: throw new NotSupportedException("Empty is not a supported return type."); case TypeCode.Int16: generator.Box(typeof(int)); break; case TypeCode.Int32: generator.Box(typeof(int)); break; case TypeCode.Int64: generator.ConvertToDouble(); generator.Box(typeof(double)); break; case TypeCode.DateTime: case TypeCode.Object: // Check if the type must be wrapped with a ClrInstanceWrapper. // Note: if the type is a value type it cannot be a primitive or it would // have been handled elsewhere in the switch. ILLabel endOfWrapCheck = null; if (fromType.IsValueType == false) { generator.Duplicate(); generator.Call(ReflectionHelpers.TypeUtilities_IsPrimitiveOrObject); endOfWrapCheck = generator.CreateLabel(); generator.BranchIfTrue(endOfWrapCheck); } // The type must be wrapped. var temp = generator.CreateTemporaryVariable(fromType); generator.StoreVariable(temp); generator.LoadArgument(0); generator.LoadVariable(temp); if (fromType.IsValueType == true) { generator.Box(fromType); } generator.ReleaseTemporaryVariable(temp); generator.CallStatic(ReflectionHelpers.ClrInstanceWrapper_Create); // End of wrap check. if (fromType.IsValueType == false) { generator.DefineLabelPosition(endOfWrapCheck); } break; case TypeCode.SByte: generator.Box(typeof(int)); break; case TypeCode.Single: generator.Box(typeof(double)); break; case TypeCode.String: break; case TypeCode.UInt16: generator.Box(typeof(int)); break; case TypeCode.UInt32: generator.Box(typeof(uint)); break; case TypeCode.UInt64: generator.ConvertUnsignedToDouble(); generator.Box(typeof(double)); break; } // Label the end of the null check. if (fromType.IsValueType == false) { generator.DefineLabelPosition(endOfNullCheck); } }
/// <summary> /// Generates IL for the script. /// </summary> /// <param name="generator"> The generator to output the CIL to. </param> /// <param name="optimizationInfo"> Information about any optimizations that should be performed. </param> protected override void GenerateCode(ILGenerator generator, OptimizationInfo optimizationInfo) { // Declare a variable to store the eval result. optimizationInfo.EvalResult = generator.DeclareVariable(typeof(object)); if (this.StrictMode == true) { // Create a new scope. this.InitialScope.GenerateScopeCreation(generator, optimizationInfo); } // Verify the scope is correct. VerifyScope(generator); // Initialize any declarations. this.InitialScope.GenerateDeclarations(generator, optimizationInfo); // Generate the main body of code. this.AbstractSyntaxTree.GenerateCode(generator, optimizationInfo); // Make the return value from the method the eval result. generator.LoadVariable(optimizationInfo.EvalResult); // If the result is null, convert it to undefined. var end = generator.CreateLabel(); generator.Duplicate(); generator.BranchIfNotNull(end); generator.Pop(); EmitHelpers.EmitUndefined(generator); generator.DefineLabelPosition(end); }
/// <summary> /// Pushes the value of the reference onto the stack. /// </summary> /// <param name="generator"> The generator to output the CIL to. </param> /// <param name="optimizationInfo"> Information about any optimizations that should be performed. </param> /// <param name="throwIfUnresolvable"> <c>true</c> to throw a ReferenceError exception if /// the name is unresolvable; <c>false</c> to output <c>null</c> instead. </param> public void GenerateGet(ILGenerator generator, OptimizationInfo optimizationInfo, bool throwIfUnresolvable) { // This method generates code to retrieve the value of a variable, given the name of // variable and scope in which the variable is being referenced. The variable was // not necessary declared in this scope - it might be declared in any of the parent // scopes (together called a scope chain). The general algorithm is to start at the // head of the chain and search backwards until the variable is found. There are // two types of scopes: declarative scopes and object scopes. Object scopes are hard - // it cannot be known at compile time whether the variable exists or not so runtime // checks have to be inserted. Declarative scopes are easier - variables have to be // declared and cannot be deleted. There is one tricky bit: new variables can be // introduced into a declarative scope at runtime by a non-strict eval() statement. // Even worse, variables that were introduced by means of an eval() *can* be deleted. var scope = this.Scope; ILLocalVariable scopeVariable = null; var endOfGet = generator.CreateLabel(); do { if (scope is DeclarativeScope) { // The variable was declared in this scope. var variable = scope.GetDeclaredVariable(this.Name); if (variable != null) { if (scope.ExistsAtRuntime == false) { // The scope has been optimized away. The value of the variable is stored // in an ILVariable. // Declare an IL local variable if no storage location has been allocated yet. if (variable.Store == null) { variable.Store = generator.DeclareVariable(typeof(object), variable.Name); } // Load the value from the variable. generator.LoadVariable(variable.Store); // Ensure that we match ResultType. EmitConversion.Convert(generator, variable.Type, this.ResultType, optimizationInfo); } else { // scope.Values[index] if (scopeVariable == null) { EmitHelpers.LoadScope(generator); } else { generator.LoadVariable(scopeVariable); } generator.CastClass(typeof(DeclarativeScope)); generator.Call(ReflectionHelpers.DeclarativeScope_Values); generator.LoadInt32(variable.Index); generator.LoadArrayElement(typeof(object)); } // The variable was found - no need to search any more parent scopes. break; } else { // The variable was not defined at compile time, but may have been // introduced by an eval() statement. if (optimizationInfo.MethodOptimizationHints.HasEval == true) { // Check the variable exists: if (scope.HasValue(variableName) == true) { if (scopeVariable == null) { EmitHelpers.LoadScope(generator); } else { generator.LoadVariable(scopeVariable); } generator.CastClass(typeof(DeclarativeScope)); generator.LoadString(this.Name); generator.Call(ReflectionHelpers.Scope_HasValue); var hasValueClause = generator.CreateLabel(); generator.BranchIfFalse(hasValueClause); // Load the value of the variable. if (scopeVariable == null) { EmitHelpers.LoadScope(generator); } else { generator.LoadVariable(scopeVariable); } generator.CastClass(typeof(DeclarativeScope)); generator.LoadString(this.Name); generator.Call(ReflectionHelpers.Scope_GetValue); generator.Branch(endOfGet); // } generator.DefineLabelPosition(hasValueClause); } } } else { if (scope.ParentScope == null) { // Global variable access // ------------------------------------------- // __object_cacheKey = null; // __object_property_cachedIndex = 0; // ... // if (__object_cacheKey != object.InlineCacheKey) // xxx = object.InlineGetPropertyValue("variable", out __object_property_cachedIndex, out __object_cacheKey) // else // xxx = object.InlinePropertyValues[__object_property_cachedIndex]; // Get a reference to the global object. if (scopeVariable == null) { EmitHelpers.LoadScope(generator); } else { generator.LoadVariable(scopeVariable); } generator.CastClass(typeof(ObjectScope)); generator.Call(ReflectionHelpers.ObjectScope_ScopeObject); // TODO: share these variables somehow. var cacheKey = generator.DeclareVariable(typeof(object)); var cachedIndex = generator.DeclareVariable(typeof(int)); // Store the object into a temp variable. var objectInstance = generator.DeclareVariable(PrimitiveType.Object); generator.StoreVariable(objectInstance); // if (__object_cacheKey != object.InlineCacheKey) generator.LoadVariable(cacheKey); generator.LoadVariable(objectInstance); generator.Call(ReflectionHelpers.ObjectInstance_InlineCacheKey); var elseClause = generator.CreateLabel(); generator.BranchIfEqual(elseClause); // value = object.InlineGetProperty("property", out __object_property_cachedIndex, out __object_cacheKey) generator.LoadVariable(objectInstance); generator.LoadString(this.Name); generator.LoadAddressOfVariable(cachedIndex); generator.LoadAddressOfVariable(cacheKey); generator.Call(ReflectionHelpers.ObjectInstance_InlineGetPropertyValue); var endOfIf = generator.CreateLabel(); generator.Branch(endOfIf); // else generator.DefineLabelPosition(elseClause); // value = object.InlinePropertyValues[__object_property_cachedIndex]; generator.LoadVariable(objectInstance); generator.Call(ReflectionHelpers.ObjectInstance_InlinePropertyValues); generator.LoadVariable(cachedIndex); generator.LoadArrayElement(typeof(object)); // End of the if statement generator.DefineLabelPosition(endOfIf); // Check if the value is null. generator.Duplicate(); generator.BranchIfNotNull(endOfGet); if (scope.ParentScope != null) { generator.Pop(); } } else { // Gets the value of a variable in an object scope. if (scopeVariable == null) { EmitHelpers.LoadScope(generator); } else { generator.LoadVariable(scopeVariable); } generator.CastClass(typeof(ObjectScope)); generator.Call(ReflectionHelpers.ObjectScope_ScopeObject); generator.LoadString(this.Name); generator.Call(ReflectionHelpers.ObjectInstance_GetPropertyValue_Object); // Check if the value is null. generator.Duplicate(); generator.BranchIfNotNull(endOfGet); if (scope.ParentScope != null) { generator.Pop(); } } } // Try the parent scope. if (scope.ParentScope != null && scope.ExistsAtRuntime == true) { if (scopeVariable == null) { scopeVariable = generator.CreateTemporaryVariable(typeof(Scope)); EmitHelpers.LoadScope(generator); } else { generator.LoadVariable(scopeVariable); } generator.Call(ReflectionHelpers.Scope_ParentScope); generator.StoreVariable(scopeVariable); } scope = scope.ParentScope; } while (scope != null); // Throw an error if the name does not exist and throwIfUnresolvable is true. if (scope == null && throwIfUnresolvable == true) { EmitHelpers.EmitThrow(generator, ErrorType.ReferenceError, this.Name + " is not defined", optimizationInfo); } // Release the temporary variable. if (scopeVariable != null) { generator.ReleaseTemporaryVariable(scopeVariable); } // Define a label at the end. generator.DefineLabelPosition(endOfGet); // Object scope references may have side-effects (because of getters) so if the value // is to be ignored we evaluate the value then pop the value from the stack. //if (optimizationInfo.SuppressReturnValue == true) // generator.Pop(); }
/// <summary> /// Generates a method that does type conversion and calls the bound method. /// </summary> /// <param name="generator"> The ILGenerator used to output the body of the method. </param> /// <param name="argumentCount"> The number of arguments that will be passed to the delegate. </param> /// <returns> A delegate that does type conversion and calls the method represented by this /// object. </returns> protected override void GenerateStub(ILGenerator generator, int argumentCount) { // Here is what we are going to generate. //private static object SampleBinder(ScriptEngine engine, object thisObject, object[] arguments) //{ // // Target function signature: int (bool, int, string, object). // bool param1; // int param2; // string param3; // object param4; // param1 = arguments[0] != 0; // param2 = TypeConverter.ToInt32(arguments[1]); // param3 = TypeConverter.ToString(arguments[2]); // param4 = Undefined.Value; // return thisObject.targetMethod(param1, param2, param3, param4); //} // Find the target method. var binderMethod = this.buckets[Math.Min(argumentCount, this.buckets.Length - 1)]; // Constrain the number of apparent arguments to within the required bounds. int minArgumentCount = binderMethod.RequiredParameterCount; int maxArgumentCount = binderMethod.RequiredParameterCount + binderMethod.OptionalParameterCount; if (binderMethod.HasParamArray == true) maxArgumentCount = int.MaxValue; foreach (var argument in binderMethod.GenerateArguments(generator, Math.Min(Math.Max(argumentCount, minArgumentCount), maxArgumentCount))) { switch (argument.Source) { case BinderArgumentSource.ScriptEngine: // Load the "engine" parameter passed by the client. generator.LoadArgument(0); break; case BinderArgumentSource.ThisValue: // Load the "this" parameter passed by the client. generator.LoadArgument(1); bool inheritsFromObjectInstance = typeof(ObjectInstance).IsAssignableFrom(argument.Type); if (argument.Type.IsClass == true && inheritsFromObjectInstance == false && argument.Type != typeof(string) && argument.Type != typeof(object)) { // If the "this" object is an unsupported class, pass it through unmodified. generator.CastClass(argument.Type); } else { if (argument.Type != typeof(object)) { // If the target "this" object type is not of type object, throw an error if // the value is undefined or null. generator.Duplicate(); var temp = generator.CreateTemporaryVariable(typeof(object)); generator.StoreVariable(temp); generator.LoadArgument(0); generator.LoadVariable(temp); generator.LoadString(binderMethod.Name); generator.Call(ReflectionHelpers.TypeUtilities_VerifyThisObject); generator.ReleaseTemporaryVariable(temp); } // Convert to the target type. EmitTypeConversion(generator, typeof(object), argument.Type); if (argument.Type != typeof(ObjectInstance) && inheritsFromObjectInstance == true) { // EmitConversionToObjectInstance can emit null if the toType is derived from ObjectInstance. // Therefore, if the value emitted is null it means that the "thisObject" is a type derived // from ObjectInstance (e.g. FunctionInstance) and the value provided is a different type // (e.g. ArrayInstance). In this case, throw an exception explaining that the function is // not generic. var endOfThrowLabel = generator.CreateLabel(); generator.Duplicate(); generator.BranchIfNotNull(endOfThrowLabel); generator.LoadArgument(0); EmitHelpers.EmitThrow(generator, "TypeError", string.Format("The method '{0}' is not generic", binderMethod.Name)); generator.DefineLabelPosition(endOfThrowLabel); } } break; case BinderArgumentSource.InputParameter: if (argument.InputParameterIndex < argumentCount) { // Load the argument onto the stack. generator.LoadArgument(2); generator.LoadInt32(argument.InputParameterIndex); generator.LoadArrayElement(typeof(object)); // Get some flags that apply to the parameter. var parameterFlags = JSParameterFlags.None; var parameterAttribute = argument.GetCustomAttribute<JSParameterAttribute>(); if (parameterAttribute != null) { if (argument.Type != typeof(ObjectInstance)) throw new NotImplementedException("[JSParameter] is only supported for arguments of type ObjectInstance."); parameterFlags = parameterAttribute.Flags; } if ((parameterFlags & JSParameterFlags.DoNotConvert) == 0) { // Convert the input parameter to the correct type. EmitTypeConversion(generator, typeof(object), argument); } else { // Don't do argument conversion. /*var endOfThrowLabel = generator.CreateLabel(); generator.IsInstance(typeof(ObjectInstance)); generator.Duplicate(); generator.BranchIfNotNull(endOfThrowLabel); EmitHelpers.EmitThrow(generator, "TypeError", string.Format("Parameter {1} parameter of '{0}' must be an object", binderMethod.Name, argument.InputParameterIndex)); generator.DefineLabelPosition(endOfThrowLabel);*/ } } else { // The target method has more parameters than we have input values. EmitUndefined(generator, argument); } break; } } // Emit the call. binderMethod.GenerateCall(generator); // Convert the return value. if (binderMethod.ReturnType == typeof(void)) EmitHelpers.EmitUndefined(generator); else { EmitTypeConversion(generator, binderMethod.ReturnType, typeof(object)); // Convert a null return value to Null.Value or Undefined.Value. var endOfSpecialCaseLabel = generator.CreateLabel(); generator.Duplicate(); generator.BranchIfNotNull(endOfSpecialCaseLabel); generator.Pop(); if ((binderMethod.Flags & JSFunctionFlags.ConvertNullReturnValueToUndefined) != 0) EmitHelpers.EmitUndefined(generator); else EmitHelpers.EmitNull(generator); generator.DefineLabelPosition(endOfSpecialCaseLabel); } // End the IL. generator.Complete(); }
/// <summary> /// Generates CIL for the expression. /// </summary> /// <param name="generator"> The generator to output the CIL to. </param> /// <param name="optimizationInfo"> Information about any optimizations that should be performed. </param> public override void GenerateCode(ILGenerator generator, OptimizationInfo optimizationInfo) { // Check if this is a direct call to eval(). if (this.Target is NameExpression && ((NameExpression)this.Target).Name == "eval") { GenerateEval(generator, optimizationInfo); return; } // Emit the function instance first. ILLocalVariable targetBase = null; if (this.Target is MemberAccessExpression) { // The function is a member access expression (e.g. "Math.cos()"). // Evaluate the left part of the member access expression. var baseExpression = ((MemberAccessExpression)this.Target).Base; baseExpression.GenerateCode(generator, optimizationInfo); EmitConversion.ToAny(generator, baseExpression.ResultType); targetBase = generator.CreateTemporaryVariable(typeof(object)); generator.StoreVariable(targetBase); // Evaluate the right part of the member access expression. var memberAccessExpression = new MemberAccessExpression(((MemberAccessExpression)this.Target).Operator); memberAccessExpression.Push(new TemporaryVariableExpression(targetBase)); memberAccessExpression.Push(((MemberAccessExpression)this.Target).GetOperand(1)); memberAccessExpression.GenerateCode(generator, optimizationInfo); EmitConversion.ToAny(generator, this.Target.ResultType); } else { // Something else (e.g. "eval()"). this.Target.GenerateCode(generator, optimizationInfo); EmitConversion.ToAny(generator, this.Target.ResultType); } // Check the object really is a function - if not, throw an exception. generator.IsInstance(typeof(Library.FunctionInstance)); generator.Duplicate(); var endOfTypeCheck = generator.CreateLabel(); generator.BranchIfNotNull(endOfTypeCheck); // Throw an nicely formatted exception. generator.Pop(); EmitHelpers.EmitThrow(generator, "TypeError", string.Format("'{0}' is not a function", this.Target.ToString())); generator.DefineLabelPosition(endOfTypeCheck); // Generate code to produce the "this" value. There are three cases. if (this.Target is NameExpression) { // 1. The function is a name expression (e.g. "parseInt()"). // In this case this = scope.ImplicitThisValue, if there is one, otherwise undefined. ((NameExpression)this.Target).GenerateThis(generator); } else if (this.Target is MemberAccessExpression) { // 2. The function is a member access expression (e.g. "Math.cos()"). // In this case this = Math. //var baseExpression = ((MemberAccessExpression)this.Target).Base; //baseExpression.GenerateCode(generator, optimizationInfo); //EmitConversion.ToAny(generator, baseExpression.ResultType); generator.LoadVariable(targetBase); } else { // 3. Neither of the above (e.g. "(function() { return 5 })()") // In this case this = undefined. EmitHelpers.EmitUndefined(generator); } // Emit an array containing the function arguments. GenerateArgumentsArray(generator, optimizationInfo); // Call FunctionInstance.CallLateBound(thisValue, argumentValues) generator.Call(ReflectionHelpers.FunctionInstance_CallLateBound); // Allow reuse of the temporary variable. if (targetBase != null) { generator.ReleaseTemporaryVariable(targetBase); } }
/// <summary> /// Generates CIL for the expression. /// </summary> /// <param name="generator"> The generator to output the CIL to. </param> /// <param name="optimizationInfo"> Information about any optimizations that should be performed. </param> public override void GenerateCode(ILGenerator generator, OptimizationInfo optimizationInfo) { // Literals cannot have side-effects so if a return value is not expected then generate // nothing. //if (optimizationInfo.SuppressReturnValue == true) // return; if (this.Value is int) { generator.LoadInt32((int)this.Value); } else if (this.Value is double) { generator.LoadDouble((double)this.Value); } else if (this.Value is string) { generator.LoadString((string)this.Value); } else if (this.Value is bool) { generator.LoadBoolean((bool)this.Value); } else if (this.Value is RegularExpressionLiteral) { // RegExp var sharedRegExpVariable = optimizationInfo.GetRegExpVariable(generator, (RegularExpressionLiteral)this.Value); var label1 = generator.CreateLabel(); var label2 = generator.CreateLabel(); // if (sharedRegExp == null) { generator.LoadVariable(sharedRegExpVariable); generator.BranchIfNotNull(label1); // sharedRegExp = Global.RegExp.Construct(source, flags) EmitHelpers.LoadScriptEngine(generator); generator.Call(ReflectionHelpers.ScriptEngine_RegExp); generator.LoadString(((RegularExpressionLiteral)this.Value).Pattern); generator.LoadString(((RegularExpressionLiteral)this.Value).Flags); generator.Call(ReflectionHelpers.RegExp_Construct); generator.Duplicate(); generator.StoreVariable(sharedRegExpVariable); // } else { generator.Branch(label2); generator.DefineLabelPosition(label1); // Global.RegExp.Construct(sharedRegExp, flags) EmitHelpers.LoadScriptEngine(generator); generator.Call(ReflectionHelpers.ScriptEngine_RegExp); generator.LoadVariable(sharedRegExpVariable); generator.LoadNull(); generator.Call(ReflectionHelpers.RegExp_Construct); // } generator.DefineLabelPosition(label2); } else if (this.Value == Null.Value) { // Null. EmitHelpers.EmitNull(generator); } else if (this.Value == Undefined.Value) { // Undefined. EmitHelpers.EmitUndefined(generator); } else { throw new NotImplementedException("Unknown literal type."); } }