public static void EqualsAssemblyQualifiedName_Match_True()
        {
            var comparer = new TypeComparer(TypeMatchStrategy.AssemblyQualifiedName);
            var x        = typeof(string);
            var y        = typeof(string);
            var actual   = comparer.Equals(x, y);

            Assert.True(actual);
        }
        public static void EqualsStringsNamespaceAndName_NoMatch_False()
        {
            var comparer = new TypeComparer(TypeMatchStrategy.NamespaceAndName);
            var x        = typeof(string);
            var y        = typeof(Type);
            var actual   = comparer.Equals(x.Namespace, x.Name, x.AssemblyQualifiedName, y.Namespace, y.Name, y.AssemblyQualifiedName);

            Assert.False(actual);
        }
        public static void EqualsDescriptionAssemblyQualifiedName_NoMatch_False()
        {
            var comparer = new TypeComparer(TypeMatchStrategy.AssemblyQualifiedName);
            var x        = typeof(string);
            var y        = typeof(Type);
            var actual   = comparer.Equals(x.ToTypeDescription(), y.ToTypeDescription());

            Assert.False(actual);
        }
        public static void EqualsDescriptionNamespaceAndName_Match_True()
        {
            var comparer = new TypeComparer(TypeMatchStrategy.NamespaceAndName);
            var x        = typeof(string);
            var y        = typeof(string);
            var actual   = comparer.Equals(x.ToTypeDescription(), y.ToTypeDescription());

            Assert.True(actual);
        }
        private bool EqualsPropertyToField(PropertyInfo x, FieldInfo y)
        {
            var xMapping = x.GetCustomAttribute <MappingAttribute>(inherit: false);
            var yMapping = y.GetCustomAttribute <MappingAttribute>(inherit: false);

            var xName = xMapping != null ? xMapping.Uri : x.Name;
            var yName = yMapping != null ? yMapping.Uri : y.Name;

            return(xName == yName && TypeComparer.Equals(x.PropertyType, y.FieldType) && x.GetIndexParameters().Length == 0);
        }
        public ConstructorInfo GetConstructor(IEnumerable<Type> argTypes)
        {
            var comparer = new TypeComparer();

            return _type.GetConstructors(BINDING_FLAGS)
                         .Where(c => comparer.Equals(c.GetParameters()
                                                      .Select(p => p.ParameterType), argTypes))
                         .Union(_type.GetConstructors(BINDING_FLAGS)
                                      .Where(c => comparer.Assignable(c.GetParameters()
                                                                       .Select(p => p.ParameterType), argTypes)))
                         .FirstOrDefault();
        }
        public PropertyInfo GetIndexer(IEnumerable<Type> argTypes)
        {
            var matches = _type.GetProperties(BINDING_FLAGS)
                              .Where(p => p.Name.Equals("Item"));

            var comparer = new TypeComparer();

            return matches.Where(m => comparer.Equals(m.GetIndexParameters()
                                                       .Select(p => p.ParameterType), argTypes))
                          .Union(matches.Where(m => comparer.Assignable(m.GetIndexParameters()
                                                                         .Select(p => p.ParameterType), argTypes)))
                          .FirstOrDefault();
        }
        protected override bool EqualsProperty(PropertyInfo x, PropertyInfo y)
        {
            if (!base.EqualsProperty(x, y))
            {
                var xMapping = x.GetCustomAttribute <MappingAttribute>(inherit: false);
                var yMapping = y.GetCustomAttribute <MappingAttribute>(inherit: false);

                var xName = xMapping != null ? xMapping.Uri : x.Name;
                var yName = yMapping != null ? yMapping.Uri : y.Name;

                return(xName == yName && TypeComparer.Equals(x.PropertyType, y.PropertyType));
            }

            return(true);
        }
        public MethodInfo GetMethod(string methodName, IEnumerable<Type> argTypes)
        {
            var matches = _type.GetMethods(BINDING_FLAGS)
                                .Where(m => m.Name.Equals(methodName))
                                .ToArray();

            var comparer = new TypeComparer();

            return matches.Count() == 1
                   && !argTypes.Any()
                   ? matches.First()
                   : matches.Where(m => comparer.Equals(m.GetParameters()
                                                         .Select(p => p.ParameterType), argTypes))
                            .Union(matches.Where(m => comparer.Assignable(m.GetParameters()
                                                                           .Select(p => p.ParameterType), argTypes)))
                            .FirstOrDefault();
        }
        public static void Equals_Nulls_False()
        {
            var comparer = new TypeComparer(TypeMatchStrategy.NamespaceAndName);

            Assert.False(comparer.Equals((Type)null, (Type)null));
            Assert.False(comparer.Equals((TypeDescription)null, (TypeDescription)null));

            Assert.False(comparer.Equals(typeof(string), (Type)null));
            Assert.False(comparer.Equals((Type)null, typeof(string)));

            Assert.False(comparer.Equals(typeof(string).ToTypeDescription(), (TypeDescription)null));
            Assert.False(comparer.Equals((TypeDescription)null, typeof(string).ToTypeDescription()));
        }
Exemple #11
0
 public IDebuggerField GetField(SR.FieldInfo field)
 {
     return debugger.Dispatcher.UI(() => {
         var comparer = new TypeComparer();
         foreach (var f in GetFields(field.Name, true)) {
             if (comparer.Equals(f.FieldSig.GetFieldType(), field.FieldType))
                 return f;
         }
         return null;
     });
 }
Exemple #12
0
 public IDebuggerEvent GetEvent(SR.EventInfo evt)
 {
     return debugger.Dispatcher.UI(() => {
         var comparer = new TypeComparer();
         foreach (var e in GetEvents(evt.Name, true)) {
             var eventType = e.EventType;
             // EventType currently always returns null
             if (eventType == null)
                 return e;
             if (comparer.Equals(eventType, evt.EventHandlerType))
                 return e;
         }
         return null;
     });
 }
        /// <summary>
        ///     Attempts to construct an instance of <see cref="InjectionDefinition" /> by linking the injection method with the
        ///     injection target (the method to be injected).
        ///     The way how the method is injected is specified by the injection flags. If the injection method does not match the
        ///     criteria set by the injection flags, an exception will be thrown.
        /// </summary>
        /// <param name="injectTarget">The method that will be injected.</param>
        /// <param name="injectMethod">The method which to inject.</param>
        /// <param name="flags">Injection flags that specify what values to pass to the injection method and how to inject it.</param>
        /// <param name="localVarIDs">
        ///     An array of indicies of local variables to pass to the injection method. Used only if
        ///     <see cref="InjectFlags.PassLocals" /> is specified, otherwise ignored.
        /// </param>
        /// <param name="memberReferences">
        ///     An array of class fields from the type the target lies in to pass to the injection
        ///     method. Used only if <see cref="InjectFlags.PassFields" /> is specified, otherwise ignored.
        /// </param>
        public InjectionDefinition(MethodDefinition injectTarget,
                                   MethodDefinition injectMethod,
                                   InjectFlags flags,
                                   int[] localVarIDs = null,
                                   params FieldDefinition[] memberReferences)
        {
            Assert(
            injectMethod.IsStatic,
            $"{nameof(injectMethod)} must be static in order to be used as the injection.");
            Assert(injectMethod.IsPublic, $"{nameof(injectMethod)} must be public.");
            Assert(
            injectMethod.HasBody,
            $"{nameof(injectMethod)} must have a definition in order to be used as the injecton.");

            InjectValues hFlags = flags.ToValues();

            bool isVoid = injectTarget.ReturnType.FullName == "System.Void";

            Assert(
            !hFlags.PassLocals || localVarIDs != null,
            $"Supposed to pass local references, but {nameof(localVarIDs)} is empty");
            Assert(
            !hFlags.PassFields || memberReferences != null,
            $"Supposed to pass member fields, but {nameof(memberReferences)} is empty!");

            int prefixCount = Convert.ToInt32(hFlags.PassTag) + Convert.ToInt32(hFlags.PassInvokingInstance)
                              + Convert.ToInt32(hFlags.ModifyReturn && !isVoid);
            int localsCount = hFlags.PassLocals ? localVarIDs.Length : 0;
            int memberRefCount = (hFlags.PassFields ? memberReferences.Length : 0);
            int paramCount = (hFlags.PassParameters ? injectTarget.Parameters.Count : 0);
            int parameters = injectMethod.Parameters.Count - prefixCount - localsCount - memberRefCount;
            // int parameters = injectMethod.Parameters.Count - prefixCount - localsCount - memberRefCount;
            // PassParameters => 0 < parameters <= injectTarget.Patameters.Count
            // !PassParameters => parameters = 0
            Assert(
            (hFlags.PassParameters && 0 < parameters && parameters <= injectTarget.Parameters.Count
             || !hFlags.PassParameters && parameters == 0),
            //injectMethod.Parameters.Count == prefixCount + localsCount + memberRefCount + paramCount,
            $@"The injection method has a wrong number of parameters! Check that the provided target method, local variables, member references and injection flags add up to the right number of parameters.
Needed parameters: Prefix: {
            prefixCount}, Locals: {localsCount}, Members: {memberRefCount}, Parameters: {
            (hFlags.PassParameters ? "between 1 and " + paramCount : "0")}, TOTAL: {
            (hFlags.PassParameters ? $"between {prefixCount + localsCount + memberRefCount + 1} and " : "")}{
            prefixCount + localsCount + memberRefCount + paramCount}.
Injection has {injectMethod.Parameters.Count
            } parameters.");

            TypeComparer comparer = new TypeComparer();

            if (hFlags.PassTag)
            {
                Assert(
                injectMethod.Parameters[0].ParameterType.FullName == "System.Int32",
                "Supposed to pass a tag, but the provided tag must be of type System.Int32 (int).");
            }

            if (hFlags.PassInvokingInstance)
            {
                Assert(
                !injectTarget.IsStatic,
                "Supposed to pass invoking instance, but the target method is static and thus is not bound to any instances.");
                Assert(
                comparer.Equals(
                injectMethod.Parameters[Convert.ToInt32(hFlags.PassTag)].ParameterType,
                injectTarget.DeclaringType),
                "Supposed to pass invoking instance, but the type of the instance does not match with the type declared in the injection method.");
            }

            if (hFlags.ModifyReturn)
            {
                Assert(
                injectMethod.ReturnType.FullName == "System.Boolean",
                "The injection method must return a boolean in order to alter the return value.");
                Assert(
                isVoid
                || comparer.Equals(
                injectMethod.Parameters[Convert.ToInt32(hFlags.PassTag) + Convert.ToInt32(hFlags.PassInvokingInstance)]
                   .ParameterType,
                new ByReferenceType(injectTarget.ReturnType)),
                "Supposed to modify the return value, but the provided return type does not match with the return type of the target method! Also make sure the type is passed by reference (out/ref).");
            }

            if (hFlags.PassLocals)
            {
                Assert(injectTarget.Body.HasVariables, "The target method does not have any locals.");
                Assert(
                localVarIDs.Length != 0,
                "Supposed to pass method locals, but the IDs of the locals were not specified.");
                Assert(
                localVarIDs.All(i => 0 <= i && i < injectTarget.Body.Variables.Count),
                "Supposed to receive local references, but the provided local variable index/indices do not exist in the target method!");
                Assert(
                injectMethod.Parameters.Slice(prefixCount, localsCount)
                            .Select((p, i) => new {param = p, index = localVarIDs[i]})
                            .All(
                            t =>
                            t.param.ParameterType.IsByReference
                            && comparer.Equals(
                            t.param.ParameterType,
                            new ByReferenceType(injectTarget.Body.Variables[t.index].VariableType))),
                "Supposed to receive local references, but the types between injection method and target method mismatch. Also make sure they are passed by reference (ref/out).");
            }

            if (hFlags.PassFields)
            {
                Assert(!injectTarget.IsStatic, "Cannot pass member references if the injection method is static!");
                Assert(
                memberReferences.Length != 0,
                "Supposed to pass member references, but no members were specified.");
                Assert(
                memberReferences.All(
                m =>
                m.DeclaringType.FullName == injectTarget.DeclaringType.FullName
                && m.DeclaringType.BaseType.FullName == injectTarget.DeclaringType.BaseType.FullName),
                $"The provided member fields do not belong to {injectTarget.DeclaringType}");

                IEnumerable<TypeReference> paramRefs =
                injectMethod.Parameters.Slice(prefixCount + localsCount, memberRefCount).Select(p => p.ParameterType);
                IEnumerable<TypeReference> typeReferences = paramRefs as TypeReference[] ?? paramRefs.ToArray();

                Assert(
                typeReferences.All(p => p.IsByReference),
                "Supposed to pass class members, but the provided parameters in the injection method are not of a reference type (ref)!");
                Assert(
                typeReferences.SequenceEqual(
                memberReferences.Select(f => (TypeReference) new ByReferenceType(f.FieldType)),
                comparer),
                "Supposed to pass class members, but the existing members are of a different type than the ones specified in the injection method.");
            }

            if (hFlags.PassParameters)
            {
                Assert(
                injectMethod.HasGenericParameters == injectTarget.Parameters.Any(p => p.ParameterType.IsGenericParameter),
                "The injection and target methods have mismatching specification of generic parameters!");

                Assert(
                !injectMethod.HasGenericParameters
                || injectMethod.GenericParameters.Count <= injectTarget.GenericParameters.Count + injectTarget.DeclaringType.GenericParameters.Count,
                "The injection and target methods have a mismatching number of generic parameters! The injection method must have less or the same number of generic parameters as the target!");

                Assert(
                !hFlags.PassParametersByRef
                || injectMethod.Parameters.Skip(prefixCount + localsCount + memberRefCount)
                               .All(p => p.ParameterType.IsByReference),
                "Supposed to pass target method parameters by reference, but the provided parameters in the injection method are not of a reference type (ref).");

                Assert(
                injectMethod.Parameters.Skip(prefixCount + localsCount + memberRefCount)
                            .Select(p => p.ParameterType)
                            .SequenceEqual(
                            injectTarget.Parameters.Take(parameters)
                                        .Select(
                                        p =>
                                        (hFlags.PassParametersByRef
                                         ? new ByReferenceType(p.ParameterType) : p.ParameterType)),
                            comparer),
                "Supposed to pass target method parameters by reference, but the types specified in injection and target methods do not match.");
            }

            InjectMethod = injectMethod;
            InjectTarget = injectTarget;
            Flags = flags;
            MemberReferences = memberReferences;
            LocalVarIDs = localVarIDs;
            _PrefixCount = prefixCount;
            _MemeberRefCount = memberRefCount;
            _ParameterCount = parameters;
        }
Exemple #14
0
        public void Equals()
        {
            var engine = new ScriptEngine();

            // Undefined.
            Assert.AreEqual(true, TypeComparer.Equals(Undefined.Value, Undefined.Value));
            Assert.AreEqual(true, TypeComparer.Equals(Undefined.Value, Null.Value));
            Assert.AreEqual(false, TypeComparer.Equals(Undefined.Value, false));
            Assert.AreEqual(false, TypeComparer.Equals(Undefined.Value, true));
            Assert.AreEqual(false, TypeComparer.Equals(Undefined.Value, 0));
            Assert.AreEqual(false, TypeComparer.Equals(Undefined.Value, 0.0));
            Assert.AreEqual(false, TypeComparer.Equals(Undefined.Value, 5.5));
            Assert.AreEqual(false, TypeComparer.Equals(Undefined.Value, double.NaN));
            Assert.AreEqual(false, TypeComparer.Equals(Undefined.Value, ""));
            Assert.AreEqual(false, TypeComparer.Equals(Undefined.Value, " "));
            Assert.AreEqual(false, TypeComparer.Equals(Undefined.Value, "5.5"));
            Assert.AreEqual(false, TypeComparer.Equals(Undefined.Value, "foo"));
            Assert.AreEqual(false, TypeComparer.Equals(Undefined.Value, engine.Object.Construct()));

            // Null.
            Assert.AreEqual(true, TypeComparer.Equals(Null.Value, Undefined.Value));
            Assert.AreEqual(true, TypeComparer.Equals(Null.Value, Null.Value));
            Assert.AreEqual(false, TypeComparer.Equals(Null.Value, false));
            Assert.AreEqual(false, TypeComparer.Equals(Null.Value, true));
            Assert.AreEqual(false, TypeComparer.Equals(Null.Value, 0));
            Assert.AreEqual(false, TypeComparer.Equals(Null.Value, 0.0));
            Assert.AreEqual(false, TypeComparer.Equals(Null.Value, 5.5));
            Assert.AreEqual(false, TypeComparer.Equals(Null.Value, double.NaN));
            Assert.AreEqual(false, TypeComparer.Equals(Null.Value, ""));
            Assert.AreEqual(false, TypeComparer.Equals(Null.Value, " "));
            Assert.AreEqual(false, TypeComparer.Equals(Null.Value, "5.5"));
            Assert.AreEqual(false, TypeComparer.Equals(Null.Value, "foo"));
            Assert.AreEqual(false, TypeComparer.Equals(Null.Value, engine.Object.Construct()));

            // Boolean.
            Assert.AreEqual(false, TypeComparer.Equals(false, Undefined.Value));
            Assert.AreEqual(false, TypeComparer.Equals(false, Null.Value));
            Assert.AreEqual(true, TypeComparer.Equals(false, false));
            Assert.AreEqual(false, TypeComparer.Equals(false, true));
            Assert.AreEqual(true, TypeComparer.Equals(false, 0));
            Assert.AreEqual(true, TypeComparer.Equals(false, 0.0));
            Assert.AreEqual(false, TypeComparer.Equals(false, 5.5));
            Assert.AreEqual(false, TypeComparer.Equals(false, double.NaN));
            Assert.AreEqual(true, TypeComparer.Equals(false, ""));
            Assert.AreEqual(true, TypeComparer.Equals(false, " "));
            Assert.AreEqual(true, TypeComparer.Equals(false, "0"));
            Assert.AreEqual(false, TypeComparer.Equals(false, "1"));
            Assert.AreEqual(false, TypeComparer.Equals(false, "5.5"));
            Assert.AreEqual(false, TypeComparer.Equals(false, "false"));
            Assert.AreEqual(false, TypeComparer.Equals(false, "true"));
            Assert.AreEqual(false, TypeComparer.Equals(false, "foo"));
            Assert.AreEqual(false, TypeComparer.Equals(false, engine.Object.Construct()));
            Assert.AreEqual(true, TypeComparer.Equals(false, engine.Boolean.Construct(false)));
            Assert.AreEqual(false, TypeComparer.Equals(false, engine.Boolean.Construct(true)));
            Assert.AreEqual(true, TypeComparer.Equals(false, engine.Number.Construct(0)));
            Assert.AreEqual(false, TypeComparer.Equals(false, engine.Number.Construct(1)));
            Assert.AreEqual(false, TypeComparer.Equals(true, "0"));
            Assert.AreEqual(true, TypeComparer.Equals(true, "1"));

            // Number.
            Assert.AreEqual(false, TypeComparer.Equals(5.5, Undefined.Value));
            Assert.AreEqual(false, TypeComparer.Equals(5.5, Null.Value));
            Assert.AreEqual(false, TypeComparer.Equals(5.5, false));
            Assert.AreEqual(false, TypeComparer.Equals(5.5, true));
            Assert.AreEqual(false, TypeComparer.Equals(5.5, 0));
            Assert.AreEqual(false, TypeComparer.Equals(5.5, 0.0));
            Assert.AreEqual(true, TypeComparer.Equals(5.5, 5.5));
            Assert.AreEqual(false, TypeComparer.Equals(5.5, double.NaN));
            Assert.AreEqual(false, TypeComparer.Equals(5.5, ""));
            Assert.AreEqual(false, TypeComparer.Equals(5.5, " "));
            Assert.AreEqual(true, TypeComparer.Equals(5.5, "5.5"));
            Assert.AreEqual(false, TypeComparer.Equals(5.5, "foo"));
            Assert.AreEqual(false, TypeComparer.Equals(5.5, engine.Object.Construct()));
            Assert.AreEqual(true, TypeComparer.Equals(5.5, engine.Number.Construct(5.5)));
            Assert.AreEqual(true, TypeComparer.Equals(0, 0.0));
            Assert.AreEqual(true, TypeComparer.Equals(5, 5.0));
            Assert.AreEqual(false, TypeComparer.Equals(double.NaN, double.NaN));
            Assert.AreEqual(false, TypeComparer.Equals(double.NaN, engine.Number.Construct(double.NaN)));

            // String.
            Assert.AreEqual(false, TypeComparer.Equals("5.5", Undefined.Value));
            Assert.AreEqual(false, TypeComparer.Equals("5.5", Null.Value));
            Assert.AreEqual(false, TypeComparer.Equals("5.5", false));
            Assert.AreEqual(false, TypeComparer.Equals("5.5", true));
            Assert.AreEqual(false, TypeComparer.Equals("5.5", 0));
            Assert.AreEqual(false, TypeComparer.Equals("5.5", 0.0));
            Assert.AreEqual(true, TypeComparer.Equals("5.5", 5.5));
            Assert.AreEqual(false, TypeComparer.Equals("5.5", double.NaN));
            Assert.AreEqual(false, TypeComparer.Equals("5.5", ""));
            Assert.AreEqual(false, TypeComparer.Equals("5.5", " "));
            Assert.AreEqual(true, TypeComparer.Equals("5.5", "5.5"));
            Assert.AreEqual(false, TypeComparer.Equals("5.5", "foo"));
            Assert.AreEqual(false, TypeComparer.Equals("5.5", engine.Object.Construct()));
            Assert.AreEqual(true, TypeComparer.Equals("5.5", engine.Number.Construct(5.5)));
            Assert.AreEqual(true, TypeComparer.Equals("5.5", engine.String.Construct("5.5")));
            Assert.AreEqual(true, TypeComparer.Equals("0", engine.Boolean.Construct(false)));
            Assert.AreEqual(true, TypeComparer.Equals("1", engine.Boolean.Construct(true)));
            Assert.AreEqual(true, TypeComparer.Equals("", engine.String.Construct()));
            Assert.AreEqual(true, TypeComparer.Equals("", engine.String.Construct("")));

            // Object.
            var temp = engine.Object.Construct();

            Assert.AreEqual(true, TypeComparer.Equals(temp, temp));
            Assert.AreEqual(true, TypeComparer.Equals(engine.Boolean.Construct(false), "0"));
            Assert.AreEqual(false, TypeComparer.Equals(engine.Boolean.Construct(false), "1"));
            Assert.AreEqual(false, TypeComparer.Equals(engine.Boolean.Construct(true), "0"));
            Assert.AreEqual(true, TypeComparer.Equals(engine.Boolean.Construct(true), "1"));
            Assert.AreEqual(false, TypeComparer.Equals(engine.Boolean.Construct(false), "false"));
            Assert.AreEqual(false, TypeComparer.Equals(engine.Boolean.Construct(false), "true"));
            Assert.AreEqual(false, TypeComparer.Equals(engine.Boolean.Construct(true), "false"));
            Assert.AreEqual(false, TypeComparer.Equals(engine.Boolean.Construct(true), "true"));
            Assert.AreEqual(false, TypeComparer.Equals(engine.Object.Construct(), engine.Object.Construct()));
            Assert.AreEqual(false, TypeComparer.Equals(engine.Number.Construct(5.5), engine.Number.Construct(5.5)));
            Assert.AreEqual(true, TypeComparer.Equals(engine.Number.Construct(5.5), 5.5));
            Assert.AreEqual(false, TypeComparer.Equals(engine.String.Construct("5.5"), engine.String.Construct("5.5")));
            Assert.AreEqual(true, TypeComparer.Equals(engine.String.Construct("5.5"), 5.5));
            Assert.AreEqual(true, TypeComparer.Equals(engine.String.Construct(""), ""));
        }
Exemple #15
0
    #pragma warning disable CS3001 // Argument type is not CLS-compliant - needed for CLAP
        public static void Error(ExceptionContext context)
    #pragma warning restore CS3001 // Argument type is not CLS-compliant
        {
            new { context }.Must().NotBeNull();
            var typeDescriptionComparer = new TypeComparer(TypeMatchStrategy.NamespaceAndName);

            // change color to red
            var originalColor = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.Red;

            // parser exception or
            if (context.Exception is CommandLineParserException)
            {
                Console.WriteLine("Failure parsing command line arguments.  Run the exe with the 'help' command for usage.");
                Console.WriteLine("   " + context.Exception.Message);
            }
            else if ((ExceptionTypeRepresentationsToOnlyPrintMessage ?? new TypeRepresentation[0]).Any(_ => typeDescriptionComparer.Equals(_, context.Exception.GetType().ToRepresentation())))
            {
                Console.WriteLine("Failure during execution; configured to omit stack trace.");
                Console.WriteLine(string.Empty);
                Console.WriteLine("   " + context.Exception.Message);
            }
            else
            {
                Console.WriteLine("Failure during execution.");
                Console.WriteLine("   " + context.Exception.Message);
                Console.WriteLine(string.Empty);
                Console.WriteLine("   " + context.Exception);
                Its.Log.Instrumentation.Log.Write(context.Exception);
            }

            // restore color
            Console.WriteLine();
            Console.ForegroundColor = originalColor;
        }
Exemple #16
0
        /// <summary>
        /// Evaluates the expression, if possible.
        /// </summary>
        /// <returns> The result of evaluating the expression, or <c>null</c> if the expression can
        /// not be evaluated. </returns>
        public override object Evaluate()
        {
            // Evaluate the operands.
            var left = this.Left.Evaluate();

            if (left == null)
            {
                return(null);
            }
            var right = this.Right.Evaluate();

            if (right == null)
            {
                return(null);
            }

            // Apply the binary operator logic.
            switch (this.OperatorType)
            {
            case OperatorType.Add:
            {
                var leftPrimitive  = TypeConverter.ToPrimitive(left, PrimitiveTypeHint.None);
                var rightPrimitive = TypeConverter.ToPrimitive(right, PrimitiveTypeHint.None);
                if (TypeUtilities.IsString(leftPrimitive) == true || TypeUtilities.IsString(rightPrimitive) == true)
                {
                    return(TypeConverter.ToString(leftPrimitive) + TypeConverter.ToString(rightPrimitive));
                }
                return(TypeConverter.ToNumber(leftPrimitive) + TypeConverter.ToNumber(rightPrimitive));
            }

            // Arithmetic operations.
            case OperatorType.Subtract:
                return(TypeConverter.ToNumber(left) - TypeConverter.ToNumber(right));

            case OperatorType.Multiply:
                return(TypeConverter.ToNumber(left) * TypeConverter.ToNumber(right));

            case OperatorType.Divide:
                return(TypeConverter.ToNumber(left) / TypeConverter.ToNumber(right));

            case OperatorType.Modulo:
                return(TypeConverter.ToNumber(left) % TypeConverter.ToNumber(right));

            case OperatorType.Exponentiation:
                return(Library.MathObject.Pow(TypeConverter.ToNumber(left), TypeConverter.ToNumber(right)));

            // Bitwise operations.
            case OperatorType.BitwiseAnd:
                return(TypeConverter.ToInt32(left) & TypeConverter.ToInt32(right));

            case OperatorType.BitwiseOr:
                return(TypeConverter.ToInt32(left) | TypeConverter.ToInt32(right));

            case OperatorType.BitwiseXor:
                return(TypeConverter.ToInt32(left) ^ TypeConverter.ToInt32(right));

            case OperatorType.LeftShift:
                return(TypeConverter.ToInt32(left) << (int)(TypeConverter.ToUint32(right) & 0x1F));

            case OperatorType.SignedRightShift:
                return(TypeConverter.ToInt32(left) >> (int)(TypeConverter.ToUint32(right) & 0x1F));

            case OperatorType.UnsignedRightShift:
                return((uint)TypeConverter.ToInt32(left) >> (int)(TypeConverter.ToUint32(right) & 0x1F));

            // Relational operations.
            case OperatorType.LessThan:
            case OperatorType.LessThanOrEqual:
            case OperatorType.GreaterThan:
            case OperatorType.GreaterThanOrEqual:
                return(PrimitiveType.Bool);

            // Equality operations.
            case OperatorType.Equal:
                return(TypeComparer.Equals(left, right) == true);

            case OperatorType.StrictlyEqual:
                return(TypeComparer.StrictEquals(left, right) == true);

            case OperatorType.NotEqual:
                return(TypeComparer.Equals(left, right) == false);

            case OperatorType.StrictlyNotEqual:
                return(TypeComparer.StrictEquals(left, right) == false);

            // Logical operations.
            case OperatorType.LogicalAnd:
                if (TypeConverter.ToBoolean(left) == false)
                {
                    return(left);
                }
                return(right);

            case OperatorType.LogicalOr:
                if (TypeConverter.ToBoolean(left) == true)
                {
                    return(left);
                }
                return(right);

            // Misc
            case OperatorType.InstanceOf:
            case OperatorType.In:
                return(null);

            default:
                throw new NotImplementedException(string.Format("Unsupported operator {0}", this.OperatorType));
            }
        }
Exemple #17
0
        private void AddMissingAliases(TypeDeclaration typeDeclaration)
        {
            var type       = this.Resolver.ResolveNode(typeDeclaration, null).Type;
            var interfaces = type.DirectBaseTypes.Where(t => t.Kind == TypeKind.Interface).ToArray();
            var members    = type.GetMembers(null, GetMemberOptions.IgnoreInheritedMembers).ToArray();
            var baseTypes  = type.GetNonInterfaceBaseTypes().ToArray().Reverse();

            if (interfaces.Length > 0)
            {
                foreach (var baseInterface in interfaces)
                {
                    var interfaceMembers = baseInterface.GetMembers().Where(m => m.DeclaringTypeDefinition.Kind == TypeKind.Interface);
                    foreach (var interfaceMember in interfaceMembers)
                    {
                        var isDirectlyImplemented = members.Any(m => m.ImplementedInterfaceMembers.Contains(interfaceMember));
                        if (!isDirectlyImplemented)
                        {
                            foreach (var baseType in baseTypes)
                            {
                                //var derivedMember = InheritanceHelper.GetDerivedMember(interfaceMember, baseType.GetDefinition());
                                IMember derivedMember = null;
                                IEnumerable <IMember> baseMembers;
                                if (interfaceMember.SymbolKind == SymbolKind.Accessor)
                                {
                                    baseMembers = baseType.GetAccessors(null, GetMemberOptions.IgnoreInheritedMembers).Where(m => m.Name == interfaceMember.Name && TypeComparer.Equals(m.ReturnType, interfaceMember.ReturnType));
                                }
                                else
                                {
                                    baseMembers = baseType.GetMembers(null, GetMemberOptions.IgnoreInheritedMembers).Where(m => m.Name == interfaceMember.Name && TypeComparer.Equals(m.ReturnType, interfaceMember.ReturnType));
                                }

                                foreach (IMember baseMember in baseMembers)
                                {
                                    if (baseMember.IsPrivate)
                                    {
                                        continue;
                                    }
                                    if (SignatureComparer.Ordinal.Equals(interfaceMember, baseMember))
                                    {
                                        derivedMember = baseMember.Specialize(interfaceMember.Substitution);
                                        break;
                                    }
                                }

                                if (derivedMember != null && !derivedMember.ImplementedInterfaceMembers.Contains(interfaceMember) && !this.CurrentType.InstanceConfig.Alias.Any(a => typeDeclaration.Equals(a.Entity) && interfaceMember.Equals(a.InterfaceMember) && derivedMember.Equals(a.DerivedMember)))
                                {
                                    this.CurrentType.InstanceConfig.Alias.Add(new TypeConfigItem {
                                        Entity = typeDeclaration, InterfaceMember = interfaceMember, DerivedMember = derivedMember
                                    });
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
Exemple #18
0
 public bool JSEquals(object o1, object o2)
 {
     return(TypeComparer.Equals(o1, o2));
 }