Ejemplo n.º 1
0
        Value Visit(ConversionResolveResult result)
        {
            if (result.IsError)
            {
                throw new GetValueException("Cannot convert from '{0}' to '{1}'.", new CSharpAmbience().ConvertType(result.Input.Type), new CSharpAmbience().ConvertType(result.Type));
            }
            var val = Convert(result.Input);

            if (result.Conversion.IsBoxingConversion)
            {
                return(val);
            }
            if (result.Conversion.IsIdentityConversion)
            {
                return(val);
            }
            if (result.Conversion.IsNumericConversion)
            {
                var convVal = CSharpPrimitiveCast.Cast(ReflectionHelper.GetTypeCode(result.Type), val.PrimitiveValue, false);
                return(Eval.CreateValue(evalThread, convVal));
            }
            if (result.Conversion.IsUserDefined)
            {
                return(InvokeMethod(null, result.Conversion.Method, val));
            }
            if (result.Conversion.IsReferenceConversion && result.Conversion.IsImplicit)
            {
                return(val);
            }
            if (result.Conversion.IsNullLiteralConversion)
            {
                return(val);
            }
            throw new GetValueException("conversion '{0}' not implemented!", result.Conversion);
        }
Ejemplo n.º 2
0
        bool IsLiteralMatch(object val)
        {
            if (val == null)
            {
                return(false);
            }
            switch (searchTermLiteralType)
            {
            case TypeCode.Int64:
                TypeCode tc = Type.GetTypeCode(val.GetType());
                if (tc >= TypeCode.SByte && tc <= TypeCode.UInt64)
                {
                    return(CSharpPrimitiveCast.Cast(TypeCode.Int64, val, false).Equals(searchTermLiteralValue));
                }
                else
                {
                    return(false);
                }

            case TypeCode.Single:
            case TypeCode.Double:
            case TypeCode.String:
                return(searchTermLiteralValue.Equals(val));

            default:
                // substring search with searchTerm
                return(IsMatch(t => val.ToString()));
            }
        }
Ejemplo n.º 3
0
 public Expression ConvertConstantValue(IType type, object constantValue)
 {
     if (type == null)
     {
         throw new ArgumentNullException("type");
     }
     if (constantValue == null)
     {
         if (type.IsReferenceType == true)
         {
             return(new NullReferenceExpression());
         }
         else
         {
             return(new DefaultValueExpression(ConvertType(type)));
         }
     }
     else if (type.Kind == TypeKind.Enum)
     {
         return(ConvertEnumValue(type, (long)CSharpPrimitiveCast.Cast(TypeCode.Int64, constantValue, false)));
     }
     else
     {
         return(new PrimitiveExpression(constantValue));
     }
 }
Ejemplo n.º 4
0
        public LiteralSearchStrategy(params string[] terms)
            : base(terms)
        {
            if (1 == searchTerm.Length)
            {
                var parser = new CSharpParser();
                var pe     = parser.ParseExpression(searchTerm[0]) as PrimitiveExpression;

                if (pe != null && pe.Value != null)
                {
                    TypeCode peValueType = Type.GetTypeCode(pe.Value.GetType());
                    switch (peValueType)
                    {
                    case TypeCode.Byte:
                    case TypeCode.SByte:
                    case TypeCode.Int16:
                    case TypeCode.UInt16:
                    case TypeCode.Int32:
                    case TypeCode.UInt32:
                    case TypeCode.Int64:
                    case TypeCode.UInt64:
                        searchTermLiteralType  = TypeCode.Int64;
                        searchTermLiteralValue = CSharpPrimitiveCast.Cast(TypeCode.Int64, pe.Value, false);
                        break;

                    case TypeCode.Single:
                    case TypeCode.Double:
                    case TypeCode.String:
                        searchTermLiteralType  = peValueType;
                        searchTermLiteralValue = pe.Value;
                        break;
                    }
                }
            }
        }
Ejemplo n.º 5
0
        public LiteralSearchStrategy(Language language, ApiVisibility apiVisibility, IProducerConsumerCollection <SearchResult> resultQueue, params string[] terms)
            : base(language, apiVisibility, resultQueue, terms)
        {
            if (terms.Length == 1)
            {
                var lexer = new Lexer(new LATextReader(new System.IO.StringReader(terms[0])));
                var value = lexer.NextToken();

                if (value != null && value.LiteralValue != null)
                {
                    TypeCode valueType = Type.GetTypeCode(value.LiteralValue.GetType());
                    switch (valueType)
                    {
                    case TypeCode.Byte:
                    case TypeCode.SByte:
                    case TypeCode.Int16:
                    case TypeCode.UInt16:
                    case TypeCode.Int32:
                    case TypeCode.UInt32:
                    case TypeCode.Int64:
                    case TypeCode.UInt64:
                        searchTermLiteralType  = TypeCode.Int64;
                        searchTermLiteralValue = CSharpPrimitiveCast.Cast(TypeCode.Int64, value.LiteralValue, false);
                        break;

                    case TypeCode.Single:
                    case TypeCode.Double:
                    case TypeCode.String:
                        searchTermLiteralType  = valueType;
                        searchTermLiteralValue = value.LiteralValue;
                        break;
                    }
                }
            }
        }
Ejemplo n.º 6
0
        ConstantResolveResult CreateTypedCaseLabel(long i, IType type, string[] map = null)
        {
            object value;

            // unpack nullable type, if necessary:
            // we need to do this in all cases, because there are nullable bools and enum types as well.
            type = NullableType.GetUnderlyingType(type);
            if (type.IsKnownType(KnownTypeCode.Boolean))
            {
                value = i != 0;
            }
            else if (type.IsKnownType(KnownTypeCode.String) && map != null)
            {
                value = map[i];
            }
            else if (type.Kind == TypeKind.Enum)
            {
                var enumType = type.GetDefinition().EnumUnderlyingType;
                value = CSharpPrimitiveCast.Cast(ReflectionHelper.GetTypeCode(enumType), i, false);
            }
            else
            {
                value = CSharpPrimitiveCast.Cast(ReflectionHelper.GetTypeCode(type), i, false);
            }
            return(new ConstantResolveResult(type, value));
        }
Ejemplo n.º 7
0
        public LiteralSearchStrategy(params string[] terms)
            : base(terms)
        {
            if (searchTerm.Length == 1)
            {
                var lexer = new Lexer(new LATextReader(new System.IO.StringReader(searchTerm[0])));
                var value = lexer.NextToken();

                if (value != null && value.LiteralValue != null)
                {
                    TypeCode valueType = Type.GetTypeCode(value.LiteralValue.GetType());
                    switch (valueType)
                    {
                    case TypeCode.Byte:
                    case TypeCode.SByte:
                    case TypeCode.Int16:
                    case TypeCode.UInt16:
                    case TypeCode.Int32:
                    case TypeCode.UInt32:
                    case TypeCode.Int64:
                    case TypeCode.UInt64:
                        searchTermLiteralType  = TypeCode.Int64;
                        searchTermLiteralValue = CSharpPrimitiveCast.Cast(TypeCode.Int64, value.LiteralValue, false);
                        break;

                    case TypeCode.Single:
                    case TypeCode.Double:
                    case TypeCode.String:
                        searchTermLiteralType  = valueType;
                        searchTermLiteralValue = value.LiteralValue;
                        break;
                    }
                }
            }
        }
Ejemplo n.º 8
0
        ConstantResolveResult CreateTypedCaseLabel(long i, IType type, string[] map = null)
        {
            object value;

            if (type.IsKnownType(KnownTypeCode.Boolean))
            {
                value = i != 0;
            }
            else if (type.IsKnownType(KnownTypeCode.String) && map != null)
            {
                value = map[i];
            }
            else if (type.Kind == TypeKind.Enum)
            {
                var enumType = type.GetDefinition().EnumUnderlyingType;
                value = CSharpPrimitiveCast.Cast(ReflectionHelper.GetTypeCode(enumType), i, false);
            }
            else if (type.IsKnownType(KnownTypeCode.NullableOfT))
            {
                var nullableType = NullableType.GetUnderlyingType(type);
                value = CSharpPrimitiveCast.Cast(ReflectionHelper.GetTypeCode(nullableType), i, false);
            }
            else
            {
                value = CSharpPrimitiveCast.Cast(ReflectionHelper.GetTypeCode(type), i, false);
            }
            return(new ConstantResolveResult(type, value));
        }
Ejemplo n.º 9
0
            public void Run()
            {
                try {
                    if (searchMode == SearchMode_Literal)
                    {
                        if (1 == searchTerm.Length)
                        {
                            CSharpParser        parser = new CSharpParser();
                            PrimitiveExpression pe     = parser.ParseExpression(searchTerm[0]) as PrimitiveExpression;
                            if (pe != null && pe.Value != null)
                            {
                                TypeCode peValueType = Type.GetTypeCode(pe.Value.GetType());
                                switch (peValueType)
                                {
                                case TypeCode.Byte:
                                case TypeCode.SByte:
                                case TypeCode.Int16:
                                case TypeCode.UInt16:
                                case TypeCode.Int32:
                                case TypeCode.UInt32:
                                case TypeCode.Int64:
                                case TypeCode.UInt64:
                                    searchTermLiteralType  = TypeCode.Int64;
                                    searchTermLiteralValue = CSharpPrimitiveCast.Cast(TypeCode.Int64, pe.Value, false);
                                    break;

                                case TypeCode.Single:
                                case TypeCode.Double:
                                case TypeCode.String:
                                    searchTermLiteralType  = peValueType;
                                    searchTermLiteralValue = pe.Value;
                                    break;
                                }
                            }
                        }
                    }

                    foreach (var loadedAssembly in assemblies)
                    {
                        ModuleDefinition module = loadedAssembly.ModuleDefinition;
                        if (module == null)
                        {
                            continue;
                        }
                        CancellationToken cancellationToken = cts.Token;
                        foreach (TypeDefinition type in module.Types)
                        {
                            cancellationToken.ThrowIfCancellationRequested();
                            PerformSearch(type);
                        }
                    }
                } catch (OperationCanceledException) {
                    // ignore cancellation
                }
                // remove the 'Searching...' entry
                dispatcher.BeginInvoke(
                    DispatcherPriority.Normal,
                    new Action(delegate { this.Results.RemoveAt(this.Results.Count - 1); }));
            }
Ejemplo n.º 10
0
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                var t = value.GetType();

                if (t.IsEnum)
                {
                    return((int)CSharpPrimitiveCast.Cast(TypeCode.Int32, value, false));
                }
                return(value);
            }
Ejemplo n.º 11
0
        static object[] MakeConstantArray(ResolveResult[] sizeArguments, ResolveResult[] initializerElements)
        {
            if (initializerElements == null)
            {
                return(null);
            }

            for (int i = 0; i < initializerElements.Length; i++)
            {
                if (!initializerElements[i].IsCompileTimeConstant)
                {
                    return(null);
                }
            }

            if (sizeArguments != null && sizeArguments.Length > 0)
            {
                if (sizeArguments.Length > 1)
                {
                    // 2D-arrays can't be constant
                    return(null);
                }
                if (!sizeArguments[0].IsCompileTimeConstant)
                {
                    return(null);
                }

                int expectedSize;
                try {
                    expectedSize = (int)CSharpPrimitiveCast.Cast(TypeCode.Int32, sizeArguments[0].ConstantValue, true);
                } catch (InvalidCastException) {
                    return(null);
                } catch (OverflowException) {
                    return(null);
                }
                if (expectedSize != initializerElements.Length)
                {
                    return(null);
                }
            }

            object[] constants = new object[initializerElements.Length];
            for (int i = 0; i < initializerElements.Length; i++)
            {
                constants[i] = initializerElements[i].ConstantValue;
            }
            return(constants);
        }
Ejemplo n.º 12
0
        public ResolveResult Resolve(ITypeResolveContext context)
        {
            ResolveResult rr = baseValue.Resolve(context);

            if (rr.IsCompileTimeConstant && rr.ConstantValue != null)
            {
                object   val      = rr.ConstantValue;
                TypeCode typeCode = Type.GetTypeCode(val.GetType());
                if (typeCode >= TypeCode.SByte && typeCode <= TypeCode.UInt64)
                {
                    long   intVal = (long)CSharpPrimitiveCast.Cast(TypeCode.Int64, val, false);
                    object newVal = CSharpPrimitiveCast.Cast(typeCode, unchecked (intVal + incrementAmount), false);
                    return(new ConstantResolveResult(rr.Type, newVal));
                }
            }
            return(new ErrorResolveResult(rr.Type));
        }
Ejemplo n.º 13
0
        public object GetValue(ITypeResolveContext context)
        {
            object val = baseValue.GetValue(context);

            if (val == null)
            {
                return(null);
            }
            TypeCode typeCode = Type.GetTypeCode(val.GetType());

            if (!(typeCode >= TypeCode.SByte && typeCode <= TypeCode.UInt64))
            {
                return(null);
            }
            long intVal = (long)CSharpPrimitiveCast.Cast(TypeCode.Int64, val, false);

            return(CSharpPrimitiveCast.Cast(typeCode, unchecked (intVal + incrementAmount), false));
        }
Ejemplo n.º 14
0
        CaseLabel CreateTypedCaseLabel(long i, IType type)
        {
            object value;

            if (type.IsKnownType(KnownTypeCode.Boolean))
            {
                value = i != 0;
            }
            else if (type.Kind == TypeKind.Enum)
            {
                var enumType = type.GetDefinition().EnumUnderlyingType;
                value = CSharpPrimitiveCast.Cast(ReflectionHelper.GetTypeCode(enumType), i, false);
            }
            else
            {
                value = CSharpPrimitiveCast.Cast(ReflectionHelper.GetTypeCode(type), i, false);
            }
            return(new CaseLabel(exprBuilder.ConvertConstantValue(new ConstantResolveResult(type, value))));
        }
Ejemplo n.º 15
0
        static void RunTest(bool checkForOverflow)
        {
            string mode = checkForOverflow ? "checked" : "unchecked";

            foreach (object input in inputValues)
            {
                string inputType = input.GetType().Name;
                foreach (var targetType in targetTypes)
                {
                    try {
                        object result = CSharpPrimitiveCast.Cast(targetType, input, checkForOverflow);
                        Console.WriteLine("{0} ({1})({2}){3} = ({4}){5}", mode, targetType, inputType, input,
                                          result.GetType().Name, result);
                    } catch (Exception ex) {
                        Console.WriteLine("{0} ({1})({2}){3} = {4}", mode, targetType, inputType, input,
                                          ex.GetType().Name);
                    }
                }
            }
        }
Ejemplo n.º 16
0
        public static IEnumerable <Flag> GetFlags(Type flagsType, int mask = -1, int selectedValues = 0, string neutralItem = null)
        {
            if (neutralItem != null)
            {
                yield return(new Flag(neutralItem, -1, false));
            }

            foreach (var item in flagsType.GetFields(BindingFlags.Static | BindingFlags.Public))
            {
                if (item.Name.EndsWith("Mask", StringComparison.Ordinal))
                {
                    continue;
                }
                int value = (int)CSharpPrimitiveCast.Cast(TypeCode.Int32, item.GetRawConstantValue(), false);
                if ((value & mask) == 0)
                {
                    continue;
                }
                yield return(new Flag($"{item.Name} ({value:X4})", value, (selectedValues & value) != 0));
            }
        }
Ejemplo n.º 17
0
 public Expression ConvertConstantValue(IType type, object constantValue)
 {
     if (type == null)
         throw new ArgumentNullException("type");
     if (constantValue == null) {
         if (type.IsReferenceType == true) {
             var expr = new NullReferenceExpression();
             if (AddResolveResultAnnotations)
                 expr.AddAnnotation(new ConstantResolveResult(SpecialType.NullType, null));
             return expr;
         } else {
             var expr = new DefaultValueExpression(ConvertType(type));
             if (AddResolveResultAnnotations)
                 expr.AddAnnotation(new ConstantResolveResult(type, null));
             return expr;
         }
     } else if (type.Kind == TypeKind.Enum) {
         return ConvertEnumValue(type, (long)CSharpPrimitiveCast.Cast(TypeCode.Int64, constantValue, false));
     } else {
         return new PrimitiveExpression(constantValue);
     }
 }
Ejemplo n.º 18
0
        public override void VisitAssignmentExpression(AssignmentExpression assignment)
        {
            base.VisitAssignmentExpression(assignment);
            // Combine "x = x op y" into "x op= y"
            BinaryOperatorExpression binary = assignment.Right as BinaryOperatorExpression;

            if (binary != null && assignment.Operator == AssignmentOperatorType.Assign)
            {
                if (CanConvertToCompoundAssignment(assignment.Left) && assignment.Left.IsMatch(binary.Left))
                {
                    assignment.Operator = GetAssignmentOperatorForBinaryOperator(binary.Operator);
                    if (assignment.Operator != AssignmentOperatorType.Assign)
                    {
                        // If we found a shorter operator, get rid of the BinaryOperatorExpression:
                        assignment.CopyAnnotationsFrom(binary);
                        assignment.Right = binary.Right;
                    }
                }
            }
            // TODO: context.Settings.IntroduceIncrementAndDecrement
            if (assignment.Operator == AssignmentOperatorType.Add || assignment.Operator == AssignmentOperatorType.Subtract)
            {
                // detect increment/decrement
                var rr = assignment.Right.GetResolveResult();
                if (rr.IsCompileTimeConstant && rr.Type.IsCSharpPrimitiveIntegerType() && CSharpPrimitiveCast.Cast(rr.Type.GetTypeCode(), 1, false).Equals(rr.ConstantValue))
                {
                    // only if it's not a custom operator
                    if (assignment.Annotation <IL.CallInstruction>() == null)
                    {
                        UnaryOperatorType type;
                        // When the parent is an expression statement, pre- or post-increment doesn't matter;
                        // so we can pick post-increment which is more commonly used (for (int i = 0; i < x; i++))
                        if (assignment.Parent is ExpressionStatement)
                        {
                            type = (assignment.Operator == AssignmentOperatorType.Add) ? UnaryOperatorType.PostIncrement : UnaryOperatorType.PostDecrement;
                        }
                        else
                        {
                            type = (assignment.Operator == AssignmentOperatorType.Add) ? UnaryOperatorType.Increment : UnaryOperatorType.Decrement;
                        }
                        assignment.ReplaceWith(new UnaryOperatorExpression(type, assignment.Left.Detach()).CopyAnnotationsFrom(assignment));
                    }
                }
            }
        }
Ejemplo n.º 19
0
        Expression ConvertEnumValue(IType type, long val)
        {
            ITypeDefinition enumDefinition   = type.GetDefinition();
            TypeCode        enumBaseTypeCode = ReflectionHelper.GetTypeCode(enumDefinition.EnumUnderlyingType);

            foreach (IField field in enumDefinition.Fields)
            {
                if (field.IsConst && object.Equals(CSharpPrimitiveCast.Cast(TypeCode.Int64, field.ConstantValue, false), val))
                {
                    return(ConvertType(type).Member(field.Name));
                }
            }
            if (IsFlagsEnum(enumDefinition))
            {
                long       enumValue        = val;
                Expression expr             = null;
                long       negatedEnumValue = ~val;
                // limit negatedEnumValue to the appropriate range
                switch (enumBaseTypeCode)
                {
                case TypeCode.Byte:
                case TypeCode.SByte:
                    negatedEnumValue &= byte.MaxValue;
                    break;

                case TypeCode.Int16:
                case TypeCode.UInt16:
                    negatedEnumValue &= ushort.MaxValue;
                    break;

                case TypeCode.Int32:
                case TypeCode.UInt32:
                    negatedEnumValue &= uint.MaxValue;
                    break;
                }
                Expression negatedExpr = null;
                foreach (IField field in enumDefinition.Fields.Where(fld => fld.IsConst))
                {
                    long fieldValue = (long)CSharpPrimitiveCast.Cast(TypeCode.Int64, field.ConstantValue, false);
                    if (fieldValue == 0)
                    {
                        continue;                               // skip None enum value
                    }
                    if ((fieldValue & enumValue) == fieldValue)
                    {
                        var fieldExpression = ConvertType(type).Member(field.Name);
                        if (expr == null)
                        {
                            expr = fieldExpression;
                        }
                        else
                        {
                            expr = new BinaryOperatorExpression(expr, BinaryOperatorType.BitwiseOr, fieldExpression);
                        }

                        enumValue &= ~fieldValue;
                    }
                    if ((fieldValue & negatedEnumValue) == fieldValue)
                    {
                        var fieldExpression = ConvertType(type).Member(field.Name);
                        if (negatedExpr == null)
                        {
                            negatedExpr = fieldExpression;
                        }
                        else
                        {
                            negatedExpr = new BinaryOperatorExpression(negatedExpr, BinaryOperatorType.BitwiseOr, fieldExpression);
                        }

                        negatedEnumValue &= ~fieldValue;
                    }
                }
                if (enumValue == 0 && expr != null)
                {
                    if (!(negatedEnumValue == 0 && negatedExpr != null && negatedExpr.Descendants.Count() < expr.Descendants.Count()))
                    {
                        return(expr);
                    }
                }
                if (negatedEnumValue == 0 && negatedExpr != null)
                {
                    return(new UnaryOperatorExpression(UnaryOperatorType.BitNot, negatedExpr));
                }
            }
            return(new PrimitiveExpression(CSharpPrimitiveCast.Cast(enumBaseTypeCode, val, false)).CastTo(ConvertType(type)));
        }