public IEnumerable<CodeAction> GetActions(RefactoringContext context)
        {
            if (!context.IsSomethingSelected) {
                yield break;
            }
            var pexpr = context.GetNode<PrimitiveExpression>();
            if (pexpr == null || !(pexpr.Value is string)) {
                yield break;
            }
            if (pexpr.LiteralValue.StartsWith("@", StringComparison.Ordinal)) {
                if (!(pexpr.StartLocation < new TextLocation(context.Location.Line, context.Location.Column - 1) && new TextLocation(context.Location.Line, context.Location.Column + 1) < pexpr.EndLocation)) {
                    yield break;
                }
            } else {
                if (!(pexpr.StartLocation < context.Location && context.Location < pexpr.EndLocation)) {
                    yield break;
                }
            }

            yield return new CodeAction (context.TranslateString("Introduce format item"), script => {
                var invocation = context.GetNode<InvocationExpression>();
                if (invocation != null && invocation.Target.IsMatch(PrototypeFormatReference)) {
                    AddFormatCallToInvocation(context, script, pexpr, invocation);
                    return;
                }

                var arg = CreateFormatArgument(context);
                var newInvocation = new InvocationExpression (PrototypeFormatReference.Clone()) {
                    Arguments = { CreateFormatString(context, pexpr, 0), arg }
                };

                script.Replace(pexpr, newInvocation);
                script.Select(arg);
            });
        }
Exemplo n.º 2
0
        public static bool IsConditionallyRemoved(InvocationExpression invocationExpression, IEntity entity)
 		{
            if (entity == null)
            {
                return false;
            }
 			var result = new List<string>();
 			foreach (var a in entity.Attributes)
 			{
 				var type = a.AttributeType.GetDefinition();
 				if (type != null && type.FullName.Equals("System.Diagnostics.ConditionalAttribute", StringComparison.Ordinal))
                {
 					if (a.PositionalArguments.Count > 0)
                    {
 						var symbol = a.PositionalArguments[0].ConstantValue as string;
                        if (symbol != null)
                        {
                            result.Add(symbol);
                        }
 					}
 				}
 			}

            if (result.Count > 0)
            {
                var syntaxTree = invocationExpression.GetParent<SyntaxTree>();
                if (syntaxTree != null)
                {
                    return !result.Intersect(syntaxTree.ConditionalSymbols).Any();    
                }
            }

 			return false;
 		}
Exemplo n.º 3
0
            public override void VisitInvocationExpression(InvocationExpression invocationExpression)
            {
                base.VisitInvocationExpression(invocationExpression);

                // Speed up the inspector by discarding some invocations early
                var hasEligibleArgument = invocationExpression.Arguments.Any(argument => {
                    var primitiveArg = argument as PrimitiveExpression;
                    return primitiveArg != null && primitiveArg.Value is string;
                });
                if (!hasEligibleArgument)
                    return;

                var invocationResolveResult = context.Resolve(invocationExpression) as CSharpInvocationResolveResult;
                if (invocationResolveResult == null)
                    return;
                Expression formatArgument;
                IList<Expression> formatArguments;
                TextLocation formatStart;
                if (!FormatStringHelper.TryGetFormattingParameters(invocationResolveResult, invocationExpression,
                                                                   out formatArgument, out formatStart, out formatArguments, null)) {
                    return;
                }
                var primitiveArgument = formatArgument as PrimitiveExpression;
                if (primitiveArgument == null || !(primitiveArgument.Value is string))
                    return;
                var format = (string)primitiveArgument.Value;
                var parsingResult = context.ParseFormatString(format);
                CheckSegments(parsingResult.Segments, formatStart, formatArguments, invocationExpression);
            }
Exemplo n.º 4
0
        private static void AssertInvokeIsOptimized(InvocationExpression expr, Expression expression, IReadOnlyList<Expression> args)
        {
            var n = args.Count;

            var updated = Update(expr);
            var visited = Visit(expr);

            foreach (var node in new[] { expr, updated, visited })
            {
                Assert.Same(expression, node.Expression);

                AssertInvocation(n, node);

                var argProvider = node as IArgumentProvider;
                Assert.NotNull(argProvider);

                Assert.Equal(n, argProvider.ArgumentCount);

                if (node != visited) // our visitor clones argument nodes
                {
                    for (var i = 0; i < n; i++)
                    {
                        Assert.Same(args[i], argProvider.GetArgument(i));
                        Assert.Same(args[i], node.Arguments[i]);
                    }
                }
            }
        }
            public override void VisitInvocationExpression(InvocationExpression anyInvoke)
            {
                base.VisitInvocationExpression (anyInvoke);

                var match = pattern.Match (anyInvoke);
                if (!match.Success)
                    return;

                var anyResolve = ctx.Resolve (anyInvoke) as InvocationResolveResult;
                if (anyResolve == null || anyResolve.Member.FullName != "System.Linq.Enumerable.Any")
                    return;
                var whereInvoke = match.Get<InvocationExpression> ("whereInvoke").Single ();
                var whereResolve = ctx.Resolve (whereInvoke) as InvocationResolveResult;
                if (whereResolve == null || whereResolve.Member.FullName != "System.Linq.Enumerable.Where")
                    return;
                if (whereResolve.Member.Parameters.Count != 2)
                    return;
                var predResolve = whereResolve.Member.Parameters [1];
                if (predResolve.Type.TypeParameterCount != 2)
                    return;

                AddIssue (anyInvoke, "Redundant Where() call with predicate followed by Any()", script => {
                    var arg = whereInvoke.Arguments.Single ().Clone ();
                    var target = match.Get<Expression> ("target").Single ().Clone ();
                    script.Replace (anyInvoke, new InvocationExpression (new MemberReferenceExpression (target, "Any"), arg));
                });
            }
Exemplo n.º 6
0
		static IEnumerable<IType> GetAllValidTypesFromInvocation(CSharpAstResolver resolver, InvocationExpression invoke, AstNode parameter)
		{
			int index = GetArgumentIndex(invoke.Arguments, parameter);
			if (index < 0)
				yield break;

			var targetResult = resolver.Resolve(invoke.Target) as MethodGroupResolveResult;
			if (targetResult != null) {
				foreach (var method in targetResult.Methods) {
					if (index < method.Parameters.Count) {
						if (method.Parameters [index].IsParams) {
							var arrayType = method.Parameters [index].Type as ArrayType;
							if (arrayType != null)
								yield return arrayType.ElementType;
						}

						yield return method.Parameters [index].Type;
					}
				}
				foreach (var extMethods in targetResult.GetExtensionMethods ()) {
					foreach (var extMethod in extMethods) {
						if (index + 1 < extMethod.Parameters.Count) {
							if (extMethod.Parameters [index + 1].IsParams) {
								var arrayType = extMethod.Parameters [index + 1].Type as ArrayType;
								if (arrayType != null)
									yield return arrayType.ElementType;
							}

							yield return extMethod.Parameters [index + 1].Type;
						}
					}
				}
			}
		}
			public override void VisitInvocationExpression (InvocationExpression anyInvoke)
			{
				base.VisitInvocationExpression (anyInvoke);
				
				var match = pattern.Match (anyInvoke);
				if (!match.Success)
					return;
				
				var anyResolve = ctx.Resolve (anyInvoke) as InvocationResolveResult;
				if (anyResolve == null || !HasPredicateVersion(anyResolve.Member))
					return;
				var whereInvoke = match.Get<InvocationExpression> ("whereInvoke").Single ();
				var whereResolve = ctx.Resolve (whereInvoke) as InvocationResolveResult;
				if (whereResolve == null || whereResolve.Member.Name != "Where" || !IsQueryExtensionClass(whereResolve.Member.DeclaringTypeDefinition))
					return;
				if (whereResolve.Member.Parameters.Count != 2)
					return;
				var predResolve = whereResolve.Member.Parameters [1];
				if (predResolve.Type.TypeParameterCount != 2)
					return;
				
				AddIssue (
					anyInvoke, string.Format("Redundant Where() call with predicate followed by {0}()", anyResolve.Member.Name),
				    script => {
						var arg = whereInvoke.Arguments.Single ().Clone ();
						var target = match.Get<Expression> ("target").Single ().Clone ();
						script.Replace (anyInvoke, new InvocationExpression (new MemberReferenceExpression (target, anyResolve.Member.Name), arg));
					});
			}
Exemplo n.º 8
0
		public static bool TryGetFormattingParameters(CSharpInvocationResolveResult invocationResolveResult, InvocationExpression invocationExpression,
		                                     		  out Expression formatArgument, out TextLocation formatStart, out IList<Expression> arguments,
		                                              Func<IParameter, Expression, bool> argumentFilter)
		{
			if (argumentFilter == null)
				argumentFilter = (p, e) => true;

			formatArgument = null;
			formatStart = default(TextLocation);
			arguments = new List<Expression>();
			var argumentToParameterMap = invocationResolveResult.GetArgumentToParameterMap();
			var resolvedParameters = invocationResolveResult.Member.Parameters;
			var allArguments = invocationExpression.Arguments.ToArray();
			for (int i = 0; i < allArguments.Length; i++) {
				var parameterIndex = argumentToParameterMap[i];
				if (parameterIndex < 0 || parameterIndex >= resolvedParameters.Count) {
					// No valid mapping for this parameter, skip it
					continue;
				}
				var parameter = resolvedParameters[parameterIndex];
				var argument = allArguments[i];
				if (parameter.Type.IsKnownType(KnownTypeCode.String) && parameterNames.Contains(parameter.Name)) {
					formatArgument = argument;
					formatStart = argument.StartLocation;
				} else if ((formatArgument != null || parameter.IsParams) && argumentFilter(parameter, argument)) {
					arguments.Add(argument);
				}
			}
			return formatArgument != null;
		}
Exemplo n.º 9
0
 public ExpressionListBlock(IEmitter emitter, IEnumerable<Expression> expressions, Expression paramArg, InvocationExpression invocation = null)
     : base(emitter, null)
 {
     this.Emitter = emitter;
     this.Expressions = expressions;
     this.ParamExpression = paramArg;
     this.InvocationExpression = invocation;
 }
Exemplo n.º 10
0
 private void GetResolved(InvocationExpression invocationExpression, Action<CSharpInvocationResolveResult> resolved)
 {
     if (_Resolver.resolveResults.ContainsKey(invocationExpression))
     {
         var result = _Resolver.resolveResults[invocationExpression] as CSharpInvocationResolveResult;
         if (result != null) resolved(result);
     }
 }
		public static bool CouldBeExpressionTree(InvocationExpression expr)
		{
			if (expr != null && expr.Arguments.Count == 2) {
				IMethod mr = expr.Annotation<IMethod>();
				return mr != null && mr.Name == "Lambda" && mr.DeclaringType.FullName == "System.Linq.Expressions.Expression";
			}
			return false;
		}
 protected InvocationExpression UpdateInvocation(InvocationExpression iv, Expression expression, IEnumerable<Expression> args)
 {
     if (args != iv.Arguments || expression != iv.Expression)
     {
         return Expression.Invoke(expression, args);
     }
     return iv;
 }
        AstNode ToStaticMethodInvocation(InvocationExpression invocation, MemberReferenceExpression memberReference,
		                                 CSharpInvocationResolveResult invocationRR)
        {
            var newArgumentList = invocation.Arguments.Select(arg => arg.Clone()).ToList();
            newArgumentList.Insert(0, memberReference.Target.Clone());
            var newTarget = memberReference.Clone() as MemberReferenceExpression;
            newTarget.Target = new IdentifierExpression(invocationRR.Member.DeclaringType.Name);
            return new InvocationExpression(newTarget, newArgumentList);
        }
		void AddFormatCallToInvocation (RefactoringContext context, Script script, PrimitiveExpression pExpr, InvocationExpression invocation)
		{
			var newInvocation = (InvocationExpression)invocation.Clone ();
			
			newInvocation.Arguments.First ().ReplaceWith (CreateFormatString (context, pExpr, newInvocation.Arguments.Count () - 1));
			newInvocation.Arguments.Add (CreateFormatArgument (context));
			
			script.Replace (invocation, newInvocation);
		}
        public void LookupAmbiguousInvocationNoParameters()
        {
            _compilationUnit.UsingDirectives.Add(new UsingNamespaceDirective("System"));
            var invocation = new InvocationExpression
            {
                Target = new MemberReferenceExpression(new IdentifierExpression("Console"), "WriteLine"),
            };

            AssertInvocationResolution(invocation, _consoleType.GetMethods().First(x => x.Name == "WriteLine"));
        }
        protected override bool VerifyArgumentUsage(InvocationExpression invocationExpression)
        {
            var firstParam = invocationExpression.Arguments.First() as PrimitiveExpression;
            if(firstParam != null)
            {
                return firstParam.Value.ToString().ToLower() == "hello world";
            }

            return false;
        }
		protected override void AssertInvocationExpression(InvocationExpression invocation, string parameter)
		{
			foreach (var member in invocation.Descendants.OfType<MemberReferenceExpression>())
			{
				if (member.MemberName == "LoadDocument")
					throw new InvalidOperationException("Reduce cannot contain LoadDocument() methods.");
			}

			base.AssertInvocationExpression(invocation, parameter);
		}
			public override void VisitInvocationExpression(InvocationExpression invocationExpression)
			{
				base.VisitInvocationExpression(invocationExpression);

				var resolveResult = ctx.Resolve(invocationExpression) as InvocationResolveResult;
				if (resolveResult == null || !(resolveResult.TargetResult is ThisResolveResult) ||
				    !resolveResult.Member.DeclaringTypeDefinition.IsKnownType(KnownTypeCode.Object)) {
					return;
				}
				AddIssue(invocationExpression, ctx.TranslateString("Call resolves to Object.GetHashCode, which is reference based"));
			}
		protected override void AssertInvocationExpression(InvocationExpression invocation)
		{
			var memberReferenceExpression = invocation.Target as MemberReferenceExpression;
			if (memberReferenceExpression != null)
			{
				if (memberReferenceExpression.MemberName == "LoadDocument")
					throw new InvalidOperationException("Reduce cannot contain LoadDocument() methods.");
			}

			base.AssertInvocationExpression(invocation);
		}
Exemplo n.º 20
0
			IEnumerable<CodeAction> GetActions(InvocationExpression invocationExpression)
			{
				yield return new CodeAction(ctx.TranslateString("Change invocation to call Object.ReferenceEquals"), script => {
					var args = Enumerable.Concat(new [] { new ThisReferenceExpression() }, invocationExpression.Arguments.Select(arg => arg.Clone()));
					var newInvocation = MakeInvocation("object.ReferenceEquals", args);
					script.Replace(invocationExpression, newInvocation);
				});
				yield return new CodeAction(ctx.TranslateString("Remove 'base.'"), script => {
					var newInvocation = MakeInvocation("Equals", invocationExpression.Arguments.Select(arg => arg.Clone()));
					script.Replace(invocationExpression, newInvocation);
				});
			}
 public ConsoleWriteUsedOutsideOfProgramMainPolicy(LintResults results)
     : base(results)
 {
     this.m_Pattern = new InvocationExpression {
         Target = new MemberReferenceExpression
         {
             Target = new IdentifierExpression("Console"),
             MemberName = Pattern.AnyString,
         },
         Arguments = { new Repeat(new AnyNode()) }
     };
 }
        public void LookupAmbiguousInvocationSingleParameters()
        {
            _compilationUnit.UsingDirectives.Add(new UsingNamespaceDirective("System"));
            var invocation = new InvocationExpression
            {
                Target = new MemberReferenceExpression(new IdentifierExpression("Console"), "WriteLine"),
                Arguments = { new PrimitiveExpression("Hello, World!"), }
            };

            AssertInvocationResolution(invocation, _consoleType.GetMethods().First(
                x => x.Name == "WriteLine" && x.GetParameters().FirstOrDefault()?.VariableType?.FullName == "System.String"));
        }
        protected override bool VerifyArgumentUsage(InvocationExpression invocationExpression)
        {
            var firstParam = invocationExpression.Arguments.First() as PrimitiveExpression;
            if (firstParam != null)
            {
                const RegexOptions regexOpts = RegexOptions.IgnorePatternWhitespace;
                const string regex = @"\{ *\d *\, *\d\ *}";

                return Regex.IsMatch(firstParam.Value.ToString(), regex, regexOpts);
            }

            return false;
        }
        protected override bool VerifyArgumentUsage(InvocationExpression invocationExpression)
        {
            if (invocationExpression.Arguments.Count >= 2 && invocationExpression.Arguments.First() is PrimitiveExpression)
            {
                var firstParam = invocationExpression.Arguments.First() as PrimitiveExpression;

                const RegexOptions regexOpts = RegexOptions.IgnorePatternWhitespace;
                const string regex = @"\{ *\d *\: *[C,c,D,d,E,e,F,f,G,g,N,n,X,x]\d*\}";

                return Regex.IsMatch(firstParam.Value.ToString(), regex, regexOpts);
            }

            return false;
        }
			public override void VisitInvocationExpression(InvocationExpression invocationExpression)
			{
				base.VisitInvocationExpression(invocationExpression);
				if (!IsCallDependentOnCurrentInstance(invocationExpression))
					// Call within current class scope without 'this' or 'base'
					return;
				var targetMethod = context.Resolve(invocationExpression) as InvocationResolveResult;
				if (targetMethod == null)
					return;
				if (targetMethod.IsVirtualCall) {
					AddIssue(invocationExpression,
					         context.TranslateString("Constructors should not call virtual members"));
				}
			}
Exemplo n.º 26
0
        public ArgumentsInfo(IEmitter emitter, InvocationExpression invocationExpression)
        {
            this.Emitter = emitter;
            this.Expression = invocationExpression;

            var arguments = invocationExpression.Arguments.ToList();
            this.ResolveResult = emitter.Resolver.ResolveNode(invocationExpression, emitter) as InvocationResolveResult;

            this.BuildArgumentsList(arguments);
            if (this.ResolveResult != null)
            {
                this.HasTypeArguments = ((IMethod)this.ResolveResult.Member).TypeArguments.Count > 0;
                this.BuildTypedArguments(invocationExpression.Target);
            }
        }
			public override void VisitInvocationExpression(InvocationExpression invocationExpression)
			{
				base.VisitInvocationExpression(invocationExpression);
				if (invocationExpression.Target is IdentifierExpression)
					// Call within current class scope without 'this' or 'base'
					return;
				var memberReference = invocationExpression.Target as MemberReferenceExpression;
				if (memberReference == null || memberReference.Target is ThisReferenceExpression)
					// Call within current class scope using 'this' or 'base'
					return;
				var invocationResolveResult = context.Resolve(invocationExpression) as InvocationResolveResult;
				if (invocationResolveResult == null)
					return;
				HandleMember(invocationExpression, memberReference.Target, invocationResolveResult.Member, invocationResolveResult.TargetResult);
			}
			void CheckInvocationInAutoCallContext(InvocationExpression invocationExpression)
			{
				var memberExpression = invocationExpression.Target as MemberReferenceExpression;
				if (memberExpression == null) {
					return;
				}
				var resolveResult = ctx.Resolve(invocationExpression) as CSharpInvocationResolveResult;
				if (resolveResult == null) {
					return;
				}
				if (resolveResult.Member.Name != "ToString") {
					return;
				}
				AddRedundantToStringIssue(memberExpression, invocationExpression);
			}
Exemplo n.º 29
0
		public static bool TryGetFormattingParameters(CSharpInvocationResolveResult invocationResolveResult, InvocationExpression invocationExpression,
		                                     		  out Expression formatArgument, out IList<Expression> arguments,
		                                              Func<IParameter, Expression, bool> argumentFilter)
		{
			if (argumentFilter == null)
				argumentFilter = (p, e) => true;

			formatArgument = null;
			arguments = new List<Expression>();

			// Serach for method of type: void Name(string format, params object[] args);
			if (invocationResolveResult.Member.SymbolKind == SymbolKind.Method && invocationResolveResult.Member.DeclaringType != null) {
				var methods = invocationResolveResult.Member.DeclaringType.GetMethods(m => m.Name == invocationResolveResult.Member.Name).ToList();
				if (!methods.Any(m => m.Parameters.Count == 2 && 
					m.Parameters[0].Type.IsKnownType(KnownTypeCode.String) && parameterNames.Contains(m.Parameters[0].Name) && 
					m.Parameters[1].IsParams))
					return false;
			}

			var argumentToParameterMap = invocationResolveResult.GetArgumentToParameterMap();
			var resolvedParameters = invocationResolveResult.Member.Parameters;
			var allArguments = invocationExpression.Arguments.ToArray();
			for (int i = 0; i < allArguments.Length; i++) {
				var parameterIndex = argumentToParameterMap[i];
				if (parameterIndex < 0 || parameterIndex >= resolvedParameters.Count) {
					// No valid mapping for this argument, skip it
					continue;
				}
				var parameter = resolvedParameters[parameterIndex];
				var argument = allArguments[i];
				if (i == 0 && parameter.Type.IsKnownType(KnownTypeCode.String) && parameterNames.Contains(parameter.Name)) {
					formatArgument = argument;
				} else if (formatArgument != null && parameter.IsParams && !invocationResolveResult.IsExpandedForm) {
					var ace = argument as ArrayCreateExpression;
					if (ace == null || ace.Initializer.IsNull)
						return false;
					foreach (var element in ace.Initializer.Elements) {
						if (argumentFilter(parameter, element))
							arguments.Add(argument);
					}
				} else if (formatArgument != null && argumentFilter(parameter, argument)) {
					arguments.Add(argument);
				}
			}
			return formatArgument != null;
		}
Exemplo n.º 30
0
			public override void VisitInvocationExpression(InvocationExpression invocationExpression)
			{
				base.VisitInvocationExpression(invocationExpression);

				if (invocationExpression.Arguments.Count != 1) {
					return;
				}
				var memberExpression = invocationExpression.Target as MemberReferenceExpression;
				if (memberExpression == null || !(memberExpression.Target is BaseReferenceExpression)) {
					return;
				}
				var resolveResult = ctx.Resolve(invocationExpression) as InvocationResolveResult;
				if (resolveResult == null || !resolveResult.Member.DeclaringTypeDefinition.IsKnownType(KnownTypeCode.Object)) {
					return;
				}
				var title = ctx.TranslateString("Call to base.Equals resolves to Object.Equals, which is reference equality");
				AddIssue(invocationExpression, title, GetActions(invocationExpression));
			}
Exemplo n.º 31
0
 public InvocationBlock(IEmitter emitter, InvocationExpression invocationExpression)
     : base(emitter, invocationExpression)
 {
     this.Emitter = emitter;
     this.InvocationExpression = invocationExpression;
 }
 protected virtual bool CompareInvocation(InvocationExpression a, InvocationExpression b)
 {
     return(this.Compare(a.Expression, b.Expression) &&
            this.CompareExpressionList(a.Arguments, b.Arguments));
 }
 private static void CalcHashCodeInvoke(InvocationExpression node, Context context)
 {
     CalcHashCode(new[] { node.Expression }.Concat(node.Arguments), context);
 }
 protected virtual void PVisitInvocation(InvocationExpression iv)
 {
 }
        public override List <Change> PerformChanges(RefactoringOptions options, object properties)
        {
            TextEditorData data = options.GetTextEditorData();
            int            start, end;

            MonoDevelop.Refactoring.IntroduceConstant.IntroduceConstantRefactoring.SearchString(data, '"', out start, out end);
            LineSegment line = data.Document.GetLineByOffset(start);

            int closingTagLength = 1;                    // length of the closing "

            if (end > line.Offset + line.EditableLength) // assume missing closing tag
            {
                end = line.Offset + line.EditableLength;
                closingTagLength = 0;
            }

            INRefactoryASTProvider provider = options.GetASTProvider();

            List <Expression> args             = new List <Expression> ();
            IExpressionFinder expressionFinder = options.GetParser().CreateExpressionFinder(options.Dom);
            int expressionStart = start - 1;

            while (expressionStart > 0)
            {
                if (data.Document.GetCharAt(expressionStart) == '(')
                {
                    expressionStart--;
                    break;
                }
                expressionStart--;
            }
            // Add parameter to existing string.format call
            ExpressionResult     expressionResult = expressionFinder.FindFullExpression(options.Document.Editor, expressionStart);
            InvocationExpression formatCall       = null;

            if (expressionResult != null)
            {
                InvocationExpression possibleFormatCall = provider.ParseExpression(expressionResult.Expression) as InvocationExpression;
                if (possibleFormatCall != null && possibleFormatCall.TargetObject is MemberReferenceExpression && ((MemberReferenceExpression)possibleFormatCall.TargetObject).MemberName == "Format")
                {
                    PrimitiveExpression expr = possibleFormatCall.Arguments[0] as PrimitiveExpression;
                    if (expr != null)
                    {
                        string str = data.Document.GetTextBetween(start + 1, data.SelectionRange.Offset) +
                                     "{" + (possibleFormatCall.Arguments.Count - 1) + "}" +
                                     data.Document.GetTextBetween(data.SelectionRange.EndOffset, end);
                        expr.Value       = str;
                        expr.StringValue = '"' + str + '"';
                        possibleFormatCall.Arguments.Add(new PrimitiveExpression(data.Document.GetTextAt(data.SelectionRange)));
                        formatCall = possibleFormatCall;
                        start      = data.Document.LocationToOffset(expressionResult.Region.Start.Line, expressionResult.Region.Start.Column);
                        end        = data.Document.LocationToOffset(expressionResult.Region.End.Line, expressionResult.Region.End.Column) - 1;
                    }
                }
            }

            // insert new format call
            if (formatCall == null)
            {
                string formattedString = UnescapeString(data.Document.GetTextBetween(start + 1, data.SelectionRange.Offset) + "{0}" + data.Document.GetTextBetween(data.SelectionRange.EndOffset, end));

                args.Add(new PrimitiveExpression(formattedString));
                args.Add(new PrimitiveExpression(data.Document.GetTextAt(data.SelectionRange)));

                TypeReference typeRef = new TypeReference("System.String");
                typeRef.IsKeyword = true;
                MemberReferenceExpression stringFormat = new MemberReferenceExpression(new TypeReferenceExpression(typeRef), "Format");
                formatCall = new InvocationExpression(stringFormat, args);
            }

            List <Change>     changes = new List <Change> ();
            TextReplaceChange change  = new TextReplaceChange();

            change.FileName           = options.Document.FileName;
            change.Offset             = start;
            change.RemovedChars       = end - start + closingTagLength;
            change.InsertedText       = provider.OutputNode(options.Dom, formatCall);
            change.MoveCaretToReplace = true;
            changes.Add(change);
            return(changes);
        }
Exemplo n.º 36
0
 public override void VisitInvocationExpression(InvocationExpression invocationExpression)
 {
     ParenthesizeIfRequired(invocationExpression.Target, Primary);
     base.VisitInvocationExpression(invocationExpression);
 }
Exemplo n.º 37
0
 protected override Expression VisitInvocation(InvocationExpression node) => throw new ApplicationException();
Exemplo n.º 38
0
        // ********************************************************************************************************************************

        /// <summary>
        /// Tries to infer the resource key being referenced from the given expression.
        /// </summary>
        static string GetKeyFromExpression(Expression expr, out bool isPrefixOnly)
        {
            isPrefixOnly = false;
                        #if DEBUG
            LoggingService.Debug("ResourceToolkit: BclNRefactoryResourceResolver trying to get key from expression: " + expr.ToString());
                        #endif

            IndexerExpression indexer = expr as IndexerExpression;
            if (indexer != null)
            {
                foreach (Expression index in indexer.Indexes)
                {
                    PrimitiveExpression p = index as PrimitiveExpression;
                    if (p != null)
                    {
                        string key = p.Value as string;
                        if (key != null)
                        {
                                                        #if DEBUG
                            LoggingService.Debug("ResourceToolkit: BclNRefactoryResourceResolver found key: " + key);
                                                        #endif
                            return(key);
                        }
                    }
                }
            }

            InvocationExpression invocation = expr as InvocationExpression;
            if (invocation != null)
            {
                MemberReferenceExpression fre = invocation.TargetObject as MemberReferenceExpression;
                if (fre != null)
                {
                    if (fre.MemberName == "GetString" || fre.MemberName == "GetObject" || fre.MemberName == "GetStream")
                    {
                        if (invocation.Arguments.Count > 0)
                        {
                            PrimitiveExpression p = invocation.Arguments[0] as PrimitiveExpression;
                            if (p != null)
                            {
                                string key = p.Value as string;
                                if (key != null)
                                {
                                                                        #if DEBUG
                                    LoggingService.Debug("ResourceToolkit: BclNRefactoryResourceResolver found key: " + key);
                                                                        #endif
                                    return(key);
                                }
                            }
                        }
                    }
                    else if (fre.MemberName == "ApplyResources")
                    {
                        if (invocation.Arguments.Count >= 2)
                        {
                            PrimitiveExpression p = invocation.Arguments[1] as PrimitiveExpression;
                            if (p != null)
                            {
                                string key = p.Value as string;
                                if (key != null)
                                {
                                                                        #if DEBUG
                                    LoggingService.Debug("ResourceToolkit: BclNRefactoryResourceResolver found key prefix: " + key);
                                                                        #endif
                                    isPrefixOnly = true;
                                    return(key);
                                }
                            }
                        }
                    }
                }
            }

            return(null);
        }
Exemplo n.º 39
0
        Expression Convert(Expression expr)
        {
            InvocationExpression invocation = expr as InvocationExpression;

            if (invocation != null)
            {
                MethodReference mr = invocation.Annotation <MethodReference>();
                if (mr != null && mr.DeclaringType.FullName == "System.Linq.Expressions.Expression")
                {
                    switch (mr.Name)
                    {
                    case "Add":
                        return(ConvertBinaryOperator(invocation, BinaryOperatorType.Add, false));

                    case "AddChecked":
                        return(ConvertBinaryOperator(invocation, BinaryOperatorType.Add, true));

                    case "AddAssign":
                        return(ConvertAssignmentOperator(invocation, AssignmentOperatorType.Add, false));

                    case "AddAssignChecked":
                        return(ConvertAssignmentOperator(invocation, AssignmentOperatorType.Add, true));

                    case "And":
                        return(ConvertBinaryOperator(invocation, BinaryOperatorType.BitwiseAnd));

                    case "AndAlso":
                        return(ConvertBinaryOperator(invocation, BinaryOperatorType.ConditionalAnd));

                    case "AndAssign":
                        return(ConvertAssignmentOperator(invocation, AssignmentOperatorType.BitwiseAnd));

                    case "ArrayAccess":
                    case "ArrayIndex":
                        return(ConvertArrayIndex(invocation));

                    case "ArrayLength":
                        return(ConvertArrayLength(invocation));

                    case "Assign":
                        return(ConvertAssignmentOperator(invocation, AssignmentOperatorType.Assign));

                    case "Call":
                        return(ConvertCall(invocation));

                    case "Coalesce":
                        return(ConvertBinaryOperator(invocation, BinaryOperatorType.NullCoalescing));

                    case "Condition":
                        return(ConvertCondition(invocation));

                    case "Constant":
                        if (invocation.Arguments.Count >= 1)
                        {
                            return(invocation.Arguments.First().Clone());
                        }
                        else
                        {
                            return(NotSupported(expr));
                        }

                    case "Convert":
                        return(ConvertCast(invocation, false));

                    case "ConvertChecked":
                        return(ConvertCast(invocation, true));

                    case "Divide":
                        return(ConvertBinaryOperator(invocation, BinaryOperatorType.Divide));

                    case "DivideAssign":
                        return(ConvertAssignmentOperator(invocation, AssignmentOperatorType.Divide));

                    case "Equal":
                        return(ConvertBinaryOperator(invocation, BinaryOperatorType.Equality));

                    case "ExclusiveOr":
                        return(ConvertBinaryOperator(invocation, BinaryOperatorType.ExclusiveOr));

                    case "ExclusiveOrAssign":
                        return(ConvertAssignmentOperator(invocation, AssignmentOperatorType.ExclusiveOr));

                    case "Field":
                        return(ConvertField(invocation));

                    case "GreaterThan":
                        return(ConvertBinaryOperator(invocation, BinaryOperatorType.GreaterThan));

                    case "GreaterThanOrEqual":
                        return(ConvertBinaryOperator(invocation, BinaryOperatorType.GreaterThanOrEqual));

                    case "Invoke":
                        return(ConvertInvoke(invocation));

                    case "Lambda":
                        return(ConvertLambda(invocation));

                    case "LeftShift":
                        return(ConvertBinaryOperator(invocation, BinaryOperatorType.ShiftLeft));

                    case "LeftShiftAssign":
                        return(ConvertAssignmentOperator(invocation, AssignmentOperatorType.ShiftLeft));

                    case "LessThan":
                        return(ConvertBinaryOperator(invocation, BinaryOperatorType.LessThan));

                    case "LessThanOrEqual":
                        return(ConvertBinaryOperator(invocation, BinaryOperatorType.LessThanOrEqual));

                    case "ListInit":
                        return(ConvertListInit(invocation));

                    case "MemberInit":
                        return(ConvertMemberInit(invocation));

                    case "Modulo":
                        return(ConvertBinaryOperator(invocation, BinaryOperatorType.Modulus));

                    case "ModuloAssign":
                        return(ConvertAssignmentOperator(invocation, AssignmentOperatorType.Modulus));

                    case "Multiply":
                        return(ConvertBinaryOperator(invocation, BinaryOperatorType.Multiply, false));

                    case "MultiplyChecked":
                        return(ConvertBinaryOperator(invocation, BinaryOperatorType.Multiply, true));

                    case "MultiplyAssign":
                        return(ConvertAssignmentOperator(invocation, AssignmentOperatorType.Multiply, false));

                    case "MultiplyAssignChecked":
                        return(ConvertAssignmentOperator(invocation, AssignmentOperatorType.Multiply, true));

                    case "Negate":
                        return(ConvertUnaryOperator(invocation, UnaryOperatorType.Minus, false));

                    case "NegateChecked":
                        return(ConvertUnaryOperator(invocation, UnaryOperatorType.Minus, true));

                    case "New":
                        return(ConvertNewObject(invocation));

                    case "NewArrayBounds":
                        return(ConvertNewArrayBounds(invocation));

                    case "NewArrayInit":
                        return(ConvertNewArrayInit(invocation));

                    case "Not":
                        return(ConvertUnaryOperator(invocation, UnaryOperatorType.Not));

                    case "NotEqual":
                        return(ConvertBinaryOperator(invocation, BinaryOperatorType.InEquality));

                    case "OnesComplement":
                        return(ConvertUnaryOperator(invocation, UnaryOperatorType.BitNot));

                    case "Or":
                        return(ConvertBinaryOperator(invocation, BinaryOperatorType.BitwiseOr));

                    case "OrAssign":
                        return(ConvertAssignmentOperator(invocation, AssignmentOperatorType.BitwiseOr));

                    case "OrElse":
                        return(ConvertBinaryOperator(invocation, BinaryOperatorType.ConditionalOr));

                    case "Property":
                        return(ConvertProperty(invocation));

                    case "Quote":
                        if (invocation.Arguments.Count == 1)
                        {
                            return(Convert(invocation.Arguments.Single()));
                        }
                        else
                        {
                            return(NotSupported(invocation));
                        }

                    case "RightShift":
                        return(ConvertBinaryOperator(invocation, BinaryOperatorType.ShiftRight));

                    case "RightShiftAssign":
                        return(ConvertAssignmentOperator(invocation, AssignmentOperatorType.ShiftRight));

                    case "Subtract":
                        return(ConvertBinaryOperator(invocation, BinaryOperatorType.Subtract, false));

                    case "SubtractChecked":
                        return(ConvertBinaryOperator(invocation, BinaryOperatorType.Subtract, true));

                    case "SubtractAssign":
                        return(ConvertAssignmentOperator(invocation, AssignmentOperatorType.Subtract, false));

                    case "SubtractAssignChecked":
                        return(ConvertAssignmentOperator(invocation, AssignmentOperatorType.Subtract, true));

                    case "TypeAs":
                        return(ConvertTypeAs(invocation));

                    case "TypeIs":
                        return(ConvertTypeIs(invocation));
                    }
                }
            }
            IdentifierExpression ident = expr as IdentifierExpression;

            if (ident != null)
            {
                ILVariable v = ident.Annotation <ILVariable>();
                if (v != null)
                {
                    foreach (LambdaExpression lambda in activeLambdas)
                    {
                        foreach (ParameterDeclaration p in lambda.Parameters)
                        {
                            if (p.Annotation <ILVariable>() == v)
                            {
                                return(new IdentifierExpression(p.Name).WithAnnotation(v));
                            }
                        }
                    }
                }
            }
            return(NotSupported(expr));
        }
        CodeAction CreateFromStatements(RefactoringContext context, List <AstNode> statements)
        {
            if (!(statements [0].Parent is Statement))
            {
                return(null);
            }

            return(new CodeAction(context.TranslateString("Extract method"), script => {
                string methodName = "NewMethod";
                var method = new MethodDeclaration()
                {
                    ReturnType = new PrimitiveType("sub"),
                    Name = methodName,
                    Body = new BlockStatement()
                };
                bool usesNonStaticMember = false;
                foreach (var node in statements)
                {
                    usesNonStaticMember |= StaticVisitor.UsesNotStaticMember(context, node);
                    if (node is Statement)
                    {
                        method.Body.Add((Statement)node.Clone());
                    }
                    else
                    {
                        method.Body.AddChildUnsafe(node.Clone(), node.Role);
                    }
                }
                if (!usesNonStaticMember)
                {
                    method.Modifiers |= Modifiers.Static;
                }

                var target = new IdentifierExpression(methodName);
                var invocation = new InvocationExpression(target);

                var usedVariables = VariableLookupVisitor.Analyze(context, statements);

                var inExtractedRegion = new VariableUsageAnalyzation(context, usedVariables);
                var lastStatement = statements [statements.Count - 1];

                var stmt = statements [0].GetParent <BlockStatement>();
                while (stmt.GetParent <BlockStatement> () != null)
                {
                    stmt = stmt.GetParent <BlockStatement>();
                }

                inExtractedRegion.SetAnalyzedRange(statements [0], lastStatement);
                stmt.AcceptVisitor(inExtractedRegion);

                var beforeExtractedRegion = new VariableUsageAnalyzation(context, usedVariables);
                beforeExtractedRegion.SetAnalyzedRange(statements [0].Parent, statements [0], true, false);
                stmt.AcceptVisitor(beforeExtractedRegion);

                var afterExtractedRegion = new VariableUsageAnalyzation(context, usedVariables);
                afterExtractedRegion.SetAnalyzedRange(lastStatement, stmt.Statements.Last(), false, true);
                stmt.AcceptVisitor(afterExtractedRegion);
                usedVariables.Sort((l, r) => l.Region.Begin.CompareTo(r.Region.Begin));

                IVariable generatedReturnVariable = null;
                foreach (var variable in usedVariables)
                {
                    if ((variable is IParameter) || beforeExtractedRegion.Has(variable) || !afterExtractedRegion.Has(variable))
                    {
                        continue;
                    }
                    generatedReturnVariable = variable;
                    method.ReturnType = context.CreateShortType(variable.Type);
                    method.Body.Add(new ReturnStatement(new IdentifierExpression(variable.Name)));
                    break;
                }

                int parameterOutCount = 0;
                foreach (var variable in usedVariables)
                {
                    if (!(variable is IParameter) && !beforeExtractedRegion.Has(variable) && !afterExtractedRegion.Has(variable))
                    {
                        continue;
                    }
                    if (variable == generatedReturnVariable)
                    {
                        continue;
                    }
                    Expression argumentExpression = new IdentifierExpression(variable.Name);

                    ParameterModifier mod = ParameterModifier.None;
                    if (inExtractedRegion.GetStatus(variable) == VariableState.Changed)
                    {
                        if (beforeExtractedRegion.GetStatus(variable) == VariableState.None)
                        {
                            mod = ParameterModifier.Out;
                            argumentExpression = new DirectionExpression(FieldDirection.Out, argumentExpression);
                            parameterOutCount++;
                        }
                        else
                        {
                            mod = ParameterModifier.Ref;
                            argumentExpression = new DirectionExpression(FieldDirection.Ref, argumentExpression);
                        }
                    }

                    method.Parameters.Add(new ParameterDeclaration(context.CreateShortType(variable.Type), variable.Name, mod));
                    invocation.Arguments.Add(argumentExpression);
                }

                ParameterDeclaration parameterToTransform = null;
                bool transformParameterToReturn = method.ReturnType is PrimitiveType &&
                                                  ((PrimitiveType)method.ReturnType).Keyword == "sub" &&
                                                  parameterOutCount == 1;
                if (transformParameterToReturn)
                {
                    parameterToTransform = method.Parameters.First(p => p.ParameterModifier == ParameterModifier.Out);
                    parameterToTransform.Remove();
                    var argumentExpression = invocation.Arguments.OfType <DirectionExpression>().First(a => a.FieldDirection == FieldDirection.Out);
                    argumentExpression.Remove();
                    method.ReturnType = parameterToTransform.Type.Clone();
                    var argumentDecl = new VariableDeclarationStatement(parameterToTransform.Type.Clone(), parameterToTransform.Name);
                    method.Body.InsertChildBefore(method.Body.First(), argumentDecl, BlockStatement.StatementRole);
                    method.Body.Add(new ReturnStatement(new IdentifierExpression(parameterToTransform.Name)));
                }

                script
                .InsertWithCursor(context.TranslateString("Extract method"), Script.InsertPosition.Before, method)
                .ContinueScript(delegate {
                    foreach (var node in statements.Skip(1))
                    {
                        if (node is NewLineNode)
                        {
                            continue;
                        }
                        script.Remove(node);
                    }
                    foreach (var variable in usedVariables)
                    {
                        if ((variable is IParameter) || beforeExtractedRegion.Has(variable) || !afterExtractedRegion.Has(variable))
                        {
                            continue;
                        }
                        if (variable == generatedReturnVariable)
                        {
                            continue;
                        }
                        script.InsertBefore(statements [0], new VariableDeclarationStatement(context.CreateShortType(variable.Type), variable.Name));
                    }
                    Statement invocationStatement;

                    if (generatedReturnVariable != null)
                    {
                        invocationStatement = new VariableDeclarationStatement(new SimpleType("var"), generatedReturnVariable.Name, invocation);
                    }
                    else if (transformParameterToReturn)
                    {
                        invocationStatement = new AssignmentExpression(new IdentifierExpression(parameterToTransform.Name), invocation);
                    }
                    else
                    {
                        invocationStatement = invocation;
                    }

                    script.Replace(statements [0], invocationStatement);


                    script.Link(target, method.NameToken);
                });
            }, statements.First().StartLocation, statements.Last().EndLocation));
        }
 protected override Expression VisitInvocation(InvocationExpression node) => null;
Exemplo n.º 42
0
 Expression ConvertAssignmentOperator(InvocationExpression invocation, AssignmentOperatorType op, bool?isChecked = null)
 {
     return(NotSupported(invocation));
 }
Exemplo n.º 43
0
 internal override Expression VisitInvocation(InvocationExpression iv)
 {
     this.cantTranslateExpression = true;
     return(iv);
 }
Exemplo n.º 44
0
        ArrayInitializerExpression ConvertMemberBindings(Expression elementsArray)
        {
            Match m = memberBindingArrayPattern.Match(elementsArray);

            if (!m.Success)
            {
                return(null);
            }
            ArrayInitializerExpression result = new ArrayInitializerExpression();

            foreach (var binding in m.Get <Expression>("binding"))
            {
                InvocationExpression bindingInvocation = binding as InvocationExpression;
                if (bindingInvocation == null || bindingInvocation.Arguments.Count != 2)
                {
                    return(null);
                }
                MemberReferenceExpression bindingMRE = bindingInvocation.Target as MemberReferenceExpression;
                if (bindingMRE == null || !expressionTypeReference.IsMatch(bindingMRE.Target))
                {
                    return(null);
                }

                Expression bindingTarget = bindingInvocation.Arguments.ElementAt(0);
                Expression bindingValue  = bindingInvocation.Arguments.ElementAt(1);

                string memberName;
                Match  m2 = getMethodFromHandlePattern.Match(bindingTarget);
                if (m2.Success)
                {
                    MethodReference setter = m2.Get <AstNode>("method").Single().Annotation <MethodReference>();
                    if (setter == null)
                    {
                        return(null);
                    }
                    memberName = GetPropertyName(setter);
                }
                else
                {
                    return(null);
                }

                Expression convertedValue;
                switch (bindingMRE.MemberName)
                {
                case "Bind":
                    convertedValue = Convert(bindingValue);
                    break;

                case "MemberBind":
                    convertedValue = ConvertMemberBindings(bindingValue);
                    break;

                case "ListBind":
                    convertedValue = ConvertElementInit(bindingValue);
                    break;

                default:
                    return(null);
                }
                if (convertedValue == null)
                {
                    return(null);
                }
                result.Elements.Add(new NamedExpression(memberName, convertedValue));
            }
            return(result);
        }
Exemplo n.º 45
0
 protected override Expression VisitInvocation(InvocationExpression node)
 {
     onReturn();
     return(node);
 }
Exemplo n.º 46
0
        Expression ConvertBinaryOperator(InvocationExpression invocation, BinaryOperatorType op, bool?isChecked = null)
        {
            if (invocation.Arguments.Count < 2)
            {
                return(NotSupported(invocation));
            }

            Expression left = Convert(invocation.Arguments.ElementAt(0));

            if (left == null)
            {
                return(null);
            }
            Expression right = Convert(invocation.Arguments.ElementAt(1));

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

            BinaryOperatorExpression boe = new BinaryOperatorExpression(left, op, right);

            if (isChecked != null)
            {
                boe.AddAnnotation(isChecked.Value ? AddCheckedBlocks.CheckedAnnotation : AddCheckedBlocks.UncheckedAnnotation);
            }

            switch (invocation.Arguments.Count)
            {
            case 2:
                return(boe);

            case 3:
                Match m = getMethodFromHandlePattern.Match(invocation.Arguments.ElementAt(2));
                if (m.Success)
                {
                    return(boe.WithAnnotation(m.Get <AstNode>("method").Single().Annotation <MethodReference>()));
                }
                else
                {
                    return(null);
                }

            case 4:
                if (!trueOrFalse.IsMatch(invocation.Arguments.ElementAt(2)))
                {
                    return(null);
                }
                m = getMethodFromHandlePattern.Match(invocation.Arguments.ElementAt(3));
                if (m.Success)
                {
                    return(boe.WithAnnotation(m.Get <AstNode>("method").Single().Annotation <MethodReference>()));
                }
                else
                {
                    return(null);
                }

            default:
                return(NotSupported(invocation));
            }
        }
Exemplo n.º 47
0
 public static void LambdaAndArgChangeVisit(InvocationExpression invoke)
 {
     Assert.NotSame(invoke, new ParameterAndConstantChangingVisitor().Visit(invoke));
 }
Exemplo n.º 48
0
 private void ToStringInvocation(InvocationExpression iv)
 {
     ToStringExpressionList(iv.Arguments);
     return;
 }
Exemplo n.º 49
0
            public override void VisitInvocationExpression(InvocationExpression invocationExpression)
            {
                base.VisitInvocationExpression(invocationExpression);

                // Speed up the inspector by discarding some invocations early
                var hasEligibleArgument = invocationExpression.Arguments.Any(argument => {
                    var primitiveArg = argument as PrimitiveExpression;
                    return(primitiveArg != null && primitiveArg.Value is string);
                });

                if (!hasEligibleArgument)
                {
                    return;
                }

                var invocationResolveResult = context.Resolve(invocationExpression) as AlInvocationResolveResult;

                if (invocationResolveResult == null)
                {
                    return;
                }
                Expression         formatArgument;
                IList <Expression> formatArguments;

                if (!FormatStringHelper.TryGetFormattingParameters(invocationResolveResult, invocationExpression,
                                                                   out formatArgument, out formatArguments, null))
                {
                    return;
                }
                var primitiveArgument = formatArgument as PrimitiveExpression;

                if (primitiveArgument == null || !(primitiveArgument.Value is string))
                {
                    return;
                }
                var format        = (string)primitiveArgument.Value;
                var parsingResult = context.ParseFormatString(format);

                CheckSegments(parsingResult.Segments, formatArgument.StartLocation, formatArguments, invocationExpression);

                var argUsed = new HashSet <int> ();

                foreach (var item in parsingResult.Segments)
                {
                    var fi = item as FormatItem;
                    if (fi == null)
                    {
                        continue;
                    }
                    argUsed.Add(fi.Index);
                }
                for (int i = 0; i < formatArguments.Count; i++)
                {
                    if (!argUsed.Contains(i))
                    {
                        AddIssue(new CodeIssue(formatArguments[i], ctx.TranslateString("Argument is not used in format string"))
                        {
                            IssueMarker = IssueMarker.GrayOut
                        });
                    }
                }
            }
Exemplo n.º 50
0
 protected override bool VisitInvocation(InvocationExpression x, InvocationExpression y)
 {
     return((this.DefaultVisit(x, y) && this.Visit(x.Expression, y.Expression)) && this.VisitLists(x.Arguments, y.Arguments));
 }
Exemplo n.º 51
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="expr1"></param>
        /// <param name="expr2"></param>
        /// <returns></returns>
        internal static Expression <Func <T, bool> > And <T>(Expression <Func <T, bool> > expr1, Expression <Func <T, bool> > expr2)
        {
            InvocationExpression invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast <Expression>());

            return(Expression.Lambda <Func <T, bool> >(Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters));
        }
Exemplo n.º 52
0
        /// <summary>
        /// Gets the like expression.
        /// </summary>
        /// <typeparam name="T">The type of the entity.</typeparam>
        /// <param name="property">The property.</param>
        /// <param name="filter">The filter.</param>
        /// <param name="arg">The arg.</param>
        /// <param name="prop">The prop.</param>
        /// <returns>The like expression.</returns>
        private static Expression GetLikeExpression <T>(Expression <Func <T, string> > property, string filter, ParameterExpression arg, InvocationExpression prop)
        {
            Expression exp = null;

            if (filter.StartsWith("*"))
            {
                exp = Expression.Call(prop, "Contains", null, Expression.Constant(filter.Substring(1)));
            }
            else
            {
                exp = Expression.Call(prop, "StartsWith", null, Expression.Constant(filter));
            }

            return(exp);
        }
Exemplo n.º 53
0
 protected override int VisitInvocation(InvocationExpression exp)
 {
     return((this.DefaultVisit(exp) ^ this.Visit(exp.Expression)) ^ this.VisitList(exp.Arguments));
 }
Exemplo n.º 54
0
        Expression ConvertCall(InvocationExpression invocation)
        {
            if (invocation.Arguments.Count < 2)
            {
                return(NotSupported(invocation));
            }

            Expression target;
            int        firstArgumentPosition;

            Match m = getMethodFromHandlePattern.Match(invocation.Arguments.ElementAt(0));

            if (m.Success)
            {
                target = null;
                firstArgumentPosition = 1;
            }
            else
            {
                m = getMethodFromHandlePattern.Match(invocation.Arguments.ElementAt(1));
                if (!m.Success)
                {
                    return(NotSupported(invocation));
                }
                target = invocation.Arguments.ElementAt(0);
                firstArgumentPosition = 2;
            }

            MethodReference mr = m.Get <AstNode>("method").Single().Annotation <MethodReference>();

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

            Expression convertedTarget;

            if (target == null || target is NullReferenceExpression)
            {
                // static method
                if (m.Has("declaringType"))
                {
                    convertedTarget = new TypeReferenceExpression(m.Get <AstType>("declaringType").Single().Clone());
                }
                else
                {
                    convertedTarget = new TypeReferenceExpression(AstBuilder.ConvertType(mr.DeclaringType));
                }
            }
            else
            {
                convertedTarget = Convert(target);
                if (convertedTarget == null)
                {
                    return(null);
                }
            }

            MemberReferenceExpression mre = convertedTarget.Member(mr.Name);
            GenericInstanceMethod     gim = mr as GenericInstanceMethod;

            if (gim != null)
            {
                foreach (TypeReference tr in gim.GenericArguments)
                {
                    mre.TypeArguments.Add(AstBuilder.ConvertType(tr));
                }
            }
            IList <Expression> arguments = null;

            if (invocation.Arguments.Count == firstArgumentPosition + 1)
            {
                Expression argumentArray = invocation.Arguments.ElementAt(firstArgumentPosition);
                arguments = ConvertExpressionsArray(argumentArray);
            }
            if (arguments == null)
            {
                arguments = new List <Expression>();
                foreach (Expression argument in invocation.Arguments.Skip(firstArgumentPosition))
                {
                    Expression convertedArgument = Convert(argument);
                    if (convertedArgument == null)
                    {
                        return(null);
                    }
                    arguments.Add(convertedArgument);
                }
            }
            MethodDefinition methodDef = mr.Resolve();

            if (methodDef != null && methodDef.IsGetter)
            {
                PropertyDefinition indexer = AstMethodBodyBuilder.GetIndexer(methodDef);
                if (indexer != null)
                {
                    return(new IndexerExpression(mre.Target.Detach(), arguments).WithAnnotation(indexer));
                }
            }
            return(new InvocationExpression(mre, arguments).WithAnnotation(mr));
        }
Exemplo n.º 55
0
 /// <summary>
 /// Visit a <see cref="InvocationExpression"/>.
 /// </summary>
 /// <param name="expression"><see cref="InvocationExpression"/> to visit.</param>
 /// <returns>Returns the result of the visit.</returns>
 protected abstract object VisitInvocationExpression(InvocationExpression expression);
Exemplo n.º 56
0
        Expression ConvertTypeIs(InvocationExpression invocation)
        {
            if (invocation.Arguments.Count != 2)
            {
                return(null);
            }
            Expression converted = Convert(invocation.Arguments.ElementAt(0));
            AstType    type      = ConvertTypeReference(invocation.Arguments.ElementAt(1));

            if (converted != null && type != null)
            {
                return new IsExpression {
                           Expression = converted, Type = type
                }
            }
            ;
            return(null);
        }

        #endregion

        #region Convert Array
        Expression ConvertArrayIndex(InvocationExpression invocation)
        {
            if (invocation.Arguments.Count != 2)
            {
                return(NotSupported(invocation));
            }

            Expression targetConverted = Convert(invocation.Arguments.First());

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

            Expression index          = invocation.Arguments.ElementAt(1);
            Expression indexConverted = Convert(index);

            if (indexConverted != null)
            {
                return(new IndexerExpression(targetConverted, indexConverted));
            }
            IList <Expression> indexesConverted = ConvertExpressionsArray(index);

            if (indexesConverted != null)
            {
                return(new IndexerExpression(targetConverted, indexesConverted));
            }
            return(null);
        }

        Expression ConvertArrayLength(InvocationExpression invocation)
        {
            if (invocation.Arguments.Count != 1)
            {
                return(NotSupported(invocation));
            }

            Expression targetConverted = Convert(invocation.Arguments.Single());

            if (targetConverted != null)
            {
                return(targetConverted.Member("Length"));
            }
            else
            {
                return(null);
            }
        }

        Expression ConvertNewArrayInit(InvocationExpression invocation)
        {
            if (invocation.Arguments.Count != 2)
            {
                return(NotSupported(invocation));
            }

            AstType            elementType = ConvertTypeReference(invocation.Arguments.ElementAt(0));
            IList <Expression> elements    = ConvertExpressionsArray(invocation.Arguments.ElementAt(1));

            if (elementType != null && elements != null)
            {
                if (ContainsAnonymousType(elementType))
                {
                    elementType = null;
                }
                return(new ArrayCreateExpression {
                    Type = elementType,
                    AdditionalArraySpecifiers = { new ArraySpecifier() },
                    Initializer = new ArrayInitializerExpression(elements)
                });
            }
            return(null);
        }

        Expression ConvertNewArrayBounds(InvocationExpression invocation)
        {
            if (invocation.Arguments.Count != 2)
            {
                return(NotSupported(invocation));
            }

            AstType            elementType = ConvertTypeReference(invocation.Arguments.ElementAt(0));
            IList <Expression> arguments   = ConvertExpressionsArray(invocation.Arguments.ElementAt(1));

            if (elementType != null && arguments != null)
            {
                if (ContainsAnonymousType(elementType))
                {
                    elementType = null;
                }
                ArrayCreateExpression ace = new ArrayCreateExpression();
                ace.Type = elementType;
                ace.Arguments.AddRange(arguments);
                return(ace);
            }
            return(null);
        }

        bool ContainsAnonymousType(AstType type)
        {
            foreach (AstType t in type.DescendantsAndSelf.OfType <AstType>())
            {
                TypeReference tr = t.Annotation <TypeReference>();
                if (tr != null && tr.IsAnonymousType())
                {
                    return(true);
                }
            }
            return(false);
        }

        #endregion
    }
Exemplo n.º 57
0
        protected void VisitInvocationExpression()
        {
            InvocationExpression invocationExpression = this.InvocationExpression;
            int pos = this.Emitter.Output.Length;

            if (this.Emitter.IsForbiddenInvocation(invocationExpression))
            {
                throw new EmitterException(invocationExpression, "This method cannot be invoked directly");
            }

            var oldValue = this.Emitter.ReplaceAwaiterByVar;
            var oldAsyncExpressionHandling = this.Emitter.AsyncExpressionHandling;

            if (this.Emitter.IsAsync && !this.Emitter.AsyncExpressionHandling)
            {
                this.WriteAwaiters(invocationExpression);
                this.Emitter.ReplaceAwaiterByVar     = true;
                this.Emitter.AsyncExpressionHandling = true;
            }

            Tuple <bool, bool, string> inlineInfo = this.Emitter.GetInlineCode(invocationExpression);
            var argsInfo = new ArgumentsInfo(this.Emitter, invocationExpression);

            var argsExpressions = argsInfo.ArgumentsExpressions;
            var paramsArg       = argsInfo.ParamsExpression;
            var argsCount       = argsExpressions.Count();

            if (inlineInfo != null)
            {
                bool   isStaticMethod = inlineInfo.Item1;
                bool   isInlineMethod = inlineInfo.Item2;
                string inlineScript   = inlineInfo.Item3;

                if (isInlineMethod)
                {
                    if (invocationExpression.Arguments.Count > 0)
                    {
                        var code             = invocationExpression.Arguments.First();
                        var inlineExpression = code as PrimitiveExpression;

                        if (inlineExpression == null)
                        {
                            throw new EmitterException(invocationExpression, "Only primitive expression can be inlined");
                        }

                        string value = inlineExpression.Value.ToString().Trim();

                        if (value.Length > 0)
                        {
                            value = InlineArgumentsBlock.ReplaceInlineArgs(this, inlineExpression.Value.ToString(), invocationExpression.Arguments.Skip(1).ToArray());
                            this.Write(value);

                            value = value.Trim();
                            if (value[value.Length - 1] == ';' || value.EndsWith("*/", StringComparison.InvariantCulture) || value.StartsWith("//"))
                            {
                                this.Emitter.EnableSemicolon = false;
                                this.WriteNewLine();
                            }
                        }
                        else
                        {
                            // Empty string, emit nothing.
                            this.Emitter.EnableSemicolon = false;
                        }

                        this.Emitter.ReplaceAwaiterByVar     = oldValue;
                        this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling;

                        return;
                    }
                }
                else
                {
                    MemberReferenceExpression targetMemberRef = invocationExpression.Target as MemberReferenceExpression;
                    bool isBase = targetMemberRef != null && targetMemberRef.Target is BaseReferenceExpression;

                    if (!String.IsNullOrEmpty(inlineScript) && (isBase || invocationExpression.Target is IdentifierExpression))
                    {
                        argsInfo.ThisArgument = "this";
                        bool noThis = !inlineScript.Contains("{this}");

                        if (inlineScript.StartsWith("<self>"))
                        {
                            noThis       = false;
                            inlineScript = inlineScript.Substring(6);
                        }

                        if (!isStaticMethod && noThis)
                        {
                            this.WriteThis();
                            this.WriteDot();
                        }

                        new InlineArgumentsBlock(this.Emitter, argsInfo, inlineScript).Emit();
                        this.Emitter.ReplaceAwaiterByVar     = oldValue;
                        this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling;

                        return;
                    }
                }
            }

            var targetResolve = this.Emitter.Resolver.ResolveNode(invocationExpression, this.Emitter);

            var csharpInvocation = targetResolve as CSharpInvocationResolveResult;
            MemberReferenceExpression targetMember = invocationExpression.Target as MemberReferenceExpression;

            ResolveResult targetMemberResolveResult = null;

            if (targetMember != null)
            {
                targetMemberResolveResult = this.Emitter.Resolver.ResolveNode(targetMember.Target, this.Emitter);
            }

            if (targetMember != null)
            {
                var member = this.Emitter.Resolver.ResolveNode(targetMember.Target, this.Emitter);

                //var targetResolve = this.Emitter.Resolver.ResolveNode(targetMember, this.Emitter);

                if (targetResolve != null)
                {
                    InvocationResolveResult invocationResult;
                    bool isExtensionMethodInvocation = false;
                    if (csharpInvocation != null)
                    {
                        if (member != null && member.Type.Kind == TypeKind.Delegate && (csharpInvocation.Member.Name == "Invoke" || csharpInvocation.Member.Name == "BeginInvoke" || csharpInvocation.Member.Name == "EndInvoke") && !csharpInvocation.IsExtensionMethodInvocation)
                        {
                            throw new EmitterException(invocationExpression, "Delegate's 'Invoke' methods are not supported. Please use direct delegate invoke.");
                        }

                        if (csharpInvocation.IsExtensionMethodInvocation)
                        {
                            invocationResult            = csharpInvocation;
                            isExtensionMethodInvocation = true;
                            var resolvedMethod = invocationResult.Member as IMethod;
                            if (resolvedMethod != null && resolvedMethod.IsExtensionMethod)
                            {
                                string inline   = this.Emitter.GetInline(resolvedMethod);
                                bool   isNative = this.IsNativeMethod(resolvedMethod);

                                if (string.IsNullOrWhiteSpace(inline) && isNative)
                                {
                                    invocationResult = null;
                                }
                            }
                        }
                        else
                        {
                            invocationResult = null;
                        }

                        if (this.IsEmptyPartialInvoking(csharpInvocation.Member as IMethod) || IsConditionallyRemoved(invocationExpression, csharpInvocation.Member))
                        {
                            this.Emitter.SkipSemiColon           = true;
                            this.Emitter.ReplaceAwaiterByVar     = oldValue;
                            this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling;

                            return;
                        }
                    }
                    else
                    {
                        invocationResult = targetResolve as InvocationResolveResult;

                        if (invocationResult != null && (this.IsEmptyPartialInvoking(invocationResult.Member as IMethod) || IsConditionallyRemoved(invocationExpression, invocationResult.Member)))
                        {
                            this.Emitter.SkipSemiColon           = true;
                            this.Emitter.ReplaceAwaiterByVar     = oldValue;
                            this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling;

                            return;
                        }
                    }

                    if (invocationResult == null)
                    {
                        invocationResult = this.Emitter.Resolver.ResolveNode(invocationExpression, this.Emitter) as InvocationResolveResult;
                    }

                    if (invocationResult != null)
                    {
                        var resolvedMethod = invocationResult.Member as IMethod;

                        if (resolvedMethod != null && resolvedMethod.IsExtensionMethod)
                        {
                            string inline   = this.Emitter.GetInline(resolvedMethod);
                            bool   isNative = this.IsNativeMethod(resolvedMethod);

                            if (isExtensionMethodInvocation)
                            {
                                if (!string.IsNullOrWhiteSpace(inline))
                                {
                                    this.Write("");
                                    StringBuilder savedBuilder = this.Emitter.Output;
                                    this.Emitter.Output = new StringBuilder();
                                    this.WriteThisExtension(invocationExpression.Target);
                                    argsInfo.ThisArgument = this.Emitter.Output.ToString();
                                    this.Emitter.Output   = savedBuilder;
                                    new InlineArgumentsBlock(this.Emitter, argsInfo, inline).Emit();
                                }
                                else if (!isNative)
                                {
                                    var    overloads     = OverloadsCollection.Create(this.Emitter, resolvedMethod);
                                    string name          = BridgeTypes.ToJsName(resolvedMethod.DeclaringType, this.Emitter) + "." + overloads.GetOverloadName();
                                    var    isIgnoreClass = resolvedMethod.DeclaringTypeDefinition != null && this.Emitter.Validator.IsIgnoreType(resolvedMethod.DeclaringTypeDefinition);

                                    this.Write(name);

                                    this.WriteOpenParentheses();

                                    this.Emitter.Comma = false;

                                    if (!isIgnoreClass && !Helpers.IsIgnoreGeneric(resolvedMethod, this.Emitter) && argsInfo.HasTypeArguments)
                                    {
                                        new TypeExpressionListBlock(this.Emitter, argsInfo.TypeArguments).Emit();
                                    }

                                    this.EnsureComma(false);

                                    this.WriteThisExtension(invocationExpression.Target);

                                    if (invocationExpression.Arguments.Count > 0)
                                    {
                                        this.WriteComma();
                                    }

                                    new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, invocationExpression).Emit();

                                    this.WriteCloseParentheses();
                                }

                                if (!string.IsNullOrWhiteSpace(inline) || !isNative)
                                {
                                    this.Emitter.ReplaceAwaiterByVar     = oldValue;
                                    this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling;

                                    return;
                                }
                            }
                            else if (isNative)
                            {
                                if (!string.IsNullOrWhiteSpace(inline))
                                {
                                    this.Write("");
                                    StringBuilder savedBuilder = this.Emitter.Output;
                                    this.Emitter.Output = new StringBuilder();
                                    this.WriteThisExtension(invocationExpression.Target);
                                    argsInfo.ThisArgument = this.Emitter.Output.ToString();
                                    this.Emitter.Output   = savedBuilder;
                                    new InlineArgumentsBlock(this.Emitter, argsInfo, inline).Emit();
                                }
                                else
                                {
                                    argsExpressions.First().AcceptVisitor(this.Emitter);
                                    this.WriteDot();
                                    string name = this.Emitter.GetEntityName(resolvedMethod);
                                    this.Write(name);
                                    this.WriteOpenParentheses();
                                    new ExpressionListBlock(this.Emitter, argsExpressions.Skip(1), paramsArg, invocationExpression).Emit();
                                    this.WriteCloseParentheses();
                                }

                                this.Emitter.ReplaceAwaiterByVar     = oldValue;
                                this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling;

                                return;
                            }
                        }
                    }
                }
            }

            var proto = false;

            if (targetMember != null && targetMember.Target is BaseReferenceExpression)
            {
                var rr = this.Emitter.Resolver.ResolveNode(targetMember, this.Emitter) as MemberResolveResult;

                if (rr != null)
                {
                    proto = rr.IsVirtualCall;

                    /*var method = rr.Member as IMethod;
                     * if (method != null && method.IsVirtual)
                     * {
                     *  proto = true;
                     * }
                     * else
                     * {
                     *  var prop = rr.Member as IProperty;
                     *
                     *  if (prop != null && prop.IsVirtual)
                     *  {
                     *      proto = true;
                     *  }
                     * }*/
                }
            }

            if (proto)
            {
                var baseType = this.Emitter.GetBaseMethodOwnerTypeDefinition(targetMember.MemberName, targetMember.TypeArguments.Count);

                bool isIgnore = this.Emitter.Validator.IsIgnoreType(baseType);

                if (isIgnore)
                {
                    //throw (System.Exception)this.Emitter.CreateException(targetMember.Target, "Cannot call base method, because parent class code is ignored");
                }

                bool needComma = false;

                var resolveResult = this.Emitter.Resolver.ResolveNode(targetMember, this.Emitter);

                string name = null;

                if (this.Emitter.TypeInfo.GetBaseTypes(this.Emitter).Any())
                {
                    name = BridgeTypes.ToJsName(this.Emitter.TypeInfo.GetBaseClass(this.Emitter), this.Emitter);
                }
                else
                {
                    name = BridgeTypes.ToJsName(baseType, this.Emitter);
                }

                string baseMethod;
                bool   isIgnoreGeneric = false;
                if (resolveResult is InvocationResolveResult)
                {
                    InvocationResolveResult invocationResult = (InvocationResolveResult)resolveResult;
                    baseMethod      = OverloadsCollection.Create(this.Emitter, invocationResult.Member).GetOverloadName();
                    isIgnoreGeneric = Helpers.IsIgnoreGeneric(invocationResult.Member, this.Emitter);
                }
                else if (resolveResult is MemberResolveResult)
                {
                    MemberResolveResult memberResult = (MemberResolveResult)resolveResult;
                    baseMethod      = OverloadsCollection.Create(this.Emitter, memberResult.Member).GetOverloadName();
                    isIgnoreGeneric = Helpers.IsIgnoreGeneric(memberResult.Member, this.Emitter);
                }
                else
                {
                    baseMethod = targetMember.MemberName;
                    baseMethod = this.Emitter.AssemblyInfo.PreserveMemberCase ? baseMethod : Object.Net.Utilities.StringUtils.ToLowerCamelCase(baseMethod);
                }

                this.Write(name, ".prototype.", baseMethod);

                this.WriteDot();

                this.Write("call");
                this.WriteOpenParentheses();
                this.WriteThis();
                this.Emitter.Comma = true;
                if (!isIgnore && !isIgnoreGeneric && argsInfo.HasTypeArguments)
                {
                    new TypeExpressionListBlock(this.Emitter, argsInfo.TypeArguments).Emit();
                }

                needComma = false;

                foreach (var arg in argsExpressions)
                {
                    this.EnsureComma(false);

                    if (needComma)
                    {
                        this.WriteComma();
                    }

                    needComma = true;
                    arg.AcceptVisitor(this.Emitter);
                }
                this.Emitter.Comma = false;
                this.WriteCloseParentheses();
            }
            else
            {
                var dynamicResolveResult = this.Emitter.Resolver.ResolveNode(invocationExpression, this.Emitter) as DynamicInvocationResolveResult;

                if (dynamicResolveResult != null)
                {
                    var group = dynamicResolveResult.Target as MethodGroupResolveResult;

                    if (group != null && group.Methods.Count() > 1)
                    {
                        throw new EmitterException(invocationExpression, "Cannot compile this dynamic invocation because there are two or more method overloads with the same parameter count. To work around this limitation, assign the dynamic value to a non-dynamic variable before use or call a method with different parameter count");
                    }
                }

                var     targetResolveResult     = this.Emitter.Resolver.ResolveNode(invocationExpression.Target, this.Emitter);
                var     invocationResolveResult = targetResolveResult as MemberResolveResult;
                IMethod method = null;

                if (invocationResolveResult != null)
                {
                    method = invocationResolveResult.Member as IMethod;
                }

                if (this.IsEmptyPartialInvoking(method) || IsConditionallyRemoved(invocationExpression, method))
                {
                    this.Emitter.SkipSemiColon           = true;
                    this.Emitter.ReplaceAwaiterByVar     = oldValue;
                    this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling;
                    return;
                }

                bool isIgnore = method != null && method.DeclaringTypeDefinition != null && this.Emitter.Validator.IsIgnoreType(method.DeclaringTypeDefinition);

                bool needExpand = false;
                if (method != null)
                {
                    string paramsName = null;

                    var paramsParam = method.Parameters.FirstOrDefault(p => p.IsParams);
                    if (paramsParam != null)
                    {
                        paramsName = paramsParam.Name;
                    }

                    if (paramsName != null)
                    {
                        if (csharpInvocation != null && !csharpInvocation.IsExpandedForm)
                        {
                            needExpand = true;
                        }
                    }
                }

                int count = this.Emitter.Writers.Count;
                invocationExpression.Target.AcceptVisitor(this.Emitter);

                if (this.Emitter.Writers.Count > count)
                {
                    var writer = this.Emitter.Writers.Pop();

                    if (method != null && method.IsExtensionMethod)
                    {
                        StringBuilder savedBuilder = this.Emitter.Output;
                        this.Emitter.Output = new StringBuilder();
                        this.WriteThisExtension(invocationExpression.Target);
                        argsInfo.ThisArgument = this.Emitter.Output.ToString();
                        this.Emitter.Output   = savedBuilder;
                    }
                    else if (writer.ThisArg != null)
                    {
                        argsInfo.ThisArgument = writer.ThisArg;
                    }

                    new InlineArgumentsBlock(this.Emitter, argsInfo, writer.InlineCode)
                    {
                        IgnoreRange = writer.IgnoreRange
                    }.Emit();
                    var result = this.Emitter.Output.ToString();
                    this.Emitter.Output    = writer.Output;
                    this.Emitter.IsNewLine = writer.IsNewLine;
                    this.Write(result);

                    if (writer.Callback != null)
                    {
                        writer.Callback.Invoke();
                    }
                }
                else
                {
                    if (needExpand && isIgnore)
                    {
                        this.Write(".apply");
                    }

                    this.WriteOpenParentheses();

                    bool isIgnoreGeneric  = false;
                    var  invocationResult = targetResolve as InvocationResolveResult;

                    if (invocationResult != null)
                    {
                        isIgnoreGeneric = Helpers.IsIgnoreGeneric(invocationResult.Member, this.Emitter);
                    }

                    if (needExpand && isIgnore)
                    {
                        StringBuilder savedBuilder = this.Emitter.Output;
                        this.Emitter.Output = new StringBuilder();
                        this.WriteThisExtension(invocationExpression.Target);
                        var thisArg = this.Emitter.Output.ToString();
                        this.Emitter.Output = savedBuilder;

                        this.Write(thisArg);

                        this.Emitter.Comma = true;

                        if (!isIgnore && !isIgnoreGeneric && argsInfo.HasTypeArguments)
                        {
                            new TypeExpressionListBlock(this.Emitter, argsInfo.TypeArguments).Emit();
                        }

                        this.EnsureComma(false);

                        if (argsExpressions.Length > 1)
                        {
                            this.WriteOpenBracket();
                            new ExpressionListBlock(this.Emitter, argsExpressions.Take(argsExpressions.Length - 1).ToArray(), paramsArg, invocationExpression).Emit();
                            this.WriteCloseBracket();
                            this.Write(".concat(");
                            new ExpressionListBlock(this.Emitter, new Expression[] { argsExpressions[argsExpressions.Length - 1] }, paramsArg, invocationExpression).Emit();
                            this.Write(")");
                        }
                        else
                        {
                            new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, invocationExpression).Emit();
                        }
                    }
                    else
                    {
                        this.Emitter.Comma = false;
                        if (!isIgnore && !isIgnoreGeneric && argsInfo.HasTypeArguments)
                        {
                            new TypeExpressionListBlock(this.Emitter, argsInfo.TypeArguments).Emit();
                        }

                        if (invocationExpression.Arguments.Count > 0)
                        {
                            this.EnsureComma(false);
                        }

                        new ExpressionListBlock(this.Emitter, argsExpressions, paramsArg, invocationExpression).Emit();
                    }

                    this.WriteCloseParentheses();
                }
            }

            Helpers.CheckValueTypeClone(this.Emitter.Resolver.ResolveNode(invocationExpression, this.Emitter), invocationExpression, this, pos);

            this.Emitter.ReplaceAwaiterByVar     = oldValue;
            this.Emitter.AsyncExpressionHandling = oldAsyncExpressionHandling;
        }
Exemplo n.º 58
0
 public override void VisitInvocationExpression(InvocationExpression invocationExpression)
 {
     new InvocationBlock(this, invocationExpression).Emit();
 }
Exemplo n.º 59
0
 protected abstract void WriteInvocation(InvocationExpression expr);
Exemplo n.º 60
0
        Expression ConvertNewObject(InvocationExpression invocation)
        {
            if (invocation.Arguments.Count < 1 || invocation.Arguments.Count > 3)
            {
                return(NotSupported(invocation));
            }

            Match m = newObjectCtorPattern.Match(invocation.Arguments.First());

            if (!m.Success)
            {
                return(NotSupported(invocation));
            }

            MethodReference ctor = m.Get <AstNode>("ctor").Single().Annotation <MethodReference>();

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

            AstType       declaringTypeNode;
            TypeReference declaringType;

            if (m.Has("declaringType"))
            {
                declaringTypeNode = m.Get <AstType>("declaringType").Single().Clone();
                declaringType     = declaringTypeNode.Annotation <TypeReference>();
            }
            else
            {
                declaringTypeNode = AstBuilder.ConvertType(ctor.DeclaringType);
                declaringType     = ctor.DeclaringType;
            }
            if (declaringTypeNode == null)
            {
                return(null);
            }

            ObjectCreateExpression oce = new ObjectCreateExpression(declaringTypeNode);

            if (invocation.Arguments.Count >= 2)
            {
                IList <Expression> arguments = ConvertExpressionsArray(invocation.Arguments.ElementAtOrDefault(1));
                if (arguments == null)
                {
                    return(null);
                }
                oce.Arguments.AddRange(arguments);
            }
            if (invocation.Arguments.Count >= 3 && declaringType.IsAnonymousType())
            {
                MethodDefinition resolvedCtor = ctor.Resolve();
                if (resolvedCtor == null || resolvedCtor.Parameters.Count != oce.Arguments.Count)
                {
                    return(null);
                }
                AnonymousTypeCreateExpression atce = new AnonymousTypeCreateExpression();
                var arguments = oce.Arguments.ToArray();
                if (AstMethodBodyBuilder.CanInferAnonymousTypePropertyNamesFromArguments(arguments, resolvedCtor.Parameters))
                {
                    oce.Arguments.MoveTo(atce.Initializers);
                }
                else
                {
                    for (int i = 0; i < resolvedCtor.Parameters.Count; i++)
                    {
                        atce.Initializers.Add(
                            new NamedExpression {
                            Name       = resolvedCtor.Parameters[i].Name,
                            Expression = arguments[i].Detach()
                        });
                    }
                }
                return(atce);
            }

            return(oce);
        }