Pop() 공개 추상적인 메소드

Pops the value from the top of the stack.
public abstract Pop ( ) : void
리턴 void
예제 #1
0
        /// <summary>
        /// Pops the value on the stack, converts it to the given type, then pushes the result
        /// onto the stack.
        /// </summary>
        /// <param name="generator"> The IL generator. </param>
        /// <param name="fromType"> The type to convert from. </param>
        /// <param name="toType"> The type to convert to. </param>
        /// <param name="path"> The path of the javascript source file that is currently executing. </param>
        /// <param name="function"> The name of the currently executing function. </param>
        /// <param name="line"> The line number of the statement that is currently executing. </param>
        public static void Convert(ILGenerator generator, PrimitiveType fromType, PrimitiveType toType, string path, string function, int line)
        {
            // Check that a conversion is actually necessary.
            if (fromType == toType)
            {
                return;
            }

            switch (toType)
            {
            case PrimitiveType.Any:
                ToAny(generator, fromType);
                break;

            case PrimitiveType.Undefined:
                generator.Pop();
                EmitHelpers.EmitUndefined(generator);
                break;

            case PrimitiveType.Null:
                generator.Pop();
                EmitHelpers.EmitNull(generator);
                break;

            case PrimitiveType.Bool:
                ToBool(generator, fromType);
                break;

            case PrimitiveType.Int32:
                ToInt32(generator, fromType);
                break;

            case PrimitiveType.UInt32:
                ToUInt32(generator, fromType);
                break;

            case PrimitiveType.Number:
                ToNumber(generator, fromType);
                break;

            case PrimitiveType.String:
                ToString(generator, fromType);
                break;

            case PrimitiveType.ConcatenatedString:
                ToConcatenatedString(generator, fromType);
                break;

            case PrimitiveType.Object:
                ToObject(generator, fromType, path, function, line);
                break;

            default:
                throw new NotImplementedException(string.Format("Unsupported primitive type: {0}", toType));
            }
        }
예제 #2
0
        /// <summary>
        /// Pops the value on the stack, converts it to a string, then pushes the result onto the
        /// stack.
        /// </summary>
        /// <param name="generator"> The IL generator. </param>
        /// <param name="fromType"> The type to convert from. </param>
        public static void ToString(ILGenerator generator, PrimitiveType fromType)
        {
            // Check that a conversion is actually necessary.
            if (fromType == PrimitiveType.String)
            {
                return;
            }

            switch (fromType)
            {
            case PrimitiveType.Undefined:
                // Converting from undefined produces "undefined".
                generator.Pop();
                generator.LoadString("undefined");
                break;

            case PrimitiveType.Null:
                // Converting from null produces "null".
                generator.Pop();
                generator.LoadString("null");
                break;

            case PrimitiveType.Bool:
                // Converting from a boolean produces "false" if the boolean is false, or "true" if the boolean is true.
                var elseClause = generator.CreateLabel();
                var endOfIf    = generator.CreateLabel();
                generator.BranchIfFalse(elseClause);
                generator.LoadString("true");
                generator.Branch(endOfIf);
                generator.DefineLabelPosition(elseClause);
                generator.LoadString("false");
                generator.DefineLabelPosition(endOfIf);
                break;

            case PrimitiveType.ConcatenatedString:
                generator.Call(ReflectionHelpers.ConcatenatedString_ToString);
                break;

            case PrimitiveType.Int32:
            case PrimitiveType.UInt32:
            case PrimitiveType.Number:
            case PrimitiveType.Any:
            case PrimitiveType.Object:
                // Otherwise, fall back to calling TypeConverter.ToString()
                if (PrimitiveTypeUtilities.IsValueType(fromType))
                {
                    generator.Box(fromType);
                }
                generator.Call(ReflectionHelpers.TypeConverter_ToString);
                break;

            default:
                throw new NotImplementedException(string.Format("Unsupported primitive type: {0}", fromType));
            }
        }
예제 #3
0
        /// <summary>
        /// Pops the value on the stack, converts it to the given type, then pushes the result
        /// onto the stack.
        /// </summary>
        /// <param name="generator"> The IL generator. </param>
        /// <param name="fromType"> The type to convert from. </param>
        /// <param name="toType"> The type to convert to. </param>
        /// <param name="path"> The path of the javascript source file that is currently executing. </param>
        /// <param name="function"> The name of the currently executing function. </param>
        /// <param name="line"> The line number of the statement that is currently executing. </param>
        public static void Convert(ILGenerator generator, PrimitiveType fromType, PrimitiveType toType, string path, string function, int line)
        {
            // Check that a conversion is actually necessary.
            if (fromType == toType)
                return;

            switch (toType)
            {
                case PrimitiveType.Any:
                    ToAny(generator, fromType);
                    break;

                case PrimitiveType.Undefined:
                    generator.Pop();
                    EmitHelpers.EmitUndefined(generator);
                    break;

                case PrimitiveType.Null:
                    generator.Pop();
                    EmitHelpers.EmitNull(generator);
                    break;

                case PrimitiveType.Bool:
                    ToBool(generator, fromType);
                    break;

                case PrimitiveType.Int32:
                    ToInt32(generator, fromType);
                    break;

                case PrimitiveType.UInt32:
                    ToUInt32(generator, fromType);
                    break;

                case PrimitiveType.Number:
                    ToNumber(generator, fromType);
                    break;

                case PrimitiveType.String:
                    ToString(generator, fromType);
                    break;

                case PrimitiveType.ConcatenatedString:
                    ToConcatenatedString(generator, fromType);
                    break;

                case PrimitiveType.Object:
                    ToObject(generator, fromType, path, function, line);
                    break;

                default:
                    throw new NotImplementedException(string.Format("Unsupported primitive type: {0}", toType));
            }
        }
예제 #4
0
        /// <summary>
        /// Pops the value on the stack, converts it to a double, then pushes the double result
        /// onto the stack.
        /// </summary>
        /// <param name="generator"> The IL generator. </param>
        /// <param name="fromType"> The type to convert from. </param>
        public static void ToNumber(ILGenerator generator, PrimitiveType fromType)
        {
            // Check that a conversion is actually necessary.
            if (fromType == PrimitiveType.Number)
            {
                return;
            }

            switch (fromType)
            {
            case PrimitiveType.Undefined:
                // Converting from undefined produces NaN.
                generator.Pop();
                generator.LoadDouble(double.NaN);
                break;

            case PrimitiveType.Null:
                // Converting from null produces 0.
                generator.Pop();
                generator.LoadDouble(0.0);
                break;

            case PrimitiveType.Bool:
                // Converting from a boolean produces 0 if the boolean is false, or 1 if the boolean is true.
                generator.ConvertToDouble();
                break;

            case PrimitiveType.Int32:
                // Converting from int32 produces the same number.
                generator.ConvertToDouble();
                break;

            case PrimitiveType.UInt32:
                // Converting from a number produces the following:
                generator.ConvertUnsignedToDouble();
                break;

            case PrimitiveType.String:
            case PrimitiveType.ConcatenatedString:
            case PrimitiveType.Any:
            case PrimitiveType.Object:
                // Otherwise, fall back to calling TypeConverter.ToNumber()
                generator.Call(ReflectionHelpers.TypeConverter_ToNumber);
                break;

            default:
                throw new NotImplementedException(string.Format("Unsupported primitive type: {0}", fromType));
            }
        }
예제 #5
0
        /// <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);
        }
예제 #6
0
        /// <summary>
        /// Generates CIL for the statement.
        /// </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)
        {
            // Generate code for the start of the statement.
            var statementLocals = new StatementLocals();

            GenerateStartOfStatement(generator, optimizationInfo, statementLocals);

            if (this.ContributesToEvalResult == true && optimizationInfo.EvalResult != null)
            {
                // Emit the expression.
                this.Expression.GenerateCode(generator, optimizationInfo);

                // Store the result.
                EmitConversion.ToAny(generator, this.Expression.ResultType);
                generator.StoreVariable(optimizationInfo.EvalResult);
            }
            else
            {
                // Emit the expression.
                optimizationInfo.IgnoreReturnValue          = this.Expression;
                optimizationInfo.ReturnValueWasNotGenerated = false;
                this.Expression.GenerateCode(generator, optimizationInfo);
                if (!optimizationInfo.ReturnValueWasNotGenerated)
                {
                    generator.Pop();
                }
            }

            // Generate code for the end of the statement.
            GenerateEndOfStatement(generator, optimizationInfo, statementLocals);
        }
        /// <summary>
        /// Generates CIL for the statement.
        /// </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)
        {
            // Generate code for the start of the statement.
            var statementLocals = new StatementLocals();
            GenerateStartOfStatement(generator, optimizationInfo, statementLocals);

            if (this.ContributesToEvalResult == true && optimizationInfo.EvalResult != null)
            {
                // Emit the expression.
                this.Expression.GenerateCode(generator, optimizationInfo);

                // Store the result.
                EmitConversion.ToAny(generator, this.Expression.ResultType);
                generator.StoreVariable(optimizationInfo.EvalResult);
            }
            else
            {
                // Emit the expression.
                this.Expression.GenerateCode(generator, optimizationInfo);
                generator.Pop();
            }

            // Generate code for the end of the statement.
            GenerateEndOfStatement(generator, optimizationInfo, statementLocals);
        }
예제 #8
0
        /// <summary>
        /// Pops the value on the stack, converts it to an integer, then pushes the integer result
        /// onto the stack.  Large numbers wrap (i.e. 4294967296 -> 0).
        /// </summary>
        /// <param name="generator"> The IL generator. </param>
        /// <param name="fromType"> The type to convert from. </param>
        public static void ToInt32(ILGenerator generator, PrimitiveType fromType)
        {
            // Check that a conversion is actually necessary.
            if (fromType == PrimitiveType.Int32 || fromType == PrimitiveType.UInt32 || fromType == PrimitiveType.Bool)
            {
                return;
            }

            switch (fromType)
            {
            case PrimitiveType.Undefined:
            case PrimitiveType.Null:
                // Converting from undefined or null produces 0.
                generator.Pop();
                generator.LoadInt32(0);
                break;

            case PrimitiveType.Number:
                // Converting from a number produces the number mod 4294967296.  NaN produces 0.
                generator.ConvertToUnsignedInteger();
                break;

            case PrimitiveType.String:
            case PrimitiveType.ConcatenatedString:
            case PrimitiveType.Any:
            case PrimitiveType.Object:
                // Otherwise, fall back to calling TypeConverter.ToInt32()
                generator.Call(ReflectionHelpers.TypeConverter_ToInt32);
                break;

            default:
                throw new NotImplementedException(string.Format("Unsupported primitive type: {0}", fromType));
            }
        }
예제 #9
0
        /// <summary>
        /// Generates CIL for the logical operators.
        /// </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 GenerateLogical(ILGenerator generator, OptimizationInfo optimizationInfo)
        {
            // Get the statically-determined types of the left and right operands.
            PrimitiveType leftType  = this.Left.ResultType;
            PrimitiveType rightType = this.Right.ResultType;

            // Load the left-hand side operand.
            this.Left.GenerateCode(generator, optimizationInfo);

            // Make sure the output type is consistant.
            if (leftType != rightType)
            {
                if (PrimitiveTypeUtilities.IsNumeric(leftType) == true && PrimitiveTypeUtilities.IsNumeric(rightType) == true)
                {
                    EmitConversion.ToNumber(generator, leftType);
                    leftType = PrimitiveType.Number;
                }
                else
                {
                    EmitConversion.ToAny(generator, leftType);
                    leftType = PrimitiveType.Any;
                }
            }

            // Duplicate and convert to a Boolean.
            generator.Duplicate();
            EmitConversion.ToBool(generator, leftType);

            // Stack contains "left, (bool)left"
            var endOfIf = generator.CreateLabel();

            if (this.OperatorType == OperatorType.LogicalAnd)
            {
                generator.BranchIfFalse(endOfIf);
            }
            else
            {
                generator.BranchIfTrue(endOfIf);
            }

            // Stack contains "left".  Load the right-hand side operand.
            generator.Pop();
            this.Right.GenerateCode(generator, optimizationInfo);

            // Make sure the output type is consistant.
            if (leftType != rightType)
            {
                if (PrimitiveTypeUtilities.IsNumeric(leftType) == true && PrimitiveTypeUtilities.IsNumeric(rightType) == true)
                {
                    EmitConversion.ToNumber(generator, rightType);
                }
                else
                {
                    EmitConversion.ToAny(generator, rightType);
                }
            }

            // Define the label used above.
            generator.DefineLabelPosition(endOfIf);
        }
예제 #10
0
        /// <summary>
        /// Pops the value on the stack, converts it from one type to another, then pushes the
        /// result onto the stack.  Undefined is converted to the given default value.
        /// </summary>
        /// <param name="generator"> The IL generator. </param>
        /// <param name="fromType"> The type to convert from. </param>
        /// <param name="targetParameter"> The type to convert to and the default value, if there is one. </param>
        private static void EmitTypeConversion(ILGenerator generator, Type fromType, BinderArgument argument)
        {
            // Emit either the default value if there is one, otherwise emit "undefined".
            if (argument.HasDefaultValue)
            {
                // Check if the input value is undefined.
                var elseClause = generator.CreateLabel();
                generator.Duplicate();
                generator.BranchIfNull(elseClause);
                generator.Duplicate();
                generator.LoadField(ReflectionHelpers.Undefined_Value);
                generator.CompareEqual();
                generator.BranchIfTrue(elseClause);

                // Convert as per normal.
                EmitTypeConversion(generator, fromType, argument.Type);

                // Jump to the end.
                var endOfIf = generator.CreateLabel();
                generator.Branch(endOfIf);
                generator.DefineLabelPosition(elseClause);

                // Pop the existing value and emit the default value.
                generator.Pop();
                EmitUndefined(generator, argument);

                // Define the end of the block.
                generator.DefineLabelPosition(endOfIf);
            }
            else
            {
                // Convert as per normal.
                EmitTypeConversion(generator, fromType, argument.Type);
            }
        }
예제 #11
0
        /// <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);
            }
        }
예제 #12
0
        /// <summary>
        /// Generates code that initializes the variable and function declarations.
        /// </summary>
        /// <param name="generator"> The generator to output the CIL to. </param>
        /// <param name="optimizationInfo"> Information about any optimizations that should be performed. </param>
        internal virtual void GenerateDeclarations(ILGenerator generator, OptimizationInfo optimizationInfo)
        {
            // Initialize the declared variables and functions.
            foreach (var variable in this.variables.Values)
            {
                // Emit the initialization code.
                if (this is ObjectScope)
                {
                    // Determine the property attributes.
                    var attributes = Library.PropertyAttributes.Enumerable;
                    if (variable.Writable == true)
                    {
                        attributes |= Library.PropertyAttributes.Writable;
                    }
                    if (variable.Deletable == true)
                    {
                        attributes |= Library.PropertyAttributes.Configurable;
                    }

                    if (variable.ValueAtTopOfScope == null)
                    {
                        // void InitializeMissingProperty(object key, PropertyAttributes attributes)
                        EmitHelpers.LoadScope(generator);
                        generator.CastClass(typeof(ObjectScope));
                        generator.Call(ReflectionHelpers.ObjectScope_ScopeObject);
                        generator.LoadString(variable.Name);
                        generator.LoadInt32((int)attributes);
                        generator.Call(ReflectionHelpers.ObjectInstance_InitializeMissingProperty);
                    }
                    else
                    {
                        // bool DefineProperty(string propertyName, PropertyDescriptor descriptor, bool throwOnError)
                        EmitHelpers.LoadScope(generator);
                        generator.CastClass(typeof(ObjectScope));
                        generator.Call(ReflectionHelpers.ObjectScope_ScopeObject);
                        generator.LoadString(variable.Name);
                        variable.ValueAtTopOfScope.GenerateCode(generator, optimizationInfo);
                        EmitConversion.Convert(generator, variable.ValueAtTopOfScope.ResultType, PrimitiveType.Any, optimizationInfo);
                        generator.LoadInt32((int)attributes);
                        generator.NewObject(ReflectionHelpers.PropertyDescriptor_Constructor2);
                        generator.LoadBoolean(false);
                        generator.Call(ReflectionHelpers.ObjectInstance_DefineProperty);
                        generator.Pop();
                    }
                }
                else if (variable.ValueAtTopOfScope != null)
                {
                    variable.ValueAtTopOfScope.GenerateCode(generator, optimizationInfo);
                    var name = new NameExpression(this, variable.Name);
                    name.GenerateSet(generator, optimizationInfo, variable.ValueAtTopOfScope.ResultType, false);
                }
            }
        }
예제 #13
0
        /// <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)
        {
            // Get an array of comma-delimited expressions.
            var items = this.Items;

            for (int i = 0; i < items.Count - 1; i++)
            {
                // Generate code for the item, evaluating the side-effects but not producing any values.
                items[i].GenerateCode(generator, optimizationInfo); //.AddFlags(OptimizationFlags.SuppressReturnValue));
                generator.Pop();
            }

            // Generate code for the last item and return the value.
            items[items.Count - 1].GenerateCode(generator, optimizationInfo);
        }
예제 #14
0
        /// <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)
        {
            // Get an array of comma-delimited expressions.
            var items = this.Items;

            for (int i = 0; i < items.Count - 1; i++)
            {
                // Generate code for the item, evaluating the side-effects but not producing any values.
                items[i].GenerateCode(generator, optimizationInfo); //.AddFlags(OptimizationFlags.SuppressReturnValue));
                generator.Pop();
            }

            // Generate code for the last item and return the value.
            items[items.Count - 1].GenerateCode(generator, optimizationInfo);
        }
        /// <summary>
        /// Generates CIL for the delete 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>
        private void GenerateDelete(ILGenerator generator, OptimizationInfo optimizationInfo)
        {
            // Attempting to delete something that isn't a reference returns true but otherwise does nothing.
            if ((this.Operand is IReferenceExpression) == false)
            {
                // Make sure the expression is evaluated.
                this.Operand.GenerateCode(generator, optimizationInfo);

                // Discard the result and return true.
                generator.Pop();
                generator.LoadBoolean(true);
                return;
            }

            // The operand is a variable or property reference.
            ((IReferenceExpression)this.Operand).GenerateDelete(generator, optimizationInfo);
        }
예제 #16
0
        /// <summary>
        /// Generates code to push the "this" value for a function call.
        /// </summary>
        /// <param name="generator"> The generator to output the CIL to. </param>
        public void GenerateThis(ILGenerator generator)
        {
            // Optimization: if there are no with scopes, simply emit undefined.
            bool scopeChainHasWithScope = false;
            var  scope = this.Scope;

            do
            {
                if (scope is ObjectScope && ((ObjectScope)scope).ProvidesImplicitThisValue == true)
                {
                    scopeChainHasWithScope = true;
                    break;
                }
                scope = scope.ParentScope;
            } while (scope != null);

            if (scopeChainHasWithScope == false)
            {
                // No with scopes in the scope chain, use undefined as the "this" value.
                EmitHelpers.EmitUndefined(generator);
                return;
            }

            var end = generator.CreateLabel();

            scope = this.Scope;
            ILLocalVariable scopeVariable = generator.CreateTemporaryVariable(typeof(Scope));

            EmitHelpers.LoadScope(generator);
            generator.StoreVariable(scopeVariable);

            do
            {
                if (scope is DeclarativeScope)
                {
                    if (scope.HasDeclaredVariable(this.Name))
                    {
                        // The variable exists but declarative scopes always produce undefined for
                        // the "this" value.
                        EmitHelpers.EmitUndefined(generator);
                        break;
                    }
                }
                else
                {
                    var objectScope = (ObjectScope)scope;

                    // Check if the property exists by calling scope.ScopeObject.HasProperty(propertyName)
                    if (objectScope.ProvidesImplicitThisValue == false)
                    {
                        EmitHelpers.EmitUndefined(generator);
                    }
                    generator.LoadVariable(scopeVariable);
                    generator.CastClass(typeof(ObjectScope));
                    generator.Call(ReflectionHelpers.ObjectScope_ScopeObject);
                    if (objectScope.ProvidesImplicitThisValue == true)
                    {
                        generator.Duplicate();
                    }
                    generator.LoadString(this.Name);
                    generator.Call(ReflectionHelpers.ObjectInstance_HasProperty);
                    generator.BranchIfTrue(end);
                    generator.Pop();

                    // If the name is not defined, use undefined for the "this" value.
                    if (scope.ParentScope == null)
                    {
                        EmitHelpers.EmitUndefined(generator);
                    }
                }

                // Try the parent scope.
                if (scope.ParentScope != null && scope.ExistsAtRuntime == true)
                {
                    generator.LoadVariable(scopeVariable);
                    generator.Call(ReflectionHelpers.Scope_ParentScope);
                    generator.StoreVariable(scopeVariable);
                }
                scope = scope.ParentScope;
            } while (scope != null);

            // Release the temporary variable.
            generator.ReleaseTemporaryVariable(scopeVariable);

            // Define a label at the end.
            generator.DefineLabelPosition(end);
        }
예제 #17
0
        /// <summary>
        /// Pops the value on the stack, converts it to an integer, then pushes the integer result
        /// onto the stack.
        /// </summary>
        /// <param name="generator"> The IL generator. </param>
        /// <param name="fromType"> The type to convert from. </param>
        public static void ToInteger(ILGenerator generator, PrimitiveType fromType)
        {
            // Check that a conversion is actually necessary.
            if (fromType == PrimitiveType.Int32 || fromType == PrimitiveType.UInt32 || fromType == PrimitiveType.Bool)
                return;

            switch (fromType)
            {
                case PrimitiveType.Undefined:
                case PrimitiveType.Null:
                    // Converting from undefined or null produces 0.
                    generator.Pop();
                    generator.LoadInt32(0);
                    break;

                case PrimitiveType.Number:
                    // Converting from a number produces the following:
                    // Any number between -2147483648 and +2147483647 -> itself
                    // Any number smaller than -2147483648 -> -2147483648
                    // Any number larger than +2147483647 -> +2147483647
                    // NaN -> 0

                    // bool isPositiveInfinity = input > 2147483647.0
                    var isPositiveInfinity = generator.CreateTemporaryVariable(typeof(bool));
                    generator.Duplicate();
                    generator.LoadDouble(2147483647.0);
                    generator.CompareGreaterThan();
                    generator.StoreVariable(isPositiveInfinity);

                    // bool notNaN = input == input
                    var notNaN = generator.CreateTemporaryVariable(typeof(bool));
                    generator.Duplicate();
                    generator.Duplicate();
                    generator.CompareEqual();
                    generator.StoreVariable(notNaN);

                    // input = (int)input
                    // Infinity -> -2147483648
                    // -Infinity -> -2147483648
                    // NaN -> -2147483648
                    generator.ConvertToInteger();

                    // input = input & -((int)notNaN)
                    generator.LoadVariable(notNaN);
                    generator.Negate();
                    generator.BitwiseAnd();

                    // input = input - (int)isPositiveInfinity
                    generator.LoadVariable(isPositiveInfinity);
                    generator.Subtract();

                    // The temporary variables are no longer needed.
                    generator.ReleaseTemporaryVariable(notNaN);
                    generator.ReleaseTemporaryVariable(isPositiveInfinity);
                    break;

                case PrimitiveType.String:
                case PrimitiveType.ConcatenatedString:
                case PrimitiveType.Any:
                case PrimitiveType.Object:
                    // Otherwise, fall back to calling TypeConverter.ToInteger()
                    generator.Call(ReflectionHelpers.TypeConverter_ToInteger);
                    break;

                default:
                    throw new NotImplementedException(string.Format("Unsupported primitive type: {0}", fromType));
            }
        }
예제 #18
0
        /// <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);
            }
        }
예제 #19
0
        /// <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 (scope.ParentScope == null)
                    {
                        // Optimization: if this is the global scope, use hidden classes to
                        // optimize variable access.

                        // Global variable modification
                        // ----------------------------
                        // __object_cacheKey = null;
                        // __object_property_cachedIndex = 0;
                        // ...
                        // if (__object_cacheKey != object.InlineCacheKey)
                        //     object.InlineSetPropertyValueIfExists("property", value, strictMode, out __object_property_cachedIndex, out __object_cacheKey)
                        // else
                        //     object.InlinePropertyValues[__object_property_cachedIndex] = value;

                        // 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);

                        // xxx = object.InlineSetPropertyValueIfExists("property", value, strictMode, out __object_property_cachedIndex, out __object_cacheKey)
                        generator.LoadVariable(objectInstance);
                        generator.LoadString(this.Name);
                        generator.LoadVariable(value);
                        generator.LoadBoolean(optimizationInfo.StrictMode);
                        generator.LoadAddressOfVariable(cachedIndex);
                        generator.LoadAddressOfVariable(cacheKey);
                        if (throwIfUnresolvable == false)
                        {
                            // Set the property value unconditionally.
                            generator.Call(ReflectionHelpers.ObjectInstance_InlineSetPropertyValue);
                        }
                        else
                        {
                            // Set the property value if the property exists.
                            generator.Call(ReflectionHelpers.ObjectInstance_InlineSetPropertyValueIfExists);

                            // The return value is true if the property was defined, and false if it wasn't.
                            generator.BranchIfTrue(endOfSet);
                        }

                        var endOfIf = generator.CreateLabel();
                        generator.Branch(endOfIf);

                        // else
                        generator.DefineLabelPosition(elseClause);

                        // object.InlinePropertyValues[__object_property_cachedIndex] = value;
                        generator.LoadVariable(objectInstance);
                        generator.Call(ReflectionHelpers.ObjectInstance_InlinePropertyValues);
                        generator.LoadVariable(cachedIndex);
                        generator.LoadVariable(value);
                        generator.StoreArrayElement(typeof(object));
                        generator.Branch(endOfSet);

                        // End of the if statement
                        generator.DefineLabelPosition(endOfIf);
                    }
                    else
                    {
                        // Slow route.

                        if (scopeVariable == null)
                        {
                            EmitHelpers.LoadScope(generator);
                        }
                        else
                        {
                            generator.LoadVariable(scopeVariable);
                        }
                        generator.CastClass(typeof(ObjectScope));
                        generator.Call(ReflectionHelpers.ObjectScope_ScopeObject);
                        generator.LoadString(this.Name);
                        generator.LoadVariable(value);
                        generator.LoadBoolean(optimizationInfo.StrictMode);

                        if (scope.ParentScope == null && throwIfUnresolvable == false)
                        {
                            // Set the property value unconditionally.
                            generator.Call(ReflectionHelpers.ObjectInstance_SetPropertyValue_Object);
                        }
                        else
                        {
                            // 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);
        }
예제 #20
0
        /// <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);
        }
예제 #21
0
        /// <summary>
        /// Pops the value on the stack, converts it to an integer, then pushes the integer result
        /// onto the stack.
        /// </summary>
        /// <param name="generator"> The IL generator. </param>
        /// <param name="fromType"> The type to convert from. </param>
        public static void ToInteger(ILGenerator generator, PrimitiveType fromType)
        {
            // Check that a conversion is actually necessary.
            if (fromType == PrimitiveType.Int32 || fromType == PrimitiveType.UInt32 || fromType == PrimitiveType.Bool)
            {
                return;
            }

            switch (fromType)
            {
            case PrimitiveType.Undefined:
            case PrimitiveType.Null:
                // Converting from undefined or null produces 0.
                generator.Pop();
                generator.LoadInt32(0);
                break;

            case PrimitiveType.Number:
                // Converting from a number produces the following:
                // Any number between -2147483648 and +2147483647 -> itself
                // Any number smaller than -2147483648 -> -2147483648
                // Any number larger than +2147483647 -> +2147483647
                // NaN -> 0

                // bool isPositiveInfinity = input > 2147483647.0
                var isPositiveInfinity = generator.CreateTemporaryVariable(typeof(bool));
                generator.Duplicate();
                generator.LoadDouble(2147483647.0);
                generator.CompareGreaterThan();
                generator.StoreVariable(isPositiveInfinity);

                // bool notNaN = input == input
                var notNaN = generator.CreateTemporaryVariable(typeof(bool));
                generator.Duplicate();
                generator.Duplicate();
                generator.CompareEqual();
                generator.StoreVariable(notNaN);

                // input = (int)input
                // Infinity -> -2147483648
                // -Infinity -> -2147483648
                // NaN -> -2147483648
                generator.ConvertToInteger();

                // input = input & -((int)notNaN)
                generator.LoadVariable(notNaN);
                generator.Negate();
                generator.BitwiseAnd();

                // input = input - (int)isPositiveInfinity
                generator.LoadVariable(isPositiveInfinity);
                generator.Subtract();

                // The temporary variables are no longer needed.
                generator.ReleaseTemporaryVariable(notNaN);
                generator.ReleaseTemporaryVariable(isPositiveInfinity);
                break;

            case PrimitiveType.String:
            case PrimitiveType.ConcatenatedString:
            case PrimitiveType.Any:
            case PrimitiveType.Object:
                // Otherwise, fall back to calling TypeConverter.ToInteger()
                generator.Call(ReflectionHelpers.TypeConverter_ToInteger);
                break;

            default:
                throw new NotImplementedException(string.Format("Unsupported primitive type: {0}", fromType));
            }
        }
        /// <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);
        }
예제 #23
0
        /// <summary>
        /// Generates code that initializes the variable and function declarations.
        /// </summary>
        /// <param name="generator"> The generator to output the CIL to. </param>
        /// <param name="optimizationInfo"> Information about any optimizations that should be performed. </param>
        internal virtual void GenerateDeclarations(ILGenerator generator, OptimizationInfo optimizationInfo)
        {
            // Initialize the declared variables and functions.
            foreach (var variable in this.variables.Values)
            {
                // When a scope is reused, i.e. with an eval(), do not reinitialize the variables.
                if (variable.Initialized == true)
                    continue;

                if (variable.ValueAtTopOfScope != null)
                {
                    // Emit the initialization code.
                    if (this is ObjectScope)
                    {
                        // Determine the property attributes.
                        var attributes = Library.PropertyAttributes.Enumerable;
                        if (variable.Writable == true)
                            attributes |= Library.PropertyAttributes.Writable;
                        if (variable.Deletable == true)
                            attributes |= Library.PropertyAttributes.Configurable;

                        // bool DefineProperty(string propertyName, PropertyDescriptor descriptor, bool throwOnError)
                        EmitHelpers.LoadScope(generator);
                        generator.CastClass(typeof(ObjectScope));
                        generator.Call(ReflectionHelpers.ObjectScope_ScopeObject);
                        generator.LoadString(variable.Name);
                        variable.ValueAtTopOfScope.GenerateCode(generator, optimizationInfo);
                        EmitConversion.Convert(generator, variable.ValueAtTopOfScope.ResultType, PrimitiveType.Any, optimizationInfo);
                        generator.LoadInt32((int)attributes);
                        generator.NewObject(ReflectionHelpers.PropertyDescriptor_Constructor2);
                        generator.LoadBoolean(false);
                        generator.Call(ReflectionHelpers.ObjectInstance_DefineProperty);
                        generator.Pop();
                    }
                    else
                    {
                        variable.ValueAtTopOfScope.GenerateCode(generator, optimizationInfo);
                        var name = new NameExpression(this, variable.Name);
                        name.GenerateSet(generator, optimizationInfo, variable.ValueAtTopOfScope.ResultType, false);
                    }

                    // Mark the variable as having been initialized.
                    variable.Initialized = true;
                }
            }
        }
예제 #24
0
        /// <summary>
        /// Pops the value on the stack, converts it from one type to another, then pushes the
        /// result onto the stack.  Undefined is converted to the given default value.
        /// </summary>
        /// <param name="generator"> The IL generator. </param>
        /// <param name="fromType"> The type to convert from. </param>
        /// <param name="targetParameter"> The type to convert to and the default value, if there is one. </param>
        private static void EmitTypeConversion(ILGenerator generator, Type fromType, BinderArgument argument)
        {
            // Emit either the default value if there is one, otherwise emit "undefined".
            if (argument.HasDefaultValue)
            {
                // Check if the input value is undefined.
                var elseClause = generator.CreateLabel();
                generator.Duplicate();
                generator.BranchIfNull(elseClause);
                generator.Duplicate();
                generator.LoadField(ReflectionHelpers.Undefined_Value);
                generator.CompareEqual();
                generator.BranchIfTrue(elseClause);

                // Convert as per normal.
                EmitTypeConversion(generator, fromType, argument.Type);

                // Jump to the end.
                var endOfIf = generator.CreateLabel();
                generator.Branch(endOfIf);
                generator.DefineLabelPosition(elseClause);

                // Pop the existing value and emit the default value.
                generator.Pop();
                EmitUndefined(generator, argument);

                // Define the end of the block.
                generator.DefineLabelPosition(endOfIf);
            }
            else
            {
                // Convert as per normal.
                EmitTypeConversion(generator, fromType, argument.Type);
            }
        }
예제 #25
0
        /// <summary>
        /// Deletes the reference and pushes <c>true</c> if the delete succeeded, or <c>false</c>
        /// if the delete failed.
        /// </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 void GenerateDelete(ILGenerator generator, OptimizationInfo optimizationInfo)
        {
            // Deleting a variable is not allowed in strict mode.
            if (optimizationInfo.StrictMode == true)
                throw new JavaScriptException(optimizationInfo.Engine, ErrorType.SyntaxError, string.Format("Cannot delete {0} because deleting a variable or argument is not allowed in strict mode", this.Name), optimizationInfo.SourceSpan.StartLine, optimizationInfo.Source.Path, optimizationInfo.FunctionName);

            var endOfDelete = generator.CreateLabel();
            var scope = this.Scope;
            ILLocalVariable scopeVariable = generator.CreateTemporaryVariable(typeof(Scope));
            EmitHelpers.LoadScope(generator);
            generator.StoreVariable(scopeVariable);
            do
            {
                if (scope is DeclarativeScope)
                {
                    var variable = scope.GetDeclaredVariable(this.Name);
                    if (variable != null)
                    {
                        // The variable is known at compile-time.
                        if (variable.Deletable == false)
                        {
                            // The variable cannot be deleted - return false.
                            generator.LoadBoolean(false);
                        }
                        else
                        {
                            // The variable can be deleted (it was declared inside an eval()).
                            // Delete the variable.
                            generator.LoadVariable(scopeVariable);
                            generator.CastClass(typeof(DeclarativeScope));
                            generator.LoadString(this.Name);
                            generator.Call(ReflectionHelpers.Scope_Delete);
                        }
                        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) {
                            generator.LoadVariable(scopeVariable);
                            generator.CastClass(typeof(DeclarativeScope));
                            generator.LoadString(this.Name);
                            generator.Call(ReflectionHelpers.Scope_HasValue);
                            var hasValueClause = generator.CreateLabel();
                            generator.BranchIfFalse(hasValueClause);

                            // If the variable does exist, return true.
                            generator.LoadVariable(scopeVariable);
                            generator.CastClass(typeof(DeclarativeScope));
                            generator.LoadString(this.Name);
                            generator.Call(ReflectionHelpers.Scope_Delete);
                            generator.Branch(endOfDelete);

                            // }
                            generator.DefineLabelPosition(hasValueClause);
                        }
                    }
                }
                else
                {
                    // Check if the property exists by calling scope.ScopeObject.HasProperty(propertyName)
                    generator.LoadVariable(scopeVariable);
                    generator.CastClass(typeof(ObjectScope));
                    generator.Call(ReflectionHelpers.ObjectScope_ScopeObject);
                    generator.Duplicate();
                    generator.LoadString(this.Name);
                    generator.Call(ReflectionHelpers.ObjectInstance_HasProperty);

                    // Jump past the delete if the property doesn't exist.
                    var endOfExistsCheck = generator.CreateLabel();
                    generator.BranchIfFalse(endOfExistsCheck);

                    // Call scope.ScopeObject.Delete(key, false)
                    generator.LoadString(this.Name);
                    generator.LoadBoolean(false);
                    generator.Call(ReflectionHelpers.ObjectInstance_Delete);
                    generator.Branch(endOfDelete);

                    generator.DefineLabelPosition(endOfExistsCheck);
                    generator.Pop();

                    // If the name is not defined, return true.
                    if (scope.ParentScope == null)
                    {
                        generator.LoadBoolean(true);
                    }
                }

                // Try the parent scope.
                if (scope.ParentScope != null && scope.ExistsAtRuntime == true)
                {
                    generator.LoadVariable(scopeVariable);
                    generator.Call(ReflectionHelpers.Scope_ParentScope);
                    generator.StoreVariable(scopeVariable);
                }
                scope = scope.ParentScope;

            } while (scope != null);

            // Release the temporary variable.
            generator.ReleaseTemporaryVariable(scopeVariable);

            // Define a label at the end.
            generator.DefineLabelPosition(endOfDelete);

            // Delete obviously has side-effects so we evaluate the return value then pop it from
            // the stack.
            //if (optimizationInfo.SuppressReturnValue == true)
            //    generator.Pop();
        }
예제 #26
0
        /// <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();
        }
예제 #27
0
        /// <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.LoadNull();
                generator.BranchIfNotEqual(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 if (this.Value is List<Expression>)
            {
                // Construct an array literal.
                var arrayLiteral = (List<Expression>)this.Value;

                // Operands for ArrayConstructor.New() are: an ArrayConstructor instance (ArrayConstructor), an array (object[])
                // ArrayConstructor
                EmitHelpers.LoadScriptEngine(generator);
                generator.Call(ReflectionHelpers.ScriptEngine_Array);

                // object[]
                generator.LoadInt32(arrayLiteral.Count);
                generator.NewArray(typeof(object));
                for (int i = 0; i < arrayLiteral.Count; i ++)
                {
                    // Operands for StoreArrayElement() are: an array (object[]), index (int), value (object).
                    // Array
                    generator.Duplicate();

                    // Index
                    generator.LoadInt32(i);

                    // Value
                    var elementExpression = arrayLiteral[i];
                    if (elementExpression == null)
                        generator.LoadNull();
                    else
                    {
                        elementExpression.GenerateCode(generator, optimizationInfo);
                        EmitConversion.ToAny(generator, elementExpression.ResultType);
                    }

                    // Store the element value.
                    generator.StoreArrayElement(typeof(object));
                }

                // ArrayConstructor.New(object[])
                generator.Call(ReflectionHelpers.Array_New);
            }
            else if (this.Value is Dictionary<string, object>)
            {
                // This is an object literal.
                var properties = (Dictionary<string, object>)this.Value;

                // Create a new object.
                EmitHelpers.LoadScriptEngine(generator);
                generator.Call(ReflectionHelpers.ScriptEngine_Object);
                generator.Call(ReflectionHelpers.Object_Construct);

                foreach (var keyValuePair in properties)
                {
                    string propertyName = keyValuePair.Key;
                    object propertyValue = keyValuePair.Value;

                    generator.Duplicate();
                    generator.LoadString(propertyName);
                    if (propertyValue is Expression)
                    {
                        // Add a new property to the object.
                        var dataPropertyValue = (Expression)propertyValue;
                        dataPropertyValue.GenerateCode(generator, optimizationInfo);
                        // Support the inferred function displayName property.
                        if (dataPropertyValue is FunctionExpression)
                            ((FunctionExpression)dataPropertyValue).GenerateDisplayName(generator, optimizationInfo, propertyName, false);
                        EmitConversion.ToAny(generator, dataPropertyValue.ResultType);
                        generator.LoadBoolean(optimizationInfo.StrictMode);
                        generator.Call(ReflectionHelpers.ObjectInstance_SetPropertyValue_String);
                    }
                    else if (propertyValue is Parser.ObjectLiteralAccessor)
                    {
                        // Add a new getter/setter to the object.
                        var accessorValue = (Parser.ObjectLiteralAccessor)propertyValue;
                        if (accessorValue.Getter != null)
                        {
                            accessorValue.Getter.GenerateCode(generator, optimizationInfo);
                            // Support the inferred function displayName property.
                            accessorValue.Getter.GenerateDisplayName(generator, optimizationInfo, "get " + propertyName, true);
                            EmitConversion.ToAny(generator, accessorValue.Getter.ResultType);
                        }
                        else
                            generator.LoadNull();
                        if (accessorValue.Setter != null)
                        {
                            accessorValue.Setter.GenerateCode(generator, optimizationInfo);
                            // Support the inferred function displayName property.
                            accessorValue.Setter.GenerateDisplayName(generator, optimizationInfo, "set " + propertyName, true);
                            EmitConversion.ToAny(generator, accessorValue.Setter.ResultType);
                        }
                        else
                            generator.LoadNull();
                        generator.LoadInt32((int)Library.PropertyAttributes.FullAccess);
                        generator.NewObject(ReflectionHelpers.PropertyDescriptor_Constructor3);
                        generator.LoadBoolean(false);
                        generator.Call(ReflectionHelpers.ObjectInstance_DefineProperty);
                        generator.Pop();
                    }
                    else
                        throw new InvalidOperationException("Invalid property value type in object literal.");
                }
            }
            else
                throw new NotImplementedException("Unknown literal type.");
        }
예제 #28
0
        /// <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;
            }

            // Check if this is a super() call.
            if (this.Target is SuperExpression)
            {
                // executionContext.CallSuperClass(arguments)
                EmitHelpers.LoadExecutionContext(generator);
                GenerateArgumentsArray(generator, optimizationInfo);
                generator.Call(ReflectionHelpers.ExecutionContext_CallSuperClass);
                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. "my_func()").
                this.Target.GenerateCode(generator, optimizationInfo);
                EmitConversion.ToAny(generator, this.Target.ResultType);
            }

            // Check the object really is a function - if not, throw an exception.
            generator.Duplicate();
            generator.IsInstance(typeof(FunctionInstance));
            var endOfTypeCheck = generator.CreateLabel();

            generator.BranchIfTrue(endOfTypeCheck);

            // Throw an nicely formatted exception.
            generator.Pop();
            EmitHelpers.EmitThrow(generator, ErrorType.TypeError, string.Format("'{0}' is not a function", this.Target.ToString()), optimizationInfo);
            generator.DefineLabelPosition(endOfTypeCheck);

            // Pass in the path, function name and line.
            generator.ReinterpretCast(typeof(FunctionInstance));
            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()").
                //    If we are inside a with() block, then there is an implicit 'this' value,
                //    otherwise 'this' is undefined.
                Scope.GenerateReference(generator, optimizationInfo);
                generator.Call(ReflectionHelpers.RuntimeScope_ImplicitThis);
            }
            else if (this.Target is MemberAccessExpression targetMemberAccessExpression)
            {
                // 2. The function is a member access expression (e.g. "Math.cos()").
                //    In this case this = Math.
                //    Unless it's a super call like super.blah().
                if (targetMemberAccessExpression.Base is SuperExpression)
                {
                    EmitHelpers.LoadThis(generator);
                }
                else
                {
                    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);
            }
        }
예제 #29
0
        /// <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));
            }
        }
예제 #30
0
        /// <summary>
        /// Pops the value on the stack, converts it to a string, then pushes the result onto the
        /// stack.
        /// </summary>
        /// <param name="generator"> The IL generator. </param>
        /// <param name="fromType"> The type to convert from. </param>
        public static void ToString(ILGenerator generator, PrimitiveType fromType)
        {
            // Check that a conversion is actually necessary.
            if (fromType == PrimitiveType.String)
                return;

            switch (fromType)
            {
                case PrimitiveType.Undefined:
                    // Converting from undefined produces "undefined".
                    generator.Pop();
                    generator.LoadString("undefined");
                    break;

                case PrimitiveType.Null:
                    // Converting from null produces "null".
                    generator.Pop();
                    generator.LoadString("null");
                    break;

                case PrimitiveType.Bool:
                    // Converting from a boolean produces "false" if the boolean is false, or "true" if the boolean is true.
                    var elseClause = generator.CreateLabel();
                    var endOfIf = generator.CreateLabel();
                    generator.BranchIfFalse(elseClause);
                    generator.LoadString("true");
                    generator.Branch(endOfIf);
                    generator.DefineLabelPosition(elseClause);
                    generator.LoadString("false");
                    generator.DefineLabelPosition(endOfIf);
                    break;

                case PrimitiveType.ConcatenatedString:
                    generator.Call(ReflectionHelpers.ConcatenatedString_ToString);
                    break;

                case PrimitiveType.Int32:
                case PrimitiveType.UInt32:
                case PrimitiveType.Number:
                case PrimitiveType.Any:
                case PrimitiveType.Object:
                    // Otherwise, fall back to calling TypeConverter.ToString()
                    if (PrimitiveTypeUtilities.IsValueType(fromType))
                        generator.Box(fromType);
                    generator.Call(ReflectionHelpers.TypeConverter_ToString);
                    break;

                default:
                    throw new NotImplementedException(string.Format("Unsupported primitive type: {0}", fromType));
            }
        }
예제 #31
0
        /// <summary>
        /// Pops the value on the stack, converts it from an object to the given type, then pushes
        /// the result onto the stack.
        /// </summary>
        /// <param name="generator"> The IL generator. </param>
        /// <param name="toType"> The type to convert to. </param>
        /// <param name="convertToAddress"> <c>true</c> if the value is intended for use as an
        /// instance pointer; <c>false</c> otherwise. </param>
        internal static void EmitConversionToType(ILGenerator generator, Type toType, bool convertToAddress)
        {
            // Convert Null.Value to null if the target type is a reference type.
            ILLabel endOfNullCheck = null;
            if (toType.IsValueType == false)
            {
                var startOfElse = generator.CreateLabel();
                endOfNullCheck = generator.CreateLabel();
                generator.Duplicate();
                EmitHelpers.EmitNull(generator);
                generator.BranchIfNotEqual(startOfElse);
                generator.Pop();
                generator.LoadNull();
                generator.Branch(endOfNullCheck);
                generator.DefineLabelPosition(startOfElse);
            }

            switch (Type.GetTypeCode(toType))
            {
                case TypeCode.Boolean:
                    EmitConversion.ToBool(generator, PrimitiveType.Any);
                    break;
                case TypeCode.Byte:
                    EmitConversion.ToInt32(generator, PrimitiveType.Any);
                    break;
                case TypeCode.Char:
                    EmitConversion.ToString(generator, PrimitiveType.Any);
                    generator.Duplicate();
                    generator.Call(ReflectionHelpers.String_Length);
                    generator.LoadInt32(1);
                    var endOfCharCheck = generator.CreateLabel();
                    generator.BranchIfEqual(endOfCharCheck);
                    EmitHelpers.EmitThrow(generator, "TypeError", "Cannot convert string to char - the string must be exactly one character long");
                    generator.DefineLabelPosition(endOfCharCheck);
                    generator.LoadInt32(0);
                    generator.Call(ReflectionHelpers.String_GetChars);
                    break;
                case TypeCode.DBNull:
                    throw new NotSupportedException("DBNull is not a supported parameter type.");
                case TypeCode.Decimal:
                    EmitConversion.ToNumber(generator, PrimitiveType.Any);
                    generator.NewObject(ReflectionHelpers.Decimal_Constructor_Double);
                    break;
                case TypeCode.Double:
                    EmitConversion.ToNumber(generator, PrimitiveType.Any);
                    break;
                case TypeCode.Empty:
                    throw new NotSupportedException("Empty is not a supported return type.");
                case TypeCode.Int16:
                    EmitConversion.ToInt32(generator, PrimitiveType.Any);
                    break;
                case TypeCode.Int32:
                    EmitConversion.ToInt32(generator, PrimitiveType.Any);
                    break;
                case TypeCode.Int64:
                    EmitConversion.ToNumber(generator, PrimitiveType.Any);
                    generator.ConvertToInt64();
                    break;

                case TypeCode.DateTime:
                case TypeCode.Object:
                    // Check if the type must be unwrapped.
                    generator.Duplicate();
                    generator.IsInstance(typeof(Jurassic.Library.ClrInstanceWrapper));
                    var endOfUnwrapCheck = generator.CreateLabel();
                    generator.BranchIfFalse(endOfUnwrapCheck);

                    // Unwrap the wrapped instance.
                    generator.Call(ReflectionHelpers.ClrInstanceWrapper_GetWrappedInstance);
                    generator.DefineLabelPosition(endOfUnwrapCheck);

                    // Value types must be unboxed.
                    if (toType.IsValueType == true)
                    {
                        if (convertToAddress == true)
                            // Unbox.
                            generator.Unbox(toType);
                        else
                            // Unbox and copy to the stack.
                            generator.UnboxAny(toType);

                        //// Calling methods on value required the address of the value type, not the value type itself.
                        //if (argument.Source == BinderArgumentSource.ThisValue && argument.Type.IsValueType == true)
                        //{
                        //    var temp = generator.CreateTemporaryVariable(argument.Type);
                        //    generator.StoreVariable(temp);
                        //    generator.LoadAddressOfVariable(temp);
                        //    generator.ReleaseTemporaryVariable(temp);
                        //}
                    }


                    break;

                case TypeCode.SByte:
                    EmitConversion.ToInt32(generator, PrimitiveType.Any);
                    break;
                case TypeCode.Single:
                    EmitConversion.ToNumber(generator, PrimitiveType.Any);
                    break;
                case TypeCode.String:
                    EmitConversion.ToString(generator, PrimitiveType.Any);
                    break;
                case TypeCode.UInt16:
                    EmitConversion.ToInt32(generator, PrimitiveType.Any);
                    break;
                case TypeCode.UInt32:
                    EmitConversion.ToUInt32(generator, PrimitiveType.Any);
                    break;
                case TypeCode.UInt64:
                    EmitConversion.ToNumber(generator, PrimitiveType.Any);
                    generator.ConvertToUnsignedInt64();
                    break;
            }

            // Label the end of the null check.
            if (toType.IsValueType == false)
                generator.DefineLabelPosition(endOfNullCheck);
        }
        /// <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)
        {
            // Special-case the delete operator.
            if (this.OperatorType == OperatorType.Delete)
            {
                GenerateDelete(generator, optimizationInfo);
                return;
            }

            // If a return value is not expected, generate only the side-effects.

            /*if (optimizationInfo.SuppressReturnValue == true)
             * {
             *  this.GenerateSideEffects(generator, optimizationInfo);
             *  return;
             * }*/

            // Special-case the typeof operator.
            if (this.OperatorType == OperatorType.Typeof)
            {
                GenerateTypeof(generator, optimizationInfo);
                return;
            }

            // Load the operand onto the stack.
            this.Operand.GenerateCode(generator, optimizationInfo);

            // Convert the operand to the correct type.
            switch (this.OperatorType)
            {
            case OperatorType.Plus:
            case OperatorType.Minus:
                EmitConversion.ToNumber(generator, this.Operand.ResultType);
                break;

            case OperatorType.BitwiseNot:
                EmitConversion.ToInt32(generator, this.Operand.ResultType);
                break;

            case OperatorType.LogicalNot:
                EmitConversion.ToBool(generator, this.Operand.ResultType);
                break;
            }

            // Apply the operator.
            switch (this.OperatorType)
            {
            case OperatorType.Plus:
                break;

            case OperatorType.Minus:
                generator.Negate();
                break;

            case OperatorType.BitwiseNot:
                generator.BitwiseNot();
                break;

            case OperatorType.LogicalNot:
                generator.LoadBoolean(false);
                generator.CompareEqual();
                break;

            case OperatorType.Void:
                generator.Pop();
                EmitHelpers.EmitUndefined(generator);
                break;

            default:
                throw new NotImplementedException(string.Format("Unsupported operator {0}", this.OperatorType));
            }
        }
        /// <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.LoadNull();
                generator.BranchIfNotEqual(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 if (this.Value is List <Expression> )
            {
                // Construct an array literal.
                var arrayLiteral = (List <Expression>) this.Value;

                // Operands for ArrayConstructor.New() are: an ArrayConstructor instance (ArrayConstructor), an array (object[])
                // ArrayConstructor
                EmitHelpers.LoadScriptEngine(generator);
                generator.Call(ReflectionHelpers.ScriptEngine_Array);

                // object[]
                generator.LoadInt32(arrayLiteral.Count);
                generator.NewArray(typeof(object));
                for (int i = 0; i < arrayLiteral.Count; i++)
                {
                    // Operands for StoreArrayElement() are: an array (object[]), index (int), value (object).
                    // Array
                    generator.Duplicate();

                    // Index
                    generator.LoadInt32(i);

                    // Value
                    var elementExpression = arrayLiteral[i];
                    if (elementExpression == null)
                    {
                        generator.LoadNull();
                    }
                    else
                    {
                        elementExpression.GenerateCode(generator, optimizationInfo);
                        EmitConversion.ToAny(generator, elementExpression.ResultType);
                    }

                    // Store the element value.
                    generator.StoreArrayElement(typeof(object));
                }

                // ArrayConstructor.New(object[])
                generator.Call(ReflectionHelpers.Array_New);
            }
            else if (this.Value is Dictionary <string, object> )
            {
                // This is an object literal.
                var properties = (Dictionary <string, object>) this.Value;

                // Create a new object.
                EmitHelpers.LoadScriptEngine(generator);
                generator.Call(ReflectionHelpers.ScriptEngine_Object);
                generator.Call(ReflectionHelpers.Object_Construct);

                foreach (var keyValuePair in properties)
                {
                    string propertyName  = keyValuePair.Key;
                    object propertyValue = keyValuePair.Value;

                    generator.Duplicate();
                    generator.LoadString(propertyName);
                    if (propertyValue is Expression)
                    {
                        // Add a new property to the object.
                        var dataPropertyValue = (Expression)propertyValue;
                        dataPropertyValue.GenerateCode(generator, optimizationInfo);
                        // Support the inferred function displayName property.
                        if (dataPropertyValue is FunctionExpression)
                        {
                            ((FunctionExpression)dataPropertyValue).GenerateDisplayName(generator, optimizationInfo, propertyName, false);
                        }
                        EmitConversion.ToAny(generator, dataPropertyValue.ResultType);
                        generator.LoadBoolean(optimizationInfo.StrictMode);
                        generator.Call(ReflectionHelpers.ObjectInstance_SetPropertyValue_String);
                    }
                    else if (propertyValue is Parser.ObjectLiteralAccessor)
                    {
                        // Add a new getter/setter to the object.
                        var accessorValue = (Parser.ObjectLiteralAccessor)propertyValue;
                        if (accessorValue.Getter != null)
                        {
                            accessorValue.Getter.GenerateCode(generator, optimizationInfo);
                            // Support the inferred function displayName property.
                            accessorValue.Getter.GenerateDisplayName(generator, optimizationInfo, "get " + propertyName, true);
                            EmitConversion.ToAny(generator, accessorValue.Getter.ResultType);
                        }
                        else
                        {
                            generator.LoadNull();
                        }
                        if (accessorValue.Setter != null)
                        {
                            accessorValue.Setter.GenerateCode(generator, optimizationInfo);
                            // Support the inferred function displayName property.
                            accessorValue.Setter.GenerateDisplayName(generator, optimizationInfo, "set " + propertyName, true);
                            EmitConversion.ToAny(generator, accessorValue.Setter.ResultType);
                        }
                        else
                        {
                            generator.LoadNull();
                        }
                        generator.LoadInt32((int)Library.PropertyAttributes.FullAccess);
                        generator.NewObject(ReflectionHelpers.PropertyDescriptor_Constructor3);
                        generator.LoadBoolean(false);
                        generator.Call(ReflectionHelpers.ObjectInstance_DefineProperty);
                        generator.Pop();
                    }
                    else
                    {
                        throw new InvalidOperationException("Invalid property value type in object literal.");
                    }
                }
            }
            else
            {
                throw new NotImplementedException("Unknown literal type.");
            }
        }
        /// <summary>
        /// Generates CIL for the logical operators.
        /// </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 GenerateLogical(ILGenerator generator, OptimizationInfo optimizationInfo)
        {
            // Get the statically-determined types of the left and right operands.
            PrimitiveType leftType = this.Left.ResultType;
            PrimitiveType rightType = this.Right.ResultType;

            // Load the left-hand side operand.
            this.Left.GenerateCode(generator, optimizationInfo);

            // Make sure the output type is consistant.
            if (leftType != rightType)
            {
                if (PrimitiveTypeUtilities.IsNumeric(leftType) == true && PrimitiveTypeUtilities.IsNumeric(rightType) == true)
                {
                    EmitConversion.ToNumber(generator, leftType);
                    leftType = PrimitiveType.Number;
                }
                else
                {
                    EmitConversion.ToAny(generator, leftType);
                    leftType = PrimitiveType.Any;
                }
            }

            // Duplicate and convert to a Boolean.
            generator.Duplicate();
            EmitConversion.ToBool(generator, leftType);

            // Stack contains "left, (bool)left"
            var endOfIf = generator.CreateLabel();
            if (this.OperatorType == OperatorType.LogicalAnd)
                generator.BranchIfFalse(endOfIf);
            else
                generator.BranchIfTrue(endOfIf);

            // Stack contains "left".  Load the right-hand side operand.
            generator.Pop();
            this.Right.GenerateCode(generator, optimizationInfo);

            // Make sure the output type is consistant.
            if (leftType != rightType)
            {
                if (PrimitiveTypeUtilities.IsNumeric(leftType) == true && PrimitiveTypeUtilities.IsNumeric(rightType) == true)
                    EmitConversion.ToNumber(generator, rightType);
                else
                    EmitConversion.ToAny(generator, rightType);
            }

            // Define the label used above.
            generator.DefineLabelPosition(endOfIf);
        }
예제 #35
0
        /// <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);
        }
예제 #36
0
        /// <summary>
        /// Pops the value on the stack, converts it to an integer, then pushes the integer result
        /// onto the stack.  Large numbers wrap (i.e. 4294967296 -> 0).
        /// </summary>
        /// <param name="generator"> The IL generator. </param>
        /// <param name="fromType"> The type to convert from. </param>
        public static void ToInt32(ILGenerator generator, PrimitiveType fromType)
        {
            // Check that a conversion is actually necessary.
            if (fromType == PrimitiveType.Int32 || fromType == PrimitiveType.UInt32 || fromType == PrimitiveType.Bool)
                return;

            switch (fromType)
            {
                case PrimitiveType.Undefined:
                case PrimitiveType.Null:
                    // Converting from undefined or null produces 0.
                    generator.Pop();
                    generator.LoadInt32(0);
                    break;

                case PrimitiveType.Number:
                    // Converting from a number produces the number mod 4294967296.  NaN produces 0.
                    generator.ConvertToUnsignedInteger();
                    break;

                case PrimitiveType.String:
                case PrimitiveType.ConcatenatedString:
                case PrimitiveType.Any:
                case PrimitiveType.Object:
                    // Otherwise, fall back to calling TypeConverter.ToInt32()
                    generator.Call(ReflectionHelpers.TypeConverter_ToInt32);
                    break;

                default:
                    throw new NotImplementedException(string.Format("Unsupported primitive type: {0}", fromType));
            }
        }
예제 #37
0
        /// <summary>
        /// Pops the value on the stack, converts it to a boolean, then pushes the boolean result
        /// onto the stack.
        /// </summary>
        /// <param name="generator"> The IL generator. </param>
        /// <param name="fromType"> The type to convert from. </param>
        public static void ToBool(ILGenerator generator, PrimitiveType fromType)
        {
            // Check that a conversion is actually necessary.
            if (fromType == PrimitiveType.Bool)
            {
                return;
            }

            switch (fromType)
            {
            case PrimitiveType.Undefined:
            case PrimitiveType.Null:
                // Converting from undefined or null produces false.
                generator.Pop();
                generator.LoadInt32(0);
                break;

            case PrimitiveType.Int32:
            case PrimitiveType.UInt32:
                // Converting from an integer produces true if the integer is non-zero.
                generator.LoadInt32(0);
                generator.CompareGreaterThanUnsigned();
                break;

            case PrimitiveType.Number:
                // Converting from a number produces true if the number is non-zero and not NaN.
                var temp = generator.CreateTemporaryVariable(fromType);
                generator.StoreVariable(temp);

                // input != 0
                generator.LoadVariable(temp);
                generator.LoadDouble(0.0);
                generator.CompareEqual();
                generator.LoadInt32(0);
                generator.CompareEqual();

                // input == input
                generator.LoadVariable(temp);
                generator.Duplicate();
                generator.CompareEqual();

                // &&
                generator.CompareEqual();

                // The temporary variable is no longer needed.
                generator.ReleaseTemporaryVariable(temp);
                break;

            case PrimitiveType.String:
                // Converting from a string produces true if the string is not empty.
                generator.Call(ReflectionHelpers.String_Length);
                generator.LoadInt32(0);
                generator.CompareGreaterThan();
                break;

            case PrimitiveType.ConcatenatedString:
                // Converting from a string produces true if the string is not empty.
                generator.Call(ReflectionHelpers.ConcatenatedString_Length);
                generator.LoadInt32(0);
                generator.CompareGreaterThan();
                break;

            case PrimitiveType.Any:
            case PrimitiveType.Object:
                // Otherwise, fall back to calling TypeConverter.ToBoolean()
                generator.Call(ReflectionHelpers.TypeConverter_ToBoolean);
                break;

            default:
                throw new NotImplementedException(string.Format("Unsupported primitive type: {0}", fromType));
            }
        }
예제 #38
0
        /// <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();
            }
        }
예제 #39
0
        /// <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)
        {
            // Determine the methods that have the correct number of arguments.
            var candidateMethods = new List <BinderMethod>();

            foreach (var candidateMethod in this.targetMethods)
            {
                if (candidateMethod.IsArgumentCountCompatible(argumentCount) == true)
                {
                    candidateMethods.Add(candidateMethod);
                }
            }

            // Zero candidates means no overload had the correct number of arguments.
            if (candidateMethods.Count == 0)
            {
                EmitHelpers.EmitThrow(generator, ErrorType.TypeError, string.Format("No overload for method '{0}' takes {1} arguments", this.Name, argumentCount));
                EmitHelpers.EmitDefaultValue(generator, PrimitiveType.Any);
                generator.Complete();
                return;
            }

            // Select the method to call at run time.
            generator.LoadInt32(candidateMethods.Count);
            generator.NewArray(typeof(RuntimeMethodHandle));
            for (int i = 0; i < candidateMethods.Count; i++)
            {
                generator.Duplicate();
                generator.LoadInt32(i);
                generator.LoadToken(candidateMethods[i]);
                generator.StoreArrayElement(typeof(RuntimeMethodHandle));
            }
            generator.LoadArgument(0);
            generator.LoadArgument(1);
            generator.LoadArgument(2);
            generator.Call(ReflectionHelpers.BinderUtilities_ResolveOverloads);

            var endOfMethod = generator.CreateLabel();

            for (int i = 0; i < candidateMethods.Count; i++)
            {
                // Check if this is the selected method.
                ILLabel endOfIf = null;
                if (i < candidateMethods.Count - 1)
                {
                    generator.Duplicate();
                    generator.LoadInt32(i);
                    endOfIf = generator.CreateLabel();
                    generator.BranchIfNotEqual(endOfIf);
                }
                generator.Pop();

                var targetMethod = candidateMethods[i];

                // Convert the arguments.
                foreach (var argument in targetMethod.GenerateArguments(generator, argumentCount))
                {
                    // Load the input parameter value.
                    switch (argument.Source)
                    {
                    case BinderArgumentSource.ScriptEngine:
                        generator.LoadArgument(0);
                        break;

                    case BinderArgumentSource.ThisValue:
                        generator.LoadArgument(1);
                        break;

                    case BinderArgumentSource.InputParameter:
                        generator.LoadArgument(2);
                        generator.LoadInt32(argument.InputParameterIndex);
                        generator.LoadArrayElement(typeof(object));
                        break;
                    }

                    // Convert to the target type.
                    EmitConversionToType(generator, argument.Type, convertToAddress: argument.Source == BinderArgumentSource.ThisValue);
                }

                // Call the target method.
                targetMethod.GenerateCall(generator);

                // Convert the return value.
                if (targetMethod.ReturnType == typeof(void))
                {
                    EmitHelpers.EmitUndefined(generator);
                }
                else
                {
                    EmitConversionToObject(generator, targetMethod.ReturnType);
                }

                // Branch to the end of the method if this was the selected method.
                if (endOfIf != null)
                {
                    generator.Branch(endOfMethod);
                    generator.DefineLabelPosition(endOfIf);
                }
            }

            generator.DefineLabelPosition(endOfMethod);
            generator.Complete();
        }
예제 #40
0
        /// <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)
        {
            // Method signature: object FunctionDelegate(Compiler.Scope scope, object thisObject, Library.FunctionInstance functionObject, object[] arguments)

            // Initialize the scope (note: the initial scope for a function is always declarative).
            this.InitialScope.GenerateScopeCreation(generator, optimizationInfo);

            // In ES3 the "this" value must be an object.  See 10.4.3 in the spec.
            if (this.StrictMode == false && this.MethodOptimizationHints.HasThis == true)
            {
                // if (thisObject == null || thisObject == Null.Value || thisObject == Undefined.Value)
                EmitHelpers.LoadThis(generator);
                generator.LoadNull();
                generator.CompareEqual();
                EmitHelpers.LoadThis(generator);
                EmitHelpers.EmitNull(generator);
                generator.CompareEqual();
                generator.BitwiseOr();
                EmitHelpers.LoadThis(generator);
                EmitHelpers.EmitUndefined(generator);
                generator.CompareEqual();
                generator.BitwiseOr();

                // {
                var startOfFalse = generator.CreateLabel();
                generator.BranchIfFalse(startOfFalse);

                // thisObject = engine.Global;
                EmitHelpers.LoadScriptEngine(generator);
                generator.Call(ReflectionHelpers.ScriptEngine_Global);

                // } else {
                var endOfIf = generator.CreateLabel();
                generator.Branch(endOfIf);
                generator.DefineLabelPosition(startOfFalse);

                // thisObject = TypeConverter.ToObject(thisObject);
                EmitHelpers.LoadThis(generator);
                EmitConversion.ToObject(generator, PrimitiveType.Any, optimizationInfo);

                // }
                generator.DefineLabelPosition(endOfIf);
                EmitHelpers.StoreThis(generator);
            }

            // Transfer the function name into the scope.
            if (string.IsNullOrEmpty(this.Name) == false &&
                (this.DeclarationType != FunctionDeclarationType.Getter && this.DeclarationType != FunctionDeclarationType.Setter) &&
                this.Arguments.Any(a => a.Name == this.Name) == false &&
                optimizationInfo.MethodOptimizationHints.HasVariable(this.Name))
            {
                EmitHelpers.LoadFunction(generator);
                var functionName = new NameExpression(this.InitialScope, this.Name);
                functionName.GenerateSet(generator, optimizationInfo, PrimitiveType.Any, false);
            }

            // Transfer the arguments object into the scope.
            if (this.MethodOptimizationHints.HasArguments == true && this.Arguments.Any(a => a.Name == "arguments") == false)
            {
                // prototype
                EmitHelpers.LoadScriptEngine(generator);
                generator.Call(ReflectionHelpers.ScriptEngine_Object);
                generator.Call(ReflectionHelpers.FunctionInstance_InstancePrototype);
                // callee
                EmitHelpers.LoadFunction(generator);
                generator.CastClass(typeof(Library.UserDefinedFunction));
                // scope
                EmitHelpers.LoadScope(generator);
                generator.CastClass(typeof(DeclarativeScope));
                // argumentValues
                EmitHelpers.LoadArgumentsArray(generator);
                generator.NewObject(ReflectionHelpers.Arguments_Constructor);
                var arguments = new NameExpression(this.InitialScope, "arguments");
                arguments.GenerateSet(generator, optimizationInfo, PrimitiveType.Any, false);
            }

            // Transfer the argument values into the scope.
            // Note: the arguments array can be smaller than expected.
            if (this.Arguments.Count > 0)
            {
                for (int i = 0; i < this.Arguments.Count; i++)
                {
                    // Check if a duplicate argument name exists.
                    bool duplicate = false;
                    for (int j = i + 1; j < this.Arguments.Count; j++)
                    {
                        if (this.Arguments[i].Name == this.Arguments[j].Name)
                        {
                            duplicate = true;
                            break;
                        }
                    }
                    if (duplicate == true)
                    {
                        continue;
                    }

                    var loadDefaultValue = generator.CreateLabel();
                    var storeValue       = generator.CreateLabel();

                    // Check if an array element exists.
                    EmitHelpers.LoadArgumentsArray(generator);
                    generator.LoadArrayLength();
                    generator.LoadInt32(i);
                    generator.BranchIfLessThanOrEqual(loadDefaultValue);

                    // Load the parameter value from the parameters array.
                    EmitHelpers.LoadArgumentsArray(generator);
                    generator.LoadInt32(i);
                    generator.LoadArrayElement(typeof(object));

                    if (this.Arguments[i].DefaultValue == null)
                    {
                        // Branch to the part where it stores the value.
                        generator.Branch(storeValue);

                        // Load undefined.
                        generator.DefineLabelPosition(loadDefaultValue);
                        EmitHelpers.EmitUndefined(generator);
                    }
                    else
                    {
                        // Check if it's undefined.
                        generator.Duplicate();
                        EmitHelpers.EmitUndefined(generator);
                        generator.BranchIfNotEqual(storeValue);
                        generator.Pop();

                        // Load the default value.
                        generator.DefineLabelPosition(loadDefaultValue);
                        this.Arguments[i].DefaultValue.GenerateCode(generator, optimizationInfo);
                        EmitConversion.ToAny(generator, this.Arguments[i].DefaultValue.ResultType);
                    }

                    // Store the value in the scope.
                    generator.DefineLabelPosition(storeValue);
                    var argument = new NameExpression(this.InitialScope, this.Arguments[i].Name);
                    argument.GenerateSet(generator, optimizationInfo, PrimitiveType.Any, false);
                }
            }

            // Initialize any declarations.
            this.InitialScope.GenerateDeclarations(generator, optimizationInfo);

            // Generate code for the body of the function.
            this.AbstractSyntaxTree.GenerateCode(generator, optimizationInfo);

            // Define the return target - this is where the return statement jumps to.
            // ReturnTarget can be null if there were no return statements.
            if (optimizationInfo.ReturnTarget != null)
            {
                generator.DefineLabelPosition(optimizationInfo.ReturnTarget);
            }

            // Load the return value.  If the variable is null, there were no return statements.
            if (optimizationInfo.ReturnVariable != null)
            {
                // Return the value stored in the variable.  Will be null if execution hits the end
                // of the function without encountering any return statements.
                generator.LoadVariable(optimizationInfo.ReturnVariable);
            }
            else
            {
                // There were no return statements - return null.
                generator.LoadNull();
            }
        }
예제 #41
0
        /// <summary>
        /// Pops the value on the stack, converts it from an object to the given type, then pushes
        /// the result onto the stack.
        /// </summary>
        /// <param name="generator"> The IL generator. </param>
        /// <param name="toType"> The type to convert to. </param>
        /// <param name="convertToAddress"> <c>true</c> if the value is intended for use as an
        /// instance pointer; <c>false</c> otherwise. </param>
        internal static void EmitConversionToType(ILGenerator generator, Type toType, bool convertToAddress)
        {
            // Convert Null.Value to null if the target type is a reference type.
            ILLabel endOfNullCheck = null;

            if (toType.IsValueType == false)
            {
                var startOfElse = generator.CreateLabel();
                endOfNullCheck = generator.CreateLabel();
                generator.Duplicate();
                EmitHelpers.EmitNull(generator);
                generator.BranchIfNotEqual(startOfElse);
                generator.Pop();
                generator.LoadNull();
                generator.Branch(endOfNullCheck);
                generator.DefineLabelPosition(startOfElse);
            }

            switch (Type.GetTypeCode(toType))
            {
            case TypeCode.Boolean:
                EmitConversion.ToBool(generator, PrimitiveType.Any);
                break;

            case TypeCode.Byte:
                EmitConversion.ToInt32(generator, PrimitiveType.Any);
                break;

            case TypeCode.Char:
                EmitConversion.ToString(generator, PrimitiveType.Any);
                generator.Duplicate();
                generator.Call(ReflectionHelpers.String_Length);
                generator.LoadInt32(1);
                var endOfCharCheck = generator.CreateLabel();
                generator.BranchIfEqual(endOfCharCheck);
                EmitHelpers.EmitThrow(generator, ErrorType.TypeError, "Cannot convert string to char - the string must be exactly one character long");
                generator.DefineLabelPosition(endOfCharCheck);
                generator.LoadInt32(0);
                generator.Call(ReflectionHelpers.String_GetChars);
                break;

            case TypeCode.DBNull:
                throw new NotSupportedException("DBNull is not a supported parameter type.");

            case TypeCode.Decimal:
                EmitConversion.ToNumber(generator, PrimitiveType.Any);
                generator.NewObject(ReflectionHelpers.Decimal_Constructor_Double);
                break;

            case TypeCode.Double:
                EmitConversion.ToNumber(generator, PrimitiveType.Any);
                break;

            case TypeCode.Empty:
                throw new NotSupportedException("Empty is not a supported return type.");

            case TypeCode.Int16:
                EmitConversion.ToInt32(generator, PrimitiveType.Any);
                break;

            case TypeCode.Int32:
                EmitConversion.ToInt32(generator, PrimitiveType.Any);
                break;

            case TypeCode.Int64:
                EmitConversion.ToNumber(generator, PrimitiveType.Any);
                generator.ConvertToInt64();
                break;

            case TypeCode.DateTime:
            case TypeCode.Object:
                // Check if the type must be unwrapped.
                generator.Duplicate();
                generator.IsInstance(typeof(Jurassic.Library.ClrInstanceWrapper));
                var endOfUnwrapCheck = generator.CreateLabel();
                generator.BranchIfFalse(endOfUnwrapCheck);

                // Unwrap the wrapped instance.
                generator.Call(ReflectionHelpers.ClrInstanceWrapper_GetWrappedInstance);
                generator.DefineLabelPosition(endOfUnwrapCheck);

                // Value types must be unboxed.
                if (toType.IsValueType == true)
                {
                    if (convertToAddress == true)
                    {
                        // Unbox.
                        generator.Unbox(toType);
                    }
                    else
                    {
                        // Unbox and copy to the stack.
                        generator.UnboxAny(toType);
                    }

                    //// Calling methods on value required the address of the value type, not the value type itself.
                    //if (argument.Source == BinderArgumentSource.ThisValue && argument.Type.IsValueType == true)
                    //{
                    //    var temp = generator.CreateTemporaryVariable(argument.Type);
                    //    generator.StoreVariable(temp);
                    //    generator.LoadAddressOfVariable(temp);
                    //    generator.ReleaseTemporaryVariable(temp);
                    //}
                }


                break;

            case TypeCode.SByte:
                EmitConversion.ToInt32(generator, PrimitiveType.Any);
                break;

            case TypeCode.Single:
                EmitConversion.ToNumber(generator, PrimitiveType.Any);
                break;

            case TypeCode.String:
                EmitConversion.ToString(generator, PrimitiveType.Any);
                break;

            case TypeCode.UInt16:
                EmitConversion.ToInt32(generator, PrimitiveType.Any);
                break;

            case TypeCode.UInt32:
                EmitConversion.ToUInt32(generator, PrimitiveType.Any);
                break;

            case TypeCode.UInt64:
                EmitConversion.ToNumber(generator, PrimitiveType.Any);
                generator.ConvertToUnsignedInt64();
                break;
            }

            // Label the end of the null check.
            if (toType.IsValueType == false)
            {
                generator.DefineLabelPosition(endOfNullCheck);
            }
        }
예제 #42
0
        /// <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 (scope.ParentScope == null)
                    {
                        // Optimization: if this is the global scope, use hidden classes to
                        // optimize variable access.

                        // Global variable modification
                        // ----------------------------
                        // __object_cacheKey = null;
                        // __object_property_cachedIndex = 0;
                        // ...
                        // if (__object_cacheKey != object.InlineCacheKey)
                        //     object.InlineSetPropertyValueIfExists("property", value, strictMode, out __object_property_cachedIndex, out __object_cacheKey)
                        // else
                        //     object.InlinePropertyValues[__object_property_cachedIndex] = value;

                        // 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);

                        // xxx = object.InlineSetPropertyValueIfExists("property", value, strictMode, out __object_property_cachedIndex, out __object_cacheKey)
                        generator.LoadVariable(objectInstance);
                        generator.LoadString(this.Name);
                        generator.LoadVariable(value);
                        generator.LoadBoolean(optimizationInfo.StrictMode);
                        generator.LoadAddressOfVariable(cachedIndex);
                        generator.LoadAddressOfVariable(cacheKey);
                        if (throwIfUnresolvable == false)
                        {
                            // Set the property value unconditionally.
                            generator.Call(ReflectionHelpers.ObjectInstance_InlineSetPropertyValue);
                        }
                        else
                        {
                            // Set the property value if the property exists.
                            generator.Call(ReflectionHelpers.ObjectInstance_InlineSetPropertyValueIfExists);

                            // The return value is true if the property was defined, and false if it wasn't.
                            generator.BranchIfTrue(endOfSet);
                        }

                        var endOfIf = generator.CreateLabel();
                        generator.Branch(endOfIf);

                        // else
                        generator.DefineLabelPosition(elseClause);

                        // object.InlinePropertyValues[__object_property_cachedIndex] = value;
                        generator.LoadVariable(objectInstance);
                        generator.Call(ReflectionHelpers.ObjectInstance_InlinePropertyValues);
                        generator.LoadVariable(cachedIndex);
                        generator.LoadVariable(value);
                        generator.StoreArrayElement(typeof(object));
                        generator.Branch(endOfSet);

                        // End of the if statement
                        generator.DefineLabelPosition(endOfIf);

                    }
                    else
                    {
                        // Slow route.

                        if (scopeVariable == null)
                            EmitHelpers.LoadScope(generator);
                        else
                            generator.LoadVariable(scopeVariable);
                        generator.CastClass(typeof(ObjectScope));
                        generator.Call(ReflectionHelpers.ObjectScope_ScopeObject);
                        generator.LoadString(this.Name);
                        generator.LoadVariable(value);
                        generator.LoadBoolean(optimizationInfo.StrictMode);

                        if (scope.ParentScope == null && throwIfUnresolvable == false)
                        {
                            // Set the property value unconditionally.
                            generator.Call(ReflectionHelpers.ObjectInstance_SetPropertyValue_Object);
                        }
                        else
                        {
                            // 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);
        }
예제 #43
0
        /// <summary>
        /// Deletes the reference and pushes <c>true</c> if the delete succeeded, or <c>false</c>
        /// if the delete failed.
        /// </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 void GenerateDelete(ILGenerator generator, OptimizationInfo optimizationInfo)
        {
            // Deleting a variable is not allowed in strict mode.
            if (optimizationInfo.StrictMode == true)
            {
                throw new JavaScriptException(optimizationInfo.Engine, ErrorType.SyntaxError, string.Format("Cannot delete {0} because deleting a variable or argument is not allowed in strict mode", this.Name), optimizationInfo.SourceSpan.StartLine, optimizationInfo.Source.Path, optimizationInfo.FunctionName);
            }

            var             endOfDelete   = generator.CreateLabel();
            var             scope         = this.Scope;
            ILLocalVariable scopeVariable = generator.CreateTemporaryVariable(typeof(Scope));

            EmitHelpers.LoadScope(generator);
            generator.StoreVariable(scopeVariable);
            do
            {
                if (scope is DeclarativeScope)
                {
                    var variable = scope.GetDeclaredVariable(this.Name);
                    if (variable != null)
                    {
                        // The variable is known at compile-time.
                        if (variable.Deletable == false)
                        {
                            // The variable cannot be deleted - return false.
                            generator.LoadBoolean(false);
                        }
                        else
                        {
                            // The variable can be deleted (it was declared inside an eval()).
                            // Delete the variable.
                            generator.LoadVariable(scopeVariable);
                            generator.CastClass(typeof(DeclarativeScope));
                            generator.LoadString(this.Name);
                            generator.Call(ReflectionHelpers.Scope_Delete);
                        }
                        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) {
                            generator.LoadVariable(scopeVariable);
                            generator.CastClass(typeof(DeclarativeScope));
                            generator.LoadString(this.Name);
                            generator.Call(ReflectionHelpers.Scope_HasValue);
                            var hasValueClause = generator.CreateLabel();
                            generator.BranchIfFalse(hasValueClause);

                            // If the variable does exist, return true.
                            generator.LoadVariable(scopeVariable);
                            generator.CastClass(typeof(DeclarativeScope));
                            generator.LoadString(this.Name);
                            generator.Call(ReflectionHelpers.Scope_Delete);
                            generator.Branch(endOfDelete);

                            // }
                            generator.DefineLabelPosition(hasValueClause);
                        }
                    }
                }
                else
                {
                    // Check if the property exists by calling scope.ScopeObject.HasProperty(propertyName)
                    generator.LoadVariable(scopeVariable);
                    generator.CastClass(typeof(ObjectScope));
                    generator.Call(ReflectionHelpers.ObjectScope_ScopeObject);
                    generator.Duplicate();
                    generator.LoadString(this.Name);
                    generator.Call(ReflectionHelpers.ObjectInstance_HasProperty);

                    // Jump past the delete if the property doesn't exist.
                    var endOfExistsCheck = generator.CreateLabel();
                    generator.BranchIfFalse(endOfExistsCheck);

                    // Call scope.ScopeObject.Delete(key, false)
                    generator.LoadString(this.Name);
                    generator.LoadBoolean(false);
                    generator.Call(ReflectionHelpers.ObjectInstance_Delete);
                    generator.Branch(endOfDelete);

                    generator.DefineLabelPosition(endOfExistsCheck);
                    generator.Pop();

                    // If the name is not defined, return true.
                    if (scope.ParentScope == null)
                    {
                        generator.LoadBoolean(true);
                    }
                }

                // Try the parent scope.
                if (scope.ParentScope != null && scope.ExistsAtRuntime == true)
                {
                    generator.LoadVariable(scopeVariable);
                    generator.Call(ReflectionHelpers.Scope_ParentScope);
                    generator.StoreVariable(scopeVariable);
                }
                scope = scope.ParentScope;
            } while (scope != null);

            // Release the temporary variable.
            generator.ReleaseTemporaryVariable(scopeVariable);

            // Define a label at the end.
            generator.DefineLabelPosition(endOfDelete);

            // Delete obviously has side-effects so we evaluate the return value then pop it from
            // the stack.
            //if (optimizationInfo.SuppressReturnValue == true)
            //    generator.Pop();
        }
예제 #44
0
        /// <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);
            }
        }
예제 #45
0
        /// <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();
        }
예제 #46
0
        /// <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)
        {
            // Determine the methods that have the correct number of arguments.
            var candidateMethods = new List<BinderMethod>();
            foreach (var candidateMethod in this.targetMethods)
            {
                if (candidateMethod.IsArgumentCountCompatible(argumentCount) == true)
                    candidateMethods.Add(candidateMethod);
            }

            // Zero candidates means no overload had the correct number of arguments.
            if (candidateMethods.Count == 0)
            {
                EmitHelpers.EmitThrow(generator, "TypeError", string.Format("No overload for method '{0}' takes {1} arguments", this.Name, argumentCount));
                EmitHelpers.EmitDefaultValue(generator, PrimitiveType.Any);
                generator.Complete();
                return;
            }

            // Select the method to call at run time.
            generator.LoadInt32(candidateMethods.Count);
            generator.NewArray(typeof(RuntimeMethodHandle));
            for (int i = 0; i < candidateMethods.Count; i ++)
            {
                generator.Duplicate();
                generator.LoadInt32(i);
                generator.LoadToken(candidateMethods[i]);
                generator.StoreArrayElement(typeof(RuntimeMethodHandle));
            }
            generator.LoadArgument(0);
            generator.LoadArgument(1);
            generator.LoadArgument(2);
            generator.Call(ReflectionHelpers.BinderUtilities_ResolveOverloads);

            var endOfMethod = generator.CreateLabel();
            for (int i = 0; i < candidateMethods.Count; i++)
            {
                // Check if this is the selected method.
                ILLabel endOfIf = null;
                if (i < candidateMethods.Count - 1)
                {
                    generator.Duplicate();
                    generator.LoadInt32(i);
                    endOfIf = generator.CreateLabel();
                    generator.BranchIfNotEqual(endOfIf);
                }
                generator.Pop();

                var targetMethod = candidateMethods[i];

                // Convert the arguments.
                foreach (var argument in targetMethod.GenerateArguments(generator, argumentCount))
                {
                    // Load the input parameter value.
                    switch (argument.Source)
                    {
                        case BinderArgumentSource.ScriptEngine:
                            generator.LoadArgument(0);
                            break;
                        case BinderArgumentSource.ThisValue:
                            generator.LoadArgument(1);
                            break;
                        case BinderArgumentSource.InputParameter:
                            generator.LoadArgument(2);
                            generator.LoadInt32(argument.InputParameterIndex);
                            generator.LoadArrayElement(typeof(object));
                            break;
                    }

                    // Convert to the target type.
                    EmitConversionToType(generator, argument.Type, convertToAddress: argument.Source == BinderArgumentSource.ThisValue);
                }

                // Call the target method.
                targetMethod.GenerateCall(generator);

                // Convert the return value.
                if (targetMethod.ReturnType == typeof(void))
                    EmitHelpers.EmitUndefined(generator);
                else
                    EmitConversionToObject(generator, targetMethod.ReturnType);

                // Branch to the end of the method if this was the selected method.
                if (endOfIf != null)
                {
                    generator.Branch(endOfMethod);
                    generator.DefineLabelPosition(endOfIf);
                }
            }

            generator.DefineLabelPosition(endOfMethod);
            generator.Complete();
        }
        /// <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)
        {
            // Method signature: object FunctionDelegate(Compiler.Scope scope, object thisObject, Library.FunctionInstance functionObject, object[] arguments)

            // Initialize the scope (note: the initial scope for a function is always declarative).
            this.BaseScope.GenerateScopeCreation(generator, optimizationInfo);

            // In ES3 the "this" value must be an object.  See 10.4.3 in the spec.
            if (this.StrictMode == false && this.MethodOptimizationHints.HasThis == true)
            {
                // context.ConvertThisToObject();
                EmitHelpers.LoadExecutionContext(generator);
                generator.Call(ReflectionHelpers.ExecutionContext_ConvertThisToObject);
            }

            // Transfer the function name into the scope.
            if (Name.HasStaticName && !Name.IsGetter && !Name.IsSetter &&
                this.Arguments.Any(a => a.Name == Name.StaticName) == false &&
                optimizationInfo.MethodOptimizationHints.HasVariable(Name.StaticName))
            {
                EmitHelpers.LoadFunction(generator);
                var functionName = new NameExpression(this.BaseScope, Name.StaticName);
                functionName.GenerateSet(generator, optimizationInfo, PrimitiveType.Any);
            }

            // Transfer the arguments object into the scope.
            if (this.MethodOptimizationHints.HasArguments == true && this.Arguments.Any(a => a.Name == "arguments") == false)
            {
                // executionContext.CreateArgumentsInstance(object[] arguments)
                EmitHelpers.LoadExecutionContext(generator);
                this.BaseScope.GenerateReference(generator, optimizationInfo);
                EmitHelpers.LoadArgumentsArray(generator);
                generator.Call(ReflectionHelpers.ExecutionContext_CreateArgumentsInstance);
                var arguments = new NameExpression(this.BaseScope, "arguments");
                arguments.GenerateSet(generator, optimizationInfo, PrimitiveType.Any);
            }

            // Transfer the argument values into the scope.
            // Note: the arguments array can be smaller than expected.
            if (this.Arguments.Count > 0)
            {
                for (int i = 0; i < this.Arguments.Count; i++)
                {
                    // Check if a duplicate argument name exists.
                    bool duplicate = false;
                    for (int j = i + 1; j < this.Arguments.Count; j++)
                    {
                        if (this.Arguments[i].Name == this.Arguments[j].Name)
                        {
                            duplicate = true;
                            break;
                        }
                    }
                    if (duplicate == true)
                    {
                        continue;
                    }

                    var loadDefaultValue = generator.CreateLabel();
                    var storeValue       = generator.CreateLabel();

                    // Check if an array element exists.
                    EmitHelpers.LoadArgumentsArray(generator);
                    generator.LoadArrayLength();
                    generator.LoadInt32(i);
                    generator.BranchIfLessThanOrEqual(loadDefaultValue);

                    // Load the parameter value from the parameters array.
                    EmitHelpers.LoadArgumentsArray(generator);
                    generator.LoadInt32(i);
                    generator.LoadArrayElement(typeof(object));

                    if (this.Arguments[i].DefaultValue == null)
                    {
                        // Branch to the part where it stores the value.
                        generator.Branch(storeValue);

                        // Load undefined.
                        generator.DefineLabelPosition(loadDefaultValue);
                        EmitHelpers.EmitUndefined(generator);
                        generator.ReinterpretCast(typeof(object));
                    }
                    else
                    {
                        // Check if it's undefined.
                        generator.Duplicate();
                        EmitHelpers.EmitUndefined(generator);
                        generator.ReinterpretCast(typeof(object));
                        generator.BranchIfNotEqual(storeValue);
                        generator.Pop();

                        // Load the default value.
                        generator.DefineLabelPosition(loadDefaultValue);
                        this.Arguments[i].DefaultValue.GenerateCode(generator, optimizationInfo);
                        EmitConversion.ToAny(generator, this.Arguments[i].DefaultValue.ResultType);
                    }

                    // Store the value in the scope.
                    generator.DefineLabelPosition(storeValue);
                    var argument = new NameExpression(this.BaseScope, this.Arguments[i].Name);
                    argument.GenerateSet(generator, optimizationInfo, PrimitiveType.Any);
                }
            }

            // Initialize any declarations.
            this.BaseScope.GenerateHoistedDeclarations(generator, optimizationInfo);

            // Generate code for the body of the function.
            this.AbstractSyntaxTree.GenerateCode(generator, optimizationInfo);

            // Define the return target - this is where the return statement jumps to.
            // ReturnTarget can be null if there were no return statements.
            if (optimizationInfo.ReturnTarget != null)
            {
                generator.DefineLabelPosition(optimizationInfo.ReturnTarget);
            }

            // Load the return value.  If the variable is null, there were no return statements.
            if (optimizationInfo.ReturnVariable != null)
            {
                // Return the value stored in the variable.  Will be null if execution hits the end
                // of the function without encountering any return statements.
                generator.LoadVariable(optimizationInfo.ReturnVariable);
            }
            else
            {
                // There were no return statements - return null.
                generator.LoadNull();
            }
        }
예제 #48
0
        /// <summary>
        /// Pops the value on the stack, converts it to a boolean, then pushes the boolean result
        /// onto the stack.
        /// </summary>
        /// <param name="generator"> The IL generator. </param>
        /// <param name="fromType"> The type to convert from. </param>
        public static void ToBool(ILGenerator generator, PrimitiveType fromType)
        {
            // Check that a conversion is actually necessary.
            if (fromType == PrimitiveType.Bool)
                return;

            switch (fromType)
            {
                case PrimitiveType.Undefined:
                case PrimitiveType.Null:
                    // Converting from undefined or null produces false.
                    generator.Pop();
                    generator.LoadInt32(0);
                    break;

                case PrimitiveType.Int32:
                case PrimitiveType.UInt32:
                    // Converting from an integer produces true if the integer is non-zero.
                    generator.LoadInt32(0);
                    generator.CompareGreaterThanUnsigned();
                    break;

                case PrimitiveType.Number:
                    // Converting from a number produces true if the number is non-zero and not NaN.
                    var temp = generator.CreateTemporaryVariable(fromType);
                    generator.StoreVariable(temp);

                    // input != 0
                    generator.LoadVariable(temp);
                    generator.LoadDouble(0.0);
                    generator.CompareEqual();
                    generator.LoadInt32(0);
                    generator.CompareEqual();

                    // input == input
                    generator.LoadVariable(temp);
                    generator.Duplicate();
                    generator.CompareEqual();

                    // &&
                    generator.CompareEqual();

                    // The temporary variable is no longer needed.
                    generator.ReleaseTemporaryVariable(temp);
                    break;

                case PrimitiveType.String:
                    // Converting from a string produces true if the string is not empty.
                    generator.Call(ReflectionHelpers.String_Length);
                    generator.LoadInt32(0);
                    generator.CompareGreaterThan();
                    break;

                case PrimitiveType.ConcatenatedString:
                    // Converting from a string produces true if the string is not empty.
                    generator.Call(ReflectionHelpers.ConcatenatedString_Length);
                    generator.LoadInt32(0);
                    generator.CompareGreaterThan();
                    break;

                case PrimitiveType.Any:
                case PrimitiveType.Object:
                    // Otherwise, fall back to calling TypeConverter.ToBoolean()
                    generator.Call(ReflectionHelpers.TypeConverter_ToBoolean);
                    break;

                default:
                    throw new NotImplementedException(string.Format("Unsupported primitive type: {0}", fromType));
            }
        }
예제 #49
0
        /// <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();
        }
예제 #50
0
        /// <summary>
        /// Pops the value on the stack, converts it to a double, then pushes the double result
        /// onto the stack.
        /// </summary>
        /// <param name="generator"> The IL generator. </param>
        /// <param name="fromType"> The type to convert from. </param>
        public static void ToNumber(ILGenerator generator, PrimitiveType fromType)
        {
            // Check that a conversion is actually necessary.
            if (fromType == PrimitiveType.Number)
                return;

            switch (fromType)
            {
                case PrimitiveType.Undefined:
                    // Converting from undefined produces NaN.
                    generator.Pop();
                    generator.LoadDouble(double.NaN);
                    break;

                case PrimitiveType.Null:
                    // Converting from null produces 0.
                    generator.Pop();
                    generator.LoadDouble(0.0);
                    break;

                case PrimitiveType.Bool:
                    // Converting from a boolean produces 0 if the boolean is false, or 1 if the boolean is true.
                    generator.ConvertToDouble();
                    break;

                case PrimitiveType.Int32:
                    // Converting from int32 produces the same number.
                    generator.ConvertToDouble();
                    break;

                case PrimitiveType.UInt32:
                    // Converting from a number produces the following:
                    generator.ConvertUnsignedToDouble();
                    break;

                case PrimitiveType.String:
                case PrimitiveType.ConcatenatedString:
                case PrimitiveType.Any:
                case PrimitiveType.Object:
                    // Otherwise, fall back to calling TypeConverter.ToNumber()
                    generator.Call(ReflectionHelpers.TypeConverter_ToNumber);
                    break;

                default:
                    throw new NotImplementedException(string.Format("Unsupported primitive type: {0}", fromType));
            }
        }
예제 #51
0
        /// <summary>
        /// Generates code to push the "this" value for a function call.
        /// </summary>
        /// <param name="generator"> The generator to output the CIL to. </param>
        public void GenerateThis(ILGenerator generator)
        {
            // Optimization: if there are no with scopes, simply emit undefined.
            bool scopeChainHasWithScope = false;
            var scope = this.Scope;
            do
            {
                if (scope is ObjectScope && ((ObjectScope)scope).ProvidesImplicitThisValue == true)
                {
                    scopeChainHasWithScope = true;
                    break;
                }
                scope = scope.ParentScope;
            } while (scope != null);

            if (scopeChainHasWithScope == false)
            {
                // No with scopes in the scope chain, use undefined as the "this" value.
                EmitHelpers.EmitUndefined(generator);
                return;
            }

            var end = generator.CreateLabel();

            scope = this.Scope;
            ILLocalVariable scopeVariable = generator.CreateTemporaryVariable(typeof(Scope));
            EmitHelpers.LoadScope(generator);
            generator.StoreVariable(scopeVariable);

            do
            {
                if (scope is DeclarativeScope)
                {
                    if (scope.HasDeclaredVariable(this.Name))
                    {
                        // The variable exists but declarative scopes always produce undefined for
                        // the "this" value.
                        EmitHelpers.EmitUndefined(generator);
                        break;
                    }
                }
                else
                {
                    var objectScope = (ObjectScope)scope;

                    // Check if the property exists by calling scope.ScopeObject.HasProperty(propertyName)
                    if (objectScope.ProvidesImplicitThisValue == false)
                        EmitHelpers.EmitUndefined(generator);
                    generator.LoadVariable(scopeVariable);
                    generator.CastClass(typeof(ObjectScope));
                    generator.Call(ReflectionHelpers.ObjectScope_ScopeObject);
                    if (objectScope.ProvidesImplicitThisValue == true)
                        generator.Duplicate();
                    generator.LoadString(this.Name);
                    generator.Call(ReflectionHelpers.ObjectInstance_HasProperty);
                    generator.BranchIfTrue(end);
                    generator.Pop();

                    // If the name is not defined, use undefined for the "this" value.
                    if (scope.ParentScope == null)
                    {
                        EmitHelpers.EmitUndefined(generator);
                    }
                }

                // Try the parent scope.
                if (scope.ParentScope != null && scope.ExistsAtRuntime == true)
                {
                    generator.LoadVariable(scopeVariable);
                    generator.Call(ReflectionHelpers.Scope_ParentScope);
                    generator.StoreVariable(scopeVariable);
                }
                scope = scope.ParentScope;

            } while (scope != null);

            // Release the temporary variable.
            generator.ReleaseTemporaryVariable(scopeVariable);

            // Define a label at the end.
            generator.DefineLabelPosition(end);
        }
예제 #52
0
        /// <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)
        {
            // Special-case the delete operator.
            if (this.OperatorType == OperatorType.Delete)
            {
                GenerateDelete(generator, optimizationInfo);
                return;
            }

            // If a return value is not expected, generate only the side-effects.
            /*if (optimizationInfo.SuppressReturnValue == true)
            {
                this.GenerateSideEffects(generator, optimizationInfo);
                return;
            }*/

            // Special-case the typeof operator.
            if (this.OperatorType == OperatorType.Typeof)
            {
                GenerateTypeof(generator, optimizationInfo);
                return;
            }

            // Load the operand onto the stack.
            this.Operand.GenerateCode(generator, optimizationInfo);

            // Convert the operand to the correct type.
            switch (this.OperatorType)
            {
                case OperatorType.Plus:
                case OperatorType.Minus:
                    EmitConversion.ToNumber(generator, this.Operand.ResultType);
                    break;

                case OperatorType.BitwiseNot:
                    EmitConversion.ToInt32(generator, this.Operand.ResultType);
                    break;

                case OperatorType.LogicalNot:
                    EmitConversion.ToBool(generator, this.Operand.ResultType);
                    break;
            }

            // Apply the operator.
            switch (this.OperatorType)
            {
                case OperatorType.Plus:
                    break;

                case OperatorType.Minus:
                    generator.Negate();
                    break;

                case OperatorType.BitwiseNot:
                    generator.BitwiseNot();
                    break;

                case OperatorType.LogicalNot:
                    generator.LoadBoolean(false);
                    generator.CompareEqual();
                    break;

                case OperatorType.Void:
                    generator.Pop();
                    EmitHelpers.EmitUndefined(generator);
                    break;

                default:
                    throw new NotImplementedException(string.Format("Unsupported operator {0}", this.OperatorType));
            }
        }
예제 #53
0
        /// <summary>
        /// Generates CIL for the delete 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>
        private void GenerateDelete(ILGenerator generator, OptimizationInfo optimizationInfo)
        {
            // Attempting to delete something that isn't a reference returns true but otherwise does nothing.
            if ((this.Operand is IReferenceExpression) == false)
            {
                // Make sure the expression is evaluated.
                this.Operand.GenerateCode(generator, optimizationInfo);

                // Discard the result and return true.
                generator.Pop();
                generator.LoadBoolean(true);
                return;
            }

            // The operand is a variable or property reference.
            ((IReferenceExpression)this.Operand).GenerateDelete(generator, optimizationInfo);
        }
예제 #54
0
        /// <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);
        }