Example #1
0
        public override object VisitInvocationExpression(InvocationExpression invocationExpression, object data)
        {
            if (context.Settings.ExpressionTrees && ExpressionTreeConverter.CouldBeExpressionTree(invocationExpression))
            {
                Expression converted = ExpressionTreeConverter.TryConvert(context, invocationExpression);
                if (converted != null)
                {
                    invocationExpression.ReplaceWith(converted);
                    return(converted.AcceptVisitor(this, data));
                }
            }
            var definition = invocationExpression.Annotation <MethodDefinition>();

            if (definition != null)
            {
                //Handle hoisted base calls from yield return compiler generated class (can be generated by both Mono and Roslyn)
                if (definition.DeclaringType == context.CurrentType && definition.IsCompilerGenerated())
                {
                    DecompilerContext subContext = context.Clone();
                    subContext.CurrentMethod        = definition;
                    subContext.CurrentMethodIsAsync = false;
                    subContext.ReservedVariableNames.AddRange(currentlyUsedVariableNames);
                    var            parameters = AstBuilder.MakeParameters(definition, isLambda: true);
                    BlockStatement body       = AstMethodBodyBuilder.CreateMethodBody(definition, subContext, parameters);
                    TransformationPipeline.RunTransformationsUntil(body, v => v is DelegateConstruction, subContext);

                    if (body.Statements.Count == 1)
                    {
                        var        statement = body.Statements.Single();
                        Expression expr      = null;
                        if (statement is ReturnStatement)
                        {
                            expr = ((ReturnStatement)statement).Expression;
                        }
                        else if (statement is ExpressionStatement)
                        {
                            expr = ((ExpressionStatement)statement).Expression;
                        }
                        if (expr != null)
                        {
                            expr.Remove();
                            invocationExpression.ReplaceWith(expr);
                            return(expr.AcceptVisitor(this, data));
                        }
                    }
                }
            }
            return(base.VisitInvocationExpression(invocationExpression, data));
        }
Example #2
0
        public override object VisitInvocationExpression(InvocationExpression invocationExpression, object data)
        {
            var memberReferenceExpression = invocationExpression.Target as MemberReferenceExpression;

            if (memberReferenceExpression == null)
            {
                return(base.VisitInvocationExpression(invocationExpression, data));
            }
            if (methodNames.Contains(memberReferenceExpression.MemberName) == false)
            {
                return(base.VisitInvocationExpression(invocationExpression, data));
            }

            var first = invocationExpression.Arguments.FirstOrDefault();

            if (first != null)
            {
                invocationExpression.Arguments.InsertBefore(first, memberReferenceExpression.Target.Clone());
            }
            else
            {
                invocationExpression.Arguments.Add(memberReferenceExpression.Target.Clone());
            }
            var newInvocation = new InvocationExpression(
                new MemberReferenceExpression(
                    new TypeReferenceExpression(new SimpleType(typeof(DynamicExtensionMethods).FullName)),
                    memberReferenceExpression.MemberName),
                invocationExpression.Arguments.Select(x => x.Clone())
                );

            invocationExpression.ReplaceWith(newInvocation);

            return(base.VisitInvocationExpression(invocationExpression, data));
        }
Example #3
0
 // replace method_505 with the actual string
 public override void VisitInvocationExpression(InvocationExpression invocation)
 {
     base.VisitInvocationExpression(invocation);
     if (Program.Strings.Count() > 0)
     {
         // maybe it'd be better to reference the original name, or ensure this gets a unique name... or just don't map it? assuming it never comes up
         if (invocation.Target.LastChild is Identifier id)
         {
             // maybe it'd be better to reference the original name, or ensure this gets a unique name... or just don't map it? assuming it never comes up
             if (RemappingVisitor.IntermediaryWhenMapped(id.Name).Equals("method_505"))
             {
                 if (invocation.Arguments.Count == 1 && invocation.Arguments.First() is PrimitiveExpression p && p.Value is int val)
                 {
                     if (Program.Strings.ContainsKey(val))
                     {
                         invocation.ReplaceWith(new PrimitiveExpression(Program.Strings[val]));
                     }
                     else
                     {
                         Console.WriteLine("Missing string for " + val + "!");
                     }
                 }
             }
         }
     }
 }
Example #4
0
 public override object VisitInvocationExpression(InvocationExpression invocationExpression, object data)
 {
     if (context.Settings.ExpressionTrees && ExpressionTreeConverter.CouldBeExpressionTree(invocationExpression))
     {
         Expression converted = ExpressionTreeConverter.TryConvert(context, invocationExpression);
         if (converted != null)
         {
             invocationExpression.ReplaceWith(converted);
             return(converted.AcceptVisitor(this, data));
         }
     }
     return(base.VisitInvocationExpression(invocationExpression, data));
 }
Example #5
0
 public override object VisitInvocationExpression(InvocationExpression invocationExpression, object data)
 {
     if (context.Settings.ExpressionTrees && ExpressionTreeConverter.CouldBeExpressionTree(invocationExpression))
     {
         Expression converted = ExpressionTreeConverter.TryConvert(context, invocationExpression);
         if (converted != null)
         {
             //TODO: Do we need to preserve ILRanges or is it taken care of by TryConvert?
             invocationExpression.ReplaceWith(converted);
             return(converted.AcceptVisitor(this, data));
         }
     }
     return(base.VisitInvocationExpression(invocationExpression, data));
 }
Example #6
0
        public override object VisitInvocationExpression(InvocationExpression invocationExpression, object data)
        {
            var memberReferenceExpression = invocationExpression.Target as MemberReferenceExpression;

            if (memberReferenceExpression != null && memberReferenceExpression.MemberName == "GroupBy")
            {
                var newInvocation = new InvocationExpression(
                    new MemberReferenceExpression(
                        new TypeReferenceExpression(new SimpleType(typeof(LinqOnDynamic).FullName)),
                        memberReferenceExpression.MemberName),
                    invocationExpression.Arguments.Select(x => x.Clone())
                    );
                invocationExpression.ReplaceWith(newInvocation);
            }

            return(base.VisitInvocationExpression(invocationExpression, data));
        }
Example #7
0
        public override object VisitInvocationExpression(InvocationExpression invocationExpression, object data)
        {
            var memberReferenceExpression = invocationExpression.Target as MemberReferenceExpression;

            if (memberReferenceExpression == null || memberReferenceExpression.MemberName != "Generate")
            {
                return(base.VisitInvocationExpression(invocationExpression, data));
            }

            var identifierExpression = memberReferenceExpression.Target as IdentifierExpression;

            if (identifierExpression == null || identifierExpression.Identifier != "SpatialIndex")
            {
                return(base.VisitInvocationExpression(invocationExpression, data));
            }

            invocationExpression.ReplaceWith(new InvocationExpression(new IdentifierExpression("SpatialGenerate"), invocationExpression.Arguments.Select(x => x.Clone())));

            return(base.VisitInvocationExpression(invocationExpression, data));
        }
        internal static void ProcessInvocationExpression(InvocationExpression invocationExpression)
        {
            MethodReference methodRef = invocationExpression.Annotation <MethodReference>();

            if (methodRef == null)
            {
                return;
            }
            var arguments = invocationExpression.Arguments.ToArray();

            // Reduce "String.Concat(a, b)" to "a + b"
            if (methodRef.Name == "Concat" && methodRef.DeclaringType.FullName == "System.String" && arguments.Length >= 2)
            {
                invocationExpression.Arguments.Clear(); // detach arguments from invocationExpression
                Expression expr = arguments[0];
                for (int i = 1; i < arguments.Length; i++)
                {
                    expr = new BinaryOperatorExpression(expr, BinaryOperatorType.Add, arguments[i]);
                }
                invocationExpression.ReplaceWith(expr);
                return;
            }

            switch (methodRef.FullName)
            {
            case "System.Type System.Type::GetTypeFromHandle(System.RuntimeTypeHandle)":
                if (arguments.Length == 1)
                {
                    if (typeHandleOnTypeOfPattern.IsMatch(arguments[0]))
                    {
                        invocationExpression.ReplaceWith(((MemberReferenceExpression)arguments[0]).Target);
                        return;
                    }
                }
                break;

            case "System.Reflection.FieldInfo System.Reflection.FieldInfo::GetFieldFromHandle(System.RuntimeFieldHandle)":
                if (arguments.Length == 1)
                {
                    MemberReferenceExpression mre = arguments[0] as MemberReferenceExpression;
                    if (mre != null && mre.MemberName == "FieldHandle" && mre.Target.Annotation <LdTokenAnnotation>() != null)
                    {
                        invocationExpression.ReplaceWith(mre.Target);
                        return;
                    }
                }
                break;

            case "System.Reflection.FieldInfo System.Reflection.FieldInfo::GetFieldFromHandle(System.RuntimeFieldHandle,System.RuntimeTypeHandle)":
                if (arguments.Length == 2)
                {
                    MemberReferenceExpression mre1 = arguments[0] as MemberReferenceExpression;
                    MemberReferenceExpression mre2 = arguments[1] as MemberReferenceExpression;
                    if (mre1 != null && mre1.MemberName == "FieldHandle" && mre1.Target.Annotation <LdTokenAnnotation>() != null)
                    {
                        if (mre2 != null && mre2.MemberName == "TypeHandle" && mre2.Target is TypeOfExpression)
                        {
                            Expression     oldArg = ((InvocationExpression)mre1.Target).Arguments.Single();
                            FieldReference field  = oldArg.Annotation <FieldReference>();
                            if (field != null)
                            {
                                AstType declaringType = ((TypeOfExpression)mre2.Target).Type.Detach();
                                oldArg.ReplaceWith(declaringType.Member(field.Name).WithAnnotation(field));
                                invocationExpression.ReplaceWith(mre1.Target);
                                return;
                            }
                        }
                    }
                }
                break;
            }

            BinaryOperatorType?bop = GetBinaryOperatorTypeFromMetadataName(methodRef.Name);

            if (bop != null && arguments.Length == 2)
            {
                invocationExpression.Arguments.Clear(); // detach arguments from invocationExpression
                invocationExpression.ReplaceWith(
                    new BinaryOperatorExpression(arguments[0], bop.Value, arguments[1]).WithAnnotation(methodRef)
                    );
                return;
            }
            UnaryOperatorType?uop = GetUnaryOperatorTypeFromMetadataName(methodRef.Name);

            if (uop != null && arguments.Length == 1)
            {
                arguments[0].Remove(); // detach argument
                invocationExpression.ReplaceWith(
                    new UnaryOperatorExpression(uop.Value, arguments[0]).WithAnnotation(methodRef)
                    );
                return;
            }
            if (methodRef.Name == "op_Explicit" && arguments.Length == 1)
            {
                arguments[0].Remove(); // detach argument
                invocationExpression.ReplaceWith(
                    arguments[0].CastTo(AstBuilder.ConvertType(methodRef.ReturnType, methodRef.MethodReturnType))
                    .WithAnnotation(methodRef)
                    );
                return;
            }
            if (methodRef.Name == "op_Implicit" && arguments.Length == 1)
            {
                invocationExpression.ReplaceWith(arguments[0]);
                return;
            }
            if (methodRef.Name == "op_True" && arguments.Length == 1 && invocationExpression.Role == Roles.Condition)
            {
                invocationExpression.ReplaceWith(arguments[0]);
                return;
            }

            return;
        }
Example #9
0
        public override object VisitInvocationExpression(InvocationExpression invocationExpression, object data)
        {
            base.VisitInvocationExpression(invocationExpression, data);

            MethodReference methodRef = invocationExpression.Annotation <MethodReference>();

            if (methodRef == null)
            {
                return(null);
            }
            var arguments = invocationExpression.Arguments.ToArray();

            // Reduce "String.Concat(a, b)" to "a + b"
            if (methodRef.Name == "Concat" && methodRef.DeclaringType.FullName == "System.String" && arguments.Length >= 2)
            {
                invocationExpression.Arguments.Clear();                 // detach arguments from invocationExpression
                Expression expr = arguments[0];
                for (int i = 1; i < arguments.Length; i++)
                {
                    expr = new BinaryOperatorExpression(expr, BinaryOperatorType.Add, arguments[i]);
                }
                invocationExpression.ReplaceWith(expr);
                return(null);
            }

            switch (methodRef.FullName)
            {
            case "System.Type System.Type::GetTypeFromHandle(System.RuntimeTypeHandle)":
                if (arguments.Length == 1)
                {
                    if (typeHandleOnTypeOfPattern.IsMatch(arguments[0]))
                    {
                        invocationExpression.ReplaceWith(((MemberReferenceExpression)arguments[0]).Target);
                        return(null);
                    }
                }
                break;
            }

            BinaryOperatorType?bop = GetBinaryOperatorTypeFromMetadataName(methodRef.Name);

            if (bop != null && arguments.Length == 2)
            {
                invocationExpression.Arguments.Clear();                 // detach arguments from invocationExpression
                invocationExpression.ReplaceWith(
                    new BinaryOperatorExpression(arguments[0], bop.Value, arguments[1]).WithAnnotation(methodRef)
                    );
                return(null);
            }
            UnaryOperatorType?uop = GetUnaryOperatorTypeFromMetadataName(methodRef.Name);

            if (uop != null && arguments.Length == 1)
            {
                arguments[0].Remove();                 // detach argument
                invocationExpression.ReplaceWith(
                    new UnaryOperatorExpression(uop.Value, arguments[0]).WithAnnotation(methodRef)
                    );
                return(null);
            }
            if (methodRef.Name == "op_Explicit" && arguments.Length == 1)
            {
                arguments[0].Remove();                 // detach argument
                invocationExpression.ReplaceWith(
                    arguments[0].CastTo(AstBuilder.ConvertType(methodRef.ReturnType, methodRef.MethodReturnType))
                    .WithAnnotation(methodRef)
                    );
                return(null);
            }
            if (methodRef.Name == "op_Implicit" && arguments.Length == 1)
            {
                invocationExpression.ReplaceWith(arguments[0]);
                return(null);
            }
            if (methodRef.Name == "op_True" && arguments.Length == 1 && invocationExpression.Role == AstNode.Roles.Condition)
            {
                invocationExpression.ReplaceWith(arguments[0]);
                return(null);
            }

            return(null);
        }
        void ProcessInvocationExpression(InvocationExpression invocationExpression)
        {
            var method = invocationExpression.GetSymbol() as IMethod;

            if (method == null)
            {
                return;
            }
            var arguments = invocationExpression.Arguments.ToArray();

            // Reduce "String.Concat(a, b)" to "a + b"
            if (IsStringConcat(method) && CheckArgumentsForStringConcat(arguments))
            {
                bool isInExpressionTree = invocationExpression.Ancestors.OfType <LambdaExpression>().Any(
                    lambda => lambda.Annotation <IL.ILFunction>()?.Kind == IL.ILFunctionKind.ExpressionTree);
                Expression expr = arguments[0].Detach();
                if (!isInExpressionTree)
                {
                    expr = RemoveRedundantToStringInConcat(expr, method, isLastArgument: false).Detach();
                }
                for (int i = 1; i < arguments.Length; i++)
                {
                    var arg = arguments[i].Detach();
                    if (!isInExpressionTree)
                    {
                        arg = RemoveRedundantToStringInConcat(arg, method, isLastArgument: i == arguments.Length - 1).Detach();
                    }
                    expr = new BinaryOperatorExpression(expr, BinaryOperatorType.Add, arg);
                }
                expr.CopyAnnotationsFrom(invocationExpression);
                invocationExpression.ReplaceWith(expr);
                return;
            }

            switch (method.FullName)
            {
            case "System.Type.GetTypeFromHandle":
                if (arguments.Length == 1)
                {
                    if (typeHandleOnTypeOfPattern.IsMatch(arguments[0]))
                    {
                        Expression target = ((MemberReferenceExpression)arguments[0]).Target;
                        target.CopyInstructionsFrom(invocationExpression);
                        invocationExpression.ReplaceWith(target);
                        return;
                    }
                }
                break;

            /*
             * case "System.Reflection.FieldInfo.GetFieldFromHandle":
             * // TODO : This is dead code because LdTokenAnnotation is not added anywhere:
             * if (arguments.Length == 1) {
             *      MemberReferenceExpression mre = arguments[0] as MemberReferenceExpression;
             *      if (mre != null && mre.MemberName == "FieldHandle" && mre.Target.Annotation<LdTokenAnnotation>() != null) {
             *              invocationExpression.ReplaceWith(mre.Target);
             *              return;
             *      }
             * } else if (arguments.Length == 2) {
             *      MemberReferenceExpression mre1 = arguments[0] as MemberReferenceExpression;
             *      MemberReferenceExpression mre2 = arguments[1] as MemberReferenceExpression;
             *      if (mre1 != null && mre1.MemberName == "FieldHandle" && mre1.Target.Annotation<LdTokenAnnotation>() != null) {
             *              if (mre2 != null && mre2.MemberName == "TypeHandle" && mre2.Target is TypeOfExpression) {
             *                      Expression oldArg = ((InvocationExpression)mre1.Target).Arguments.Single();
             *                      FieldReference field = oldArg.Annotation<FieldReference>();
             *                      if (field != null) {
             *                              AstType declaringType = ((TypeOfExpression)mre2.Target).Type.Detach();
             *                              oldArg.ReplaceWith(new MemberReferenceExpression(new TypeReferenceExpression(declaringType), field.Name).CopyAnnotationsFrom(oldArg));
             *                              invocationExpression.ReplaceWith(mre1.Target);
             *                              return;
             *                      }
             *              }
             *      }
             * }
             * break;
             */
            case "System.Activator.CreateInstance":
                if (arguments.Length == 0 && method.TypeArguments.Count == 1 && IsInstantiableTypeParameter(method.TypeArguments[0]))
                {
                    invocationExpression.ReplaceWith(new ObjectCreateExpression(context.TypeSystemAstBuilder.ConvertType(method.TypeArguments.First())));
                }
                break;
            }

            BinaryOperatorType?bop = GetBinaryOperatorTypeFromMetadataName(method.Name);

            if (bop != null && arguments.Length == 2)
            {
                invocationExpression.Arguments.Clear();                 // detach arguments from invocationExpression
                invocationExpression.ReplaceWith(
                    new BinaryOperatorExpression(
                        arguments[0].UnwrapInDirectionExpression(),
                        bop.Value,
                        arguments[1].UnwrapInDirectionExpression()
                        ).CopyAnnotationsFrom(invocationExpression)
                    );
                return;
            }
            UnaryOperatorType?uop = GetUnaryOperatorTypeFromMetadataName(method.Name);

            if (uop != null && arguments.Length == 1)
            {
                if (uop == UnaryOperatorType.Increment || uop == UnaryOperatorType.Decrement)
                {
                    // `op_Increment(a)` is not equivalent to `++a`,
                    // because it doesn't assign the incremented value to a.
                    if (method.DeclaringType.IsKnownType(KnownTypeCode.Decimal))
                    {
                        // Legacy csc optimizes "d + 1m" to "op_Increment(d)",
                        // so reverse that optimization here:
                        invocationExpression.ReplaceWith(
                            new BinaryOperatorExpression(
                                arguments[0].UnwrapInDirectionExpression().Detach(),
                                (uop == UnaryOperatorType.Increment ? BinaryOperatorType.Add : BinaryOperatorType.Subtract),
                                new PrimitiveExpression(1m)
                                ).CopyAnnotationsFrom(invocationExpression)
                            );
                    }
                    return;
                }
                arguments[0].Remove();                 // detach argument
                invocationExpression.ReplaceWith(
                    new UnaryOperatorExpression(uop.Value, arguments[0].UnwrapInDirectionExpression()).CopyAnnotationsFrom(invocationExpression)
                    );
                return;
            }
            if (method.Name == "op_Explicit" && arguments.Length == 1)
            {
                arguments[0].Remove();                 // detach argument
                invocationExpression.ReplaceWith(
                    new CastExpression(context.TypeSystemAstBuilder.ConvertType(method.ReturnType), arguments[0].UnwrapInDirectionExpression())
                    .CopyAnnotationsFrom(invocationExpression)
                    );
                return;
            }
            if (method.Name == "op_True" && arguments.Length == 1 && invocationExpression.Role == Roles.Condition)
            {
                invocationExpression.ReplaceWith(arguments[0].UnwrapInDirectionExpression());
                return;
            }

            return;
        }
Example #11
0
        void ProcessInvocationExpression(InvocationExpression invocationExpression)
        {
            var method = invocationExpression.GetSymbol() as IMethod;

            if (method == null)
            {
                return;
            }
            var arguments = invocationExpression.Arguments.ToArray();

            // Reduce "String.Concat(a, b)" to "a + b"
            if (method.Name == "Concat" && method.DeclaringType.FullName == "System.String" && CheckArgumentsForStringConcat(arguments))
            {
                invocationExpression.Arguments.Clear();                 // detach arguments from invocationExpression
                Expression expr = arguments[0];
                for (int i = 1; i < arguments.Length; i++)
                {
                    expr = new BinaryOperatorExpression(expr, BinaryOperatorType.Add, arguments[i]);
                }
                invocationExpression.ReplaceWith(expr);
                return;
            }

            switch (method.FullName)
            {
            case "System.Type.GetTypeFromHandle":
                if (arguments.Length == 1)
                {
                    if (typeHandleOnTypeOfPattern.IsMatch(arguments[0]))
                    {
                        Expression target = ((MemberReferenceExpression)arguments[0]).Target;
                        target.CopyInstructionsFrom(invocationExpression);
                        invocationExpression.ReplaceWith(target);
                        return;
                    }
                }
                break;

            case "System.Reflection.FieldInfo.GetFieldFromHandle":
                if (arguments.Length == 1)
                {
                    MemberReferenceExpression mre = arguments[0] as MemberReferenceExpression;
                    if (mre != null && mre.MemberName == "FieldHandle" && mre.Target.Annotation <LdTokenAnnotation>() != null)
                    {
                        invocationExpression.ReplaceWith(mre.Target);
                        return;
                    }
                }
                else if (arguments.Length == 2)
                {
                    MemberReferenceExpression mre1 = arguments[0] as MemberReferenceExpression;
                    MemberReferenceExpression mre2 = arguments[1] as MemberReferenceExpression;
                    if (mre1 != null && mre1.MemberName == "FieldHandle" && mre1.Target.Annotation <LdTokenAnnotation>() != null)
                    {
                        if (mre2 != null && mre2.MemberName == "TypeHandle" && mre2.Target is TypeOfExpression)
                        {
                            Expression     oldArg = ((InvocationExpression)mre1.Target).Arguments.Single();
                            FieldReference field  = oldArg.Annotation <FieldReference>();
                            if (field != null)
                            {
                                AstType declaringType = ((TypeOfExpression)mre2.Target).Type.Detach();
                                oldArg.ReplaceWith(new MemberReferenceExpression(new TypeReferenceExpression(declaringType), field.Name).CopyAnnotationsFrom(oldArg));
                                invocationExpression.ReplaceWith(mre1.Target);
                                return;
                            }
                        }
                    }
                }
                break;

            case "System.Activator.CreateInstance":
                if (method.TypeArguments.Count == 1 && arguments.Length == 0 && method.TypeArguments[0].Kind == TypeKind.TypeParameter)
                {
                    invocationExpression.ReplaceWith(new ObjectCreateExpression(context.TypeSystemAstBuilder.ConvertType(method.TypeArguments.First())));
                }
                break;
            }

            BinaryOperatorType?bop = GetBinaryOperatorTypeFromMetadataName(method.Name);

            if (bop != null && arguments.Length == 2)
            {
                invocationExpression.Arguments.Clear();                 // detach arguments from invocationExpression
                invocationExpression.ReplaceWith(
                    new BinaryOperatorExpression(arguments[0], bop.Value, arguments[1]).CopyAnnotationsFrom(invocationExpression)
                    );
                return;
            }
            UnaryOperatorType?uop = GetUnaryOperatorTypeFromMetadataName(method.Name);

            if (uop != null && arguments.Length == 1)
            {
                arguments[0].Remove();                 // detach argument
                invocationExpression.ReplaceWith(
                    new UnaryOperatorExpression(uop.Value, arguments[0]).CopyAnnotationsFrom(invocationExpression)
                    );
                return;
            }
            if (method.Name == "op_Explicit" && arguments.Length == 1)
            {
                arguments[0].Remove();                 // detach argument
                invocationExpression.ReplaceWith(
                    new CastExpression(context.TypeSystemAstBuilder.ConvertType(method.ReturnType), arguments[0])
                    .CopyAnnotationsFrom(invocationExpression)
                    );
                return;
            }
            if (method.Name == "op_Implicit" && arguments.Length == 1)
            {
                invocationExpression.ReplaceWith(arguments[0]);
                return;
            }
            if (method.Name == "op_True" && arguments.Length == 1 && invocationExpression.Role == Roles.Condition)
            {
                invocationExpression.ReplaceWith(arguments[0]);
                return;
            }

            return;
        }
Example #12
0
			public override void VisitInvocationExpression (InvocationExpression invocationExpression)
			{
				base.VisitInvocationExpression (invocationExpression);

				var memberReferenceExpression = invocationExpression.Target as MemberReferenceExpression;

				if (memberReferenceExpression == null)
					return;

				var t = GetTypeRef (memberReferenceExpression.Target);
				if (t == null)
					return;

				HashSet<string> repls = null;
				string newTypeName = null;
				if (t.FullName == "System.Object") {
					repls = objectRepls;
					newTypeName = "NObject";
				} else if (t.FullName == "System.String") {
					repls = stringRepls;
					newTypeName = "NString";
				} else if (t.FullName == "System.Boolean") {
					repls = boolRepls;
					newTypeName = "NBoolean";
				} else if (t != null && t.IsPrimitive) {
					repls = numberRepls;
					newTypeName = "NNumber";
				}
				if (repls != null && repls.Contains (memberReferenceExpression.MemberName)) {
					if (memberReferenceExpression.MemberName == "Equals") {
						var left = memberReferenceExpression.Target;
						var right = invocationExpression.Arguments.First ();
						left.Remove ();
						right.Remove ();
						invocationExpression.ReplaceWith (new BinaryOperatorExpression (left, BinaryOperatorType.Equality, right));
					} else {
						var newName = memberReferenceExpression.MemberName;
						if (newTypeName == "NObject") {
							newName = "Generic" + newName;
						}
						var n = new InvocationExpression (
							        new MemberReferenceExpression (
								        new TypeReferenceExpression (new SimpleType (newTypeName)), 
								        newName),
							new Expression[] { memberReferenceExpression.Target.Clone () }
								.Concat (invocationExpression.Arguments.Select (x => x.Clone ())));

						var td = t.Resolve ();
						var meth = td.Methods.First (x => x.Name == memberReferenceExpression.MemberName);
						n.AddAnnotation (meth.ReturnType);
						invocationExpression.ReplaceWith (n);
					}
				}
			}
Example #13
0
        void ProcessInvocationExpression(InvocationExpression invocationExpression)
        {
            var method = invocationExpression.GetSymbol() as IMethod;

            if (method == null)
            {
                return;
            }
            var arguments = invocationExpression.Arguments.ToArray();

            // Reduce "String.Concat(a, b)" to "a + b"
            if (method.Name == "Concat" && method.DeclaringType.FullName == "System.String" && CheckArgumentsForStringConcat(arguments))
            {
                invocationExpression.Arguments.Clear();                 // detach arguments from invocationExpression
                Expression expr = arguments[0];
                for (int i = 1; i < arguments.Length; i++)
                {
                    expr = new BinaryOperatorExpression(expr, BinaryOperatorType.Add, arguments[i]);
                }
                expr.CopyAnnotationsFrom(invocationExpression);
                invocationExpression.ReplaceWith(expr);
                return;
            }

            switch (method.FullName)
            {
            case "System.Type.GetTypeFromHandle":
                if (arguments.Length == 1)
                {
                    if (typeHandleOnTypeOfPattern.IsMatch(arguments[0]))
                    {
                        Expression target = ((MemberReferenceExpression)arguments[0]).Target;
                        target.CopyInstructionsFrom(invocationExpression);
                        invocationExpression.ReplaceWith(target);
                        return;
                    }
                }
                break;

            case "System.Reflection.FieldInfo.GetFieldFromHandle":
                if (arguments.Length == 1)
                {
                    MemberReferenceExpression mre = arguments[0] as MemberReferenceExpression;
                    if (mre != null && mre.MemberName == "FieldHandle" && mre.Target.Annotation <LdTokenAnnotation>() != null)
                    {
                        invocationExpression.ReplaceWith(mre.Target);
                        return;
                    }
                }
                else if (arguments.Length == 2)
                {
                    MemberReferenceExpression mre1 = arguments[0] as MemberReferenceExpression;
                    MemberReferenceExpression mre2 = arguments[1] as MemberReferenceExpression;
                    if (mre1 != null && mre1.MemberName == "FieldHandle" && mre1.Target.Annotation <LdTokenAnnotation>() != null)
                    {
                        if (mre2 != null && mre2.MemberName == "TypeHandle" && mre2.Target is TypeOfExpression)
                        {
                            Expression     oldArg = ((InvocationExpression)mre1.Target).Arguments.Single();
                            FieldReference field  = oldArg.Annotation <FieldReference>();
                            if (field != null)
                            {
                                AstType declaringType = ((TypeOfExpression)mre2.Target).Type.Detach();
                                oldArg.ReplaceWith(new MemberReferenceExpression(new TypeReferenceExpression(declaringType), field.Name).CopyAnnotationsFrom(oldArg));
                                invocationExpression.ReplaceWith(mre1.Target);
                                return;
                            }
                        }
                    }
                }
                break;

            case "System.Activator.CreateInstance":
                if (arguments.Length == 0 && method.TypeArguments.Count == 1 && IsInstantiableTypeParameter(method.TypeArguments[0]))
                {
                    invocationExpression.ReplaceWith(new ObjectCreateExpression(context.TypeSystemAstBuilder.ConvertType(method.TypeArguments.First())));
                }
                break;

            case "System.String.Format":
                if (context.Settings.StringInterpolation && arguments.Length > 1 &&
                    arguments[0] is PrimitiveExpression stringExpression && stringExpression.Value is string &&
                    arguments.Skip(1).All(a => !a.DescendantsAndSelf.OfType <PrimitiveExpression>().Any(p => p.Value is string)))
                {
                    var tokens = new List <(TokenKind, int, string)>();
                    int i      = 0;
                    foreach (var(kind, data) in TokenizeFormatString((string)stringExpression.Value))
                    {
                        int index;
                        switch (kind)
                        {
                        case TokenKind.Error:
                            return;

                        case TokenKind.String:
                            tokens.Add((kind, -1, data));
                            break;

                        case TokenKind.Argument:
                            if (!int.TryParse(data, out index) || index != i)
                            {
                                return;
                            }
                            i++;
                            tokens.Add((kind, index, null));
                            break;

                        case TokenKind.ArgumentWithFormat:
                            string[] arg = data.Split(new[] { ':' }, 2);
                            if (arg.Length != 2 || arg[1].Length == 0)
                            {
                                return;
                            }
                            if (!int.TryParse(arg[0], out index) || index != i)
                            {
                                return;
                            }
                            i++;
                            tokens.Add((kind, index, arg[1]));
                            break;
Example #14
0
			public override void VisitInvocationExpression (InvocationExpression invocationExpression)
			{
				base.VisitInvocationExpression (invocationExpression);

				var mr = invocationExpression.Target as MemberReferenceExpression;
				if (mr == null)
					return;

				var target = mr.Target;
				var td = GetTypeDef (target);
				if (td == null || !td.IsEnum)
					return;

				if (mr.MemberName == "GetHashCode") {

					target.Remove ();
					invocationExpression.ReplaceWith (target);

				}
				else if (mr.MemberName == "ToString") {

					target.Remove ();
					var idx = new IndexerExpression (
						          new TypeReferenceExpression (new SimpleType (td.Name)),
						          target);
					invocationExpression.ReplaceWith (idx);

				}
			}
Example #15
0
        internal static void ProcessInvocationExpression(InvocationExpression invocationExpression, StringBuilder sb)
        {
            IMethod methodRef = invocationExpression.Annotation <IMethod>();

            if (methodRef == null)
            {
                return;
            }
            var arguments = invocationExpression.Arguments.ToArray();

            // Reduce "String.Concat(a, b)" to "a + b"
            if (methodRef.Name == "Concat" && methodRef.DeclaringType != null && arguments.Length >= 2 && methodRef.DeclaringType.FullName == "System.String")
            {
                invocationExpression.Arguments.Clear();                 // detach arguments from invocationExpression
                Expression expr = arguments[0];
                for (int i = 1; i < arguments.Length; i++)
                {
                    expr = new BinaryOperatorExpression(expr, BinaryOperatorType.Add, arguments[i]);
                }
                invocationExpression.ReplaceWith(expr);
                expr.AddAnnotation(invocationExpression.GetAllRecursiveILRanges());
                return;
            }

            bool isSupportedType = CheckType(methodRef.DeclaringType, systemString, typeString) ||
                                   CheckType(methodRef.DeclaringType, systemReflectionString, fieldInfoString);

            switch (isSupportedType ? methodRef.Name.String : string.Empty)
            {
            case "GetTypeFromHandle":
                if (arguments.Length == 1 && methodRef.FullName == "System.Type System.Type::GetTypeFromHandle(System.RuntimeTypeHandle)")
                {
                    if (typeHandleOnTypeOfPattern.IsMatch(arguments[0]))
                    {
                        invocationExpression.ReplaceWith(((MemberReferenceExpression)arguments[0]).Target
                                                         .WithAnnotation(invocationExpression.GetAllRecursiveILRanges()));
                        return;
                    }
                }
                break;

            case "GetFieldFromHandle":
                if (arguments.Length == 1 && methodRef.FullName == "System.Reflection.FieldInfo System.Reflection.FieldInfo::GetFieldFromHandle(System.RuntimeFieldHandle)")
                {
                    MemberReferenceExpression mre = arguments[0] as MemberReferenceExpression;
                    if (mre != null && mre.MemberName == "FieldHandle" && mre.Target.Annotation <LdTokenAnnotation>() != null)
                    {
                        invocationExpression.ReplaceWith(mre.Target
                                                         .WithAnnotation(invocationExpression.GetAllRecursiveILRanges()));
                        return;
                    }
                }
                else if (arguments.Length == 2 && methodRef.FullName == "System.Reflection.FieldInfo System.Reflection.FieldInfo::GetFieldFromHandle(System.RuntimeFieldHandle,System.RuntimeTypeHandle)")
                {
                    MemberReferenceExpression mre1 = arguments[0] as MemberReferenceExpression;
                    MemberReferenceExpression mre2 = arguments[1] as MemberReferenceExpression;
                    if (mre1 != null && mre1.MemberName == "FieldHandle" && mre1.Target.Annotation <LdTokenAnnotation>() != null)
                    {
                        if (mre2 != null && mre2.MemberName == "TypeHandle" && mre2.Target is TypeOfExpression)
                        {
                            Expression oldArg = ((InvocationExpression)mre1.Target).Arguments.Single();
                            IField     field  = oldArg.Annotation <IField>();
                            if (field != null)
                            {
                                var     ilRanges      = invocationExpression.GetAllRecursiveILRanges();
                                AstType declaringType = ((TypeOfExpression)mre2.Target).Type.Detach();
                                oldArg.ReplaceWith(declaringType.Member(field.Name, field).WithAnnotation(field));
                                invocationExpression.ReplaceWith(mre1.Target.WithAnnotation(ilRanges));
                                return;
                            }
                        }
                    }
                }
                break;
            }

            BinaryOperatorType?bop = GetBinaryOperatorTypeFromMetadataName(methodRef.Name);

            if (bop != null && arguments.Length == 2)
            {
                invocationExpression.Arguments.Clear();                 // detach arguments from invocationExpression
                invocationExpression.ReplaceWith(
                    new BinaryOperatorExpression(arguments[0], bop.Value, arguments[1]).WithAnnotation(methodRef)
                    .WithAnnotation(invocationExpression.GetAllRecursiveILRanges())
                    );
                return;
            }
            UnaryOperatorType?uop = GetUnaryOperatorTypeFromMetadataName(methodRef.Name);

            if (uop != null && arguments.Length == 1)
            {
                arguments[0].Remove();                 // detach argument
                invocationExpression.ReplaceWith(
                    new UnaryOperatorExpression(uop.Value, arguments[0]).WithAnnotation(methodRef)
                    .WithAnnotation(invocationExpression.GetAllRecursiveILRanges())
                    );
                return;
            }
            if (methodRef.Name == "op_Explicit" && arguments.Length == 1)
            {
                arguments[0].Remove();                 // detach argument
                invocationExpression.ReplaceWith(
                    arguments[0].CastTo(AstBuilder.ConvertType(methodRef.MethodSig.GetRetType(), sb))
                    .WithAnnotation(methodRef)
                    .WithAnnotation(invocationExpression.GetAllRecursiveILRanges())
                    );
                return;
            }
            if (methodRef.Name == "op_Implicit" && arguments.Length == 1)
            {
                invocationExpression.ReplaceWith(arguments[0].WithAnnotation(invocationExpression.GetAllRecursiveILRanges()));
                return;
            }
            if (methodRef.Name == "op_True" && arguments.Length == 1 && invocationExpression.Role == Roles.Condition)
            {
                invocationExpression.ReplaceWith(arguments[0].WithAnnotation(invocationExpression.GetAllRecursiveILRanges()));
                return;
            }

            return;
        }
Example #16
0
			public override void VisitInvocationExpression (InvocationExpression invocationExpression)
			{
				base.VisitInvocationExpression (invocationExpression);

				var mr = invocationExpression.Target as MemberReferenceExpression;
				if (mr == null)
					return;

				if (mr.MemberName != "Equals")
					return;

				var m = invocationExpression.Annotation<MemberReference> ();
				if (m.DeclaringType.FullName != "System.Object")
					return;

				var i = new InvocationExpression (
					        new MemberReferenceExpression (new TypeReferenceExpression (new SimpleType ("NObject")), "GenericEquals"),
					mr.Target.Clone (), invocationExpression.Arguments.First ().Clone ());

				invocationExpression.ReplaceWith (i);
			}
Example #17
0
			public override void VisitInvocationExpression (InvocationExpression invocationExpression)
			{
				base.VisitInvocationExpression (invocationExpression);

				var hasRefs = invocationExpression.Arguments.OfType<DirectionExpression> ().Any ();

				if (hasRefs) {

					var args = invocationExpression.Arguments.OfType<DirectionExpression> ().ToList ();

					var target = invocationExpression.Target;

					var lblock = new BlockStatement {

					};

					for (int i = 0; i < args.Count; i++) {
						var a = args [i];
						var vname = "_p" + i;
						var va = new VariableDeclarationStatement (AstType.Null, vname, new ArrayCreateExpression {
							Initializer = new ArrayInitializerExpression (a.Expression.Clone ())
						});
						a.ReplaceWith (new IdentifierExpression (vname));
						lblock.Add (va);
					}
					var rname = "_r";
					var ra = new VariableDeclarationStatement (AstType.Null, rname, invocationExpression.Clone ());
					lblock.Add (ra);
					for (int i = 0; i < args.Count; i++) {
						var a = args [i];
						var vname = "_p" + i;
						var va = new AssignmentExpression (a.Expression.Clone (), 
							new IndexerExpression (
								new IdentifierExpression (vname), new PrimitiveExpression (0)));
						lblock.Add (va);
					}
					lblock.Add (new ReturnStatement (new IdentifierExpression (rname)));

					var lambda = new LambdaExpression {
						Body = lblock,
					};

					var ilambda = new InvocationExpression (lambda);

					invocationExpression.ReplaceWith (ilambda);
				}
			}
        public override object VisitInvocationExpression(InvocationExpression invocationExpression, object data)
        {
            var parentInvocationExpression = invocationExpression.Parent as InvocationExpression;

            if (parentInvocationExpression == null)
            {
                return(base.VisitInvocationExpression(invocationExpression, data));
            }

            var target = invocationExpression.Target as MemberReferenceExpression;

            if (target == null)
            {
                return(base.VisitInvocationExpression(invocationExpression, data));
            }

            switch (target.MemberName)
            {
            case "Range":
                var identifierExpression = target.Target as IdentifierExpression;
                if (identifierExpression != null && identifierExpression.Identifier == "Enumerable")
                {
                    var parentTarget = parentInvocationExpression.Target as MemberReferenceExpression;

                    if (parentTarget == null)
                    {
                        break;
                    }

                    if (parentTarget.MemberName == "ToDictionary" &&
                        parentInvocationExpression.Arguments.Count == 3 &&
                        parentInvocationExpression.Arguments.First() == invocationExpression)
                    {
                        // support for Enumerable.Range(x, y).ToDictionary(k => k, k => k) which is
                        // Enumerable.ToDictionary(Enumerable.Range(x, y), k => k, k => k) in fact

                        var toDictArguments = parentInvocationExpression.Arguments.Skip(1);     // skip first arg which is current invocationExpression

                        var containsDynamics = toDictArguments.All(x =>
                        {
                            var castExpression = x as CastExpression;
                            if (castExpression == null)
                            {
                                return(false);
                            }
                            var type = castExpression.Type as SimpleType;
                            if (type == null)
                            {
                                return(false);
                            }
                            return(type.Identifier.Contains("dynamic"));
                        });

                        if (containsDynamics == false)
                        {
                            break;
                        }

                        // convert Enumerable.Range(x, y) to Enumerable.Range(x, y).Cast<dynamic>()
                        var enumerableRange = invocationExpression.Clone();

                        var castToDynamic = new MemberReferenceExpression(enumerableRange, "Cast", new AstType[] { new SimpleType("dynamic") });

                        var dynamicEnumerable = new InvocationExpression(castToDynamic);

                        invocationExpression.ReplaceWith(dynamicEnumerable);
                    }
                }
                break;
            }

            return(base.VisitInvocationExpression(invocationExpression, data));
        }
Example #19
0
        public override void VisitInvocationExpression(InvocationExpression e)
        {
            var md = e.Annotation<MethodDefinition>();
            if (md != null && (md.IsGetter || md.IsSetter))
            {
                var p = md.DeclaringType.Properties.FirstOrDefault(x => x.GetMethod == md || x.SetMethod == md);
                if (p != null)
                {
                    // 转换为属性访问
                    var target = (e.Target as MemberReferenceExpression).Target;
                    if (p.IsIndexer())
                    {
                        IndexerExpression ie = new IndexerExpression(target.Detach()).WithAnnotation(p);
                        e.Arguments.MoveTo(ie.Arguments);
                        e.ReplaceWith(ie);
                    }
                    else
                    {
                        //MemberReferenceExpression mre = new MemberReferenceExpression(target.Detach(), p.Name).WithAnnotation(p);

                    }
                }
            }

            //[CompilerGenerated]
            //private sealed class C_e_5
            //{
            //    public Action f_1_E2DC5B04;
            //    public void M_1_void(object x)
            //    {
            //        this.f_1_E2DC5B04();
            //    }
            //}
            //
            //public ActionCommand(Action execute)
            //{
            //    Action<object> action = null;
            //    ActionCommand.C_e_5 c_e_ = new ActionCommand.C_e_5();
            //    c_e_.f_1_E2DC5B04 = execute;
            //    if (action == null)
            //    {
            //        action = new Action<object>(c_e_.M_1_void);
            //    }
            //    base..ctor(action);
            //}
            //
            //====>
            //public ActionCommand(Action execute) : base(x=>execute())
            //{
            //}



            base.VisitInvocationExpression(e);
        }