public override void PropagateChanges(MethodInvocationExpression eval, List chain) { ExpressionCollection items = new ExpressionCollection(); foreach (object local1 in chain.Reversed) { if (!(local1 is ProcessAssignmentsToSpecialMembers.ChainItem)) { } ProcessAssignmentsToSpecialMembers.ChainItem item = (ProcessAssignmentsToSpecialMembers.ChainItem)RuntimeServices.Coerce(local1, typeof(ProcessAssignmentsToSpecialMembers.ChainItem)); if (item.Container is MethodInvocationExpression) { break; } if (item.Container is SlicingExpression) { SlicingExpression expression = (SlicingExpression)item.Container; Expression[] expressionArray1 = new Expression[] { expression.Target.CloneNode(), expression.Indices[0].Begin.CloneNode(), this.CodeBuilder.CreateReference(item.Local) }; items.Add(this.CreateConstructorInvocation(this._sliceValueTypeChangeConstructor, expressionArray1)); break; } MemberReferenceExpression container = (MemberReferenceExpression)item.Container; Expression[] args = new Expression[] { container.Target.CloneNode(), this.CodeBuilder.CreateStringLiteral(container.Name), this.CodeBuilder.CreateReference(item.Local) }; items.Add(this.CreateConstructorInvocation(this._valueTypeChangeConstructor, args)); } MethodInvocationExpression expression3 = this.CodeBuilder.CreateMethodInvocation(this._propagateChanges); IArrayType arrayType = this._valueTypeChangeType.MakeArrayType(1); expression3.Arguments.Add(this.CodeBuilder.CreateArray(arrayType, items)); eval.Arguments.Add(expression3); }
private Set GetSetter(ElementBuilder eb, Property propertyClone, string varName) { Set setter = eb.BuildSetter(); If ifStatement = eb.BuildIf(eb.OpNotEquals("value", varName)); ifStatement.AddNode(eb.BuildAssignment(varName, "value")); ExpressionCollection args = new ExpressionCollection(); args.Add(new SnippetExpression(CodeRush.StrUtil.AddQuotes(propertyClone.Name))); ExpressionCollection arguments = new ExpressionCollection(); arguments.Add(eb.BuildThisReferenceExpression()); arguments.Add(eb.BuildObjectCreationExpression("PropertyChangedEventArgs", args)); if (CodeRush.Language.IsCSharp) { ifStatement.AddNode(eb.BuildMethodCall("PropertyChanged", arguments, null /* qualifier */)); } else if (CodeRush.Language.IsBasic) { RaiseEvent raiseEvent = new RaiseEvent(eb.BuildMethodCallExpression("PropertyChanged", arguments)); ifStatement.AddNode(raiseEvent); } setter.AddNode(ifStatement); return(setter); }
public void ExpressionBuilder_TwoExpressionsCombinedWithAnd_CorrectLambda() { // Arrange var expressionCollection = new ExpressionCollection <ExpressionBuilderTestClass>(); expressionCollection.Add(new ExpressionItem <ExpressionBuilderTestClass>(x => x.Id == 1, LogicalOperator.And)); expressionCollection.Add(new ExpressionItem <ExpressionBuilderTestClass>(y => y.Value == "valid")); // Act var lambda = this._fixture.ExpressionBuilder.Build(expressionCollection).ToString(); // Assert Assert.Equal("x => ((x.Id == 1) And (x.Value == \"valid\"))", lambda); }
public void RebuildDimensions(ref ExpressionCollection elements, ExpressionCollection dimensions) { V_0 = elements.get_Count(); V_1 = dimensions.get_Count() - 1; while (V_1 > 0) { V_2 = new ExpressionCollection(); V_3 = (Int32)(dimensions.get_Item(V_1) as LiteralExpression).get_Value(); V_4 = 0; while (V_4 < V_0) { V_5 = new BlockExpression(null); V_5.set_Expressions(new ExpressionCollection()); V_6 = 0; while (V_6 < V_3) { V_5.get_Expressions().Add(elements.get_Item(V_4 + V_6)); V_6 = V_6 + 1; } V_2.Add(V_5); V_4 = V_4 + V_3; } elements = V_2; V_0 = V_0 / V_3; V_1 = V_1 - 1; } return; }
/// <summary> /// Creates an ExpressionCollection and the expected inner xml. /// </summary> /// <param name="numElements">The number of elements to add to the collection.</param> /// <param name="innerXml">Outputs the expected innerXml of the collection.</param> /// <param name="xmlParentTag">The parent tag to use for the collection.</param> /// <param name="elementType">The type of element of the contained nodes.</param> /// <returns>The ExpressionCollection with elements.</returns> public static ExpressionCollection <INUnitFilterBaseElement> CreateCollection(int numElements, out string innerXml, string xmlParentTag = XmlAndTag, NUnitElementType elementType = NUnitElementType.And) { if (numElements < 0) { throw ExceptionHelper.ThrowArgumentOutOfRangeExceptionForValueLessThanZero(nameof(numElements), numElements); } innerXml = string.Empty; ExpressionCollection <INUnitFilterBaseElement> collection = new ExpressionCollection <INUnitFilterBaseElement>(xmlParentTag); if (numElements == 0) { return(collection); } // Create expected string of xml nodes const string value = "Value_"; const string xmlTag = "name_"; IEnumerable <int> range = Enumerable.Range(1, numElements); IEnumerable <string> elements = range.Select(i => CreateXmlNode(xmlTag + i, value + i)); innerXml = string.Join(string.Empty, elements); // Add expressions to collection for (int i = 1; i <= numElements; i++) { collection.Add(new XmlSerializableElementForTest(xmlTag + i, value + i, elementType)); } return(collection); }
public override ICodeNode VisitObjectCreationExpression(ObjectCreationExpression node) { if (state == State.ReplaceDelegate && node.Arguments != null && node.Arguments.Count == 2 && node.Arguments[0].CodeNodeType == CodeNodeType.VariableReferenceExpression && node.Arguments[1].CodeNodeType == CodeNodeType.MethodReferenceExpression && delegateCopies.Contains((node.Arguments[0] as VariableReferenceExpression).Variable)) { //final check inserted here for optimization TypeDefinition objectType = node.Constructor.DeclaringType.Resolve(); if (objectType == null || objectType.BaseType == null || objectType.BaseType.FullName != "System.MulticastDelegate") { return(base.VisitObjectCreationExpression(node)); } MethodReference methodReference = (node.Arguments[1] as MethodReferenceExpression).Method; MethodDefinition methodDefinition = (node.Arguments[1] as MethodReferenceExpression).MethodDefinition; MethodSpecificContext delegateMethodContext = new MethodSpecificContext(methodDefinition.Body); DecompilationContext innerContext = new DecompilationContext(delegateMethodContext, context.TypeContext, context.ModuleContext, context.AssemblyContext); delegateMethodContext.FieldToExpression = fieldDefToAssignedValueMap; BlockStatement methodStatements = methodDefinition.Body.DecompileLambda(Language, innerContext); if ((methodStatements.Statements.Count == 1) && (methodStatements.Statements[0].CodeNodeType == CodeNodeType.ExpressionStatement) && ((methodStatements.Statements[0] as ExpressionStatement).Expression.CodeNodeType == CodeNodeType.ReturnExpression)) { ReturnExpression returnExpression = (methodStatements.Statements[0] as ExpressionStatement).Expression as ReturnExpression; ShortFormReturnExpression shortFormReturnExpression = new ShortFormReturnExpression(returnExpression.Value, returnExpression.MappedInstructions); methodStatements = new BlockStatement(); methodStatements.Statements.Add(new ExpressionStatement(shortFormReturnExpression)); } this.context.MethodContext.VariableDefinitionToNameMap.AddRange(innerContext.MethodContext.VariableDefinitionToNameMap); this.context.MethodContext.VariableNamesCollection.UnionWith(innerContext.MethodContext.VariableNamesCollection); this.context.MethodContext.AddInnerMethodParametersToContext(innerContext.MethodContext); this.context.MethodContext.GotoStatements.AddRange(innerContext.MethodContext.GotoStatements); this.context.MethodContext.GotoLabels.AddRange(innerContext.MethodContext.GotoLabels); ExpressionCollection expressionCollection = new ExpressionCollection(); bool hasAnonymousParamterer = LambdaExpressionsHelper.HasAnonymousParameter(methodDefinition.Parameters); foreach (ParameterDefinition parameter in methodDefinition.Parameters) { expressionCollection.Add(new LambdaParameterExpression(parameter, !hasAnonymousParamterer, null)); } delegatesFound.Add(methodStatements); LambdaExpression lambdaExpression = new LambdaExpression(expressionCollection, methodStatements, methodDefinition.IsAsync(), methodDefinition.IsFunction(), methodReference.Parameters, false, node.Arguments[1].MappedInstructions) { ExpressionType = objectType }; DelegateCreationExpression result = new DelegateCreationExpression(node.Constructor.DeclaringType, lambdaExpression, node.Arguments[0], node.MappedInstructions); return(result); } return(base.VisitObjectCreationExpression(node)); }
protected override bool TryMatchInternal(StatementCollection statements, int startIndex, out Statement result, out int replacedStatementsCount) { result = null; replacedStatementsCount = 0; if (!this.TryGetArrayCreation(statements, startIndex, out V_0, out V_1)) { return(false); } if (V_0.get_Initializer() != null && V_0.get_Initializer().get_Expressions().get_Count() != 0) { return(false); } V_2 = this.GetCreatedArraySize(V_0); V_3 = new Dictionary <uint, Expression>(); V_4 = (long)-1; V_7 = startIndex + 1; while (V_7 < statements.get_Count() && this.TryGetNextExpression(statements.get_Item(V_7), out V_8)) { V_9 = (statements.get_Item(V_7) as ExpressionStatement).get_Expression() as BinaryExpression; if (!this.IsArrayElementAssignment(V_9, V_1)) { break; } V_10 = this.GetAssignmentIndex(V_9.get_Left()); if (V_10 >= V_2 || (ulong)V_10 <= V_4) { break; } V_11 = new List <Instruction>(V_9.get_Left().get_UnderlyingSameMethodInstructions()); V_11.AddRange(V_9.get_MappedInstructions()); V_3.set_Item(V_10, V_9.get_Right().CloneAndAttachInstructions(V_11)); V_4 = (ulong)V_10; V_7 = V_7 + 1; } if (V_3.get_Count() == 0 || (ulong)V_2 - (long)V_3.get_Count() > (long)10) { return(false); } V_5 = V_0.get_ElementType(); V_6 = new ExpressionCollection(); V_12 = 0; while (V_12 < V_2) { if (V_3.ContainsKey(V_12)) { V_13 = V_3.get_Item(V_12); } else { V_13 = this.GetTypeDefaultLiteralExpression(V_5); } V_6.Add(V_13); V_12 = V_12 + 1; } V_0.set_Initializer(new InitializerExpression(V_6, 2)); result = statements.get_Item(startIndex); replacedStatementsCount = V_3.get_Count() + 1; return(true); }
public void AddReturnExpression(Expression expression) { if (null == _returnExpressions) { _returnExpressions = new ExpressionCollection(); } _returnExpressions.Add(expression); }
public void TestAddWithNullItemDoesNotAddItem() { // Create collection const int count = 3; ExpressionCollection <INUnitFilterBaseElement> collection = NUnitFilterTestHelper.CreateCollection(count, out _); collection.Add(null); Assert.AreEqual(count, collection.Count); }
private bool ExtendsTheCallerType(IMethodElement method, ITypeElement callerType, Expression qualifier) { if (method == null || callerType == null) { return(false); } if (method.Parameters.Count == 0) { return(false); } ISourceTreeResolver resolver = ParserServices.SourceTreeResolver; ExpressionCollection arguments = new ExpressionCollection(); arguments.Add(qualifier); method = GenericElementActivator.ActivateMemberIfNeeded(resolver, method, arguments, null, ArgumentsHelper.ResolveArgumentTypes(resolver, arguments)) as IMethodElement; if (method == null) { return(false); } IParameterElement extensionParam = method.Parameters[0] as IParameterElement; if (extensionParam == null) { return(false); } ITypeReferenceExpression typeRef = extensionParam.Type; if (typeRef == null) { return(false); } ITypeElement type = typeRef.GetDeclaration() as ITypeElement; if (type == null) { return(false); } IArrayTypeElement arrayType = callerType as IArrayTypeElement; //if (arrayType != null) //{ // return true; //} //else return(ArgumentsHelper.HasParamConversion(resolver, extensionParam, callerType, qualifier, TypeConversionMode.ImplicitConversion)); }
} // refactoringProvider_Apply(sender, ea) /// <summary> /// Get new delayed property declaration /// </summary> private string GetNewDelayedPropertyDeclaration(ElementBuilder elementBuilder, Property oldProperty) { string propName = oldProperty.Name; string typeName = oldProperty.GetTypeName(); Property newProperty = elementBuilder.AddProperty(null, typeName, propName); newProperty.Visibility = oldProperty.Visibility; newProperty.IsStatic = oldProperty.IsStatic; newProperty.IsVirtual = oldProperty.IsVirtual; newProperty.IsOverride = oldProperty.IsOverride; newProperty.IsExplicitInterfaceMember = oldProperty.IsExplicitInterfaceMember; AttributeSection attrSection = elementBuilder.AddAttributeSection(newProperty); elementBuilder.AddAttribute(attrSection, "Delayed"); if (oldProperty.HasGetter) { Get getter = elementBuilder.AddGetter(newProperty); ExpressionCollection expressionCollection = new ExpressionCollection(); expressionCollection.Add(new PrimitiveExpression(String.Format("\"{0}\"", propName))); string methodName = String.Format("GetDelayedPropertyValue<{0}>", typeName); elementBuilder.AddReturn(getter, elementBuilder.BuildMethodCall(methodName, expressionCollection, null)); } if (oldProperty.HasSetter) { Set setter = elementBuilder.AddSetter(newProperty); ExpressionCollection expressionCollection = new ExpressionCollection(); expressionCollection.Add(new PrimitiveExpression(String.Format("\"{0}\"", propName))); expressionCollection.Add(new ElementReferenceExpression("value")); string methodName = String.Format("SetDelayedPropertyValue<{0}>", typeName); elementBuilder.AddMethodCall(setter, methodName, expressionCollection, null); } // if return(elementBuilder.GenerateCode()); } // GetNewDelayedPropertyDeclaration(elementBuilder, oldProperty)
} // GetNewDelayedPropertyDeclaration(elementBuilder, oldProperty) /// <summary> /// Get new property declaration /// </summary> private string GetNewPropertyDeclaration(ElementBuilder elementBuilder, Property oldProperty) { string propName = oldProperty.Name; string typeName = oldProperty.GetTypeName(); string fieldVariableName = CodeRush.Strings.Get("FormatFieldName", propName); Variable fieldVar = elementBuilder.AddVariable(null, typeName, fieldVariableName); fieldVar.IsStatic = oldProperty.IsStatic; fieldVar.Visibility = MemberVisibility.Private; Property newProperty = elementBuilder.AddProperty(null, typeName, propName); newProperty.Visibility = oldProperty.Visibility; newProperty.IsStatic = oldProperty.IsStatic; newProperty.IsVirtual = oldProperty.IsVirtual; newProperty.IsOverride = oldProperty.IsOverride; newProperty.IsExplicitInterfaceMember = oldProperty.IsExplicitInterfaceMember; if (oldProperty.HasGetter) { Get getter = elementBuilder.AddGetter(newProperty); elementBuilder.AddReturn(getter, fieldVariableName); } if (oldProperty.HasSetter) { Set setter = elementBuilder.AddSetter(newProperty); ExpressionCollection expressionCollection = new ExpressionCollection(); expressionCollection.Add(new PrimitiveExpression(String.Format("\"{0}\"", propName))); expressionCollection.Add(new ArgumentDirectionExpression(ArgumentDirection.Ref, new ElementReferenceExpression(fieldVariableName))); expressionCollection.Add(new ElementReferenceExpression("value")); elementBuilder.AddMethodCall(setter, "SetPropertyValue", expressionCollection, null); } // if return(elementBuilder.GenerateCode()); } // GetNewPropertyDeclaration(elementBuilder, oldProperty)
public override ICodeNode VisitObjectCreationExpression(ObjectCreationExpression node) { if (this.state != 2 || node.get_Arguments() == null || node.get_Arguments().get_Count() != 2 || node.get_Arguments().get_Item(0).get_CodeNodeType() != 26 || node.get_Arguments().get_Item(1).get_CodeNodeType() != 20 || !this.delegateCopies.Contains((node.get_Arguments().get_Item(0) as VariableReferenceExpression).get_Variable())) { return(this.VisitObjectCreationExpression(node)); } V_0 = node.get_Constructor().get_DeclaringType().Resolve(); if (V_0 == null || V_0.get_BaseType() == null || String.op_Inequality(V_0.get_BaseType().get_FullName(), "System.MulticastDelegate")) { return(this.VisitObjectCreationExpression(node)); } V_1 = (node.get_Arguments().get_Item(1) as MethodReferenceExpression).get_Method(); V_2 = (node.get_Arguments().get_Item(1) as MethodReferenceExpression).get_MethodDefinition(); stackVariable62 = new MethodSpecificContext(V_2.get_Body()); V_3 = new DecompilationContext(stackVariable62, this.context.get_TypeContext(), this.context.get_ModuleContext(), this.context.get_AssemblyContext(), this.context.get_Language()); stackVariable62.set_FieldToExpression(this.fieldDefToAssignedValueMap); V_4 = V_2.get_Body().DecompileLambda(this.context.get_Language(), V_3); if (V_4.get_Statements().get_Count() == 1 && V_4.get_Statements().get_Item(0).get_CodeNodeType() == 5 && (V_4.get_Statements().get_Item(0) as ExpressionStatement).get_Expression().get_CodeNodeType() == 57) { V_8 = (V_4.get_Statements().get_Item(0) as ExpressionStatement).get_Expression() as ReturnExpression; V_9 = new ShortFormReturnExpression(V_8.get_Value(), V_8.get_MappedInstructions()); V_4 = new BlockStatement(); V_4.get_Statements().Add(new ExpressionStatement(V_9)); } this.context.get_MethodContext().get_VariableDefinitionToNameMap().AddRange <VariableDefinition, string>(V_3.get_MethodContext().get_VariableDefinitionToNameMap()); this.context.get_MethodContext().get_VariableNamesCollection().UnionWith(V_3.get_MethodContext().get_VariableNamesCollection()); this.context.get_MethodContext().AddInnerMethodParametersToContext(V_3.get_MethodContext()); this.context.get_MethodContext().get_GotoStatements().AddRange(V_3.get_MethodContext().get_GotoStatements()); this.context.get_MethodContext().get_GotoLabels().AddRange <string, Statement>(V_3.get_MethodContext().get_GotoLabels()); V_5 = new ExpressionCollection(); V_6 = LambdaExpressionsHelper.HasAnonymousParameter(V_2.get_Parameters()); V_10 = V_2.get_Parameters().GetEnumerator(); try { while (V_10.MoveNext()) { V_11 = V_10.get_Current(); V_5.Add(new LambdaParameterExpression(V_11, !V_6, null)); } } finally { V_10.Dispose(); } this.delegatesFound.Add(V_4); stackVariable157 = new LambdaExpression(V_5, V_4, V_2.IsAsync(), V_2.IsFunction(), V_1.get_Parameters(), false, node.get_Arguments().get_Item(1).get_MappedInstructions()); stackVariable157.set_ExpressionType(V_0); V_7 = stackVariable157; return(new DelegateCreationExpression(node.get_Constructor().get_DeclaringType(), V_7, node.get_Arguments().get_Item(0), node.get_MappedInstructions())); }
public void TestAddWithNonNullItemAddsItem() { // Create collection and item to add const int count = 3; const string value = "Value_new"; const string xmlTag = "name_new"; XmlSerializableElementForTest item = new XmlSerializableElementForTest(xmlTag, value, NUnitElementType.And); ExpressionCollection <INUnitFilterBaseElement> collection = NUnitFilterTestHelper.CreateCollection(count, out _); collection.Add(item); Assert.AreEqual(count + 1, collection.Count); Assert.AreSame(item, collection.Last()); }
public override ICodeNode VisitMethodReferenceExpression(MethodReferenceExpression node) { V_0 = node.get_Method().Resolve(); V_1 = this.context.get_TypeContext().get_CurrentType(); if (V_0 == null || (object)V_0.get_DeclaringType() != (object)V_1 && !V_0.get_DeclaringType().IsNestedIn(V_1)) { return(this.VisitMethodReferenceExpression(node)); } if (V_0.get_IsGetter() || V_0.get_IsSetter() || !V_0.IsCompilerGenerated(true) && !this.CheckTypeForCompilerGeneratedAttribute(V_0.get_DeclaringType())) { return(this.VisitMethodReferenceExpression(node)); } V_2 = null; if (V_0.get_Body() != null) { V_5 = this.CreateDecompilationContext(V_0); V_2 = V_0.get_Body().DecompileLambda(this.context.get_Language(), V_5); if (V_2.get_Statements().get_Count() == 1 && V_2.get_Statements().get_Item(0).get_CodeNodeType() == 5 && (V_2.get_Statements().get_Item(0) as ExpressionStatement).get_Expression().get_CodeNodeType() == 57) { V_6 = (V_2.get_Statements().get_Item(0) as ExpressionStatement).get_Expression() as ReturnExpression; V_7 = new ShortFormReturnExpression(V_6.get_Value(), V_6.get_MappedInstructions()); V_2 = new BlockStatement(); V_2.get_Statements().Add(new ExpressionStatement(V_7)); } this.context.get_MethodContext().get_VariableDefinitionToNameMap().AddRange <VariableDefinition, string>(V_5.get_MethodContext().get_VariableDefinitionToNameMap()); this.context.get_MethodContext().get_VariableNamesCollection().UnionWith(V_5.get_MethodContext().get_VariableNamesCollection()); this.context.get_MethodContext().AddInnerMethodParametersToContext(V_5.get_MethodContext()); this.context.get_MethodContext().get_GotoStatements().AddRange(V_5.get_MethodContext().get_GotoStatements()); this.context.get_MethodContext().get_GotoLabels().AddRange <string, Statement>(V_5.get_MethodContext().get_GotoLabels()); } V_3 = new ExpressionCollection(); V_4 = LambdaExpressionsHelper.HasAnonymousParameter(V_0.get_Parameters()); V_8 = V_0.get_Parameters().GetEnumerator(); try { while (V_8.MoveNext()) { V_9 = V_8.get_Current(); V_3.Add(new LambdaParameterExpression(V_9, !V_4, null)); } } finally { V_8.Dispose(); } return(new LambdaExpression(V_3, V_2, V_0.IsAsync(), V_0.IsFunction(), node.get_Method().get_Parameters(), false, node.get_MappedInstructions())); }
public override ICodeNode VisitMethodReferenceExpression(MethodReferenceExpression node) { MethodDefinition methodDefinition = node.Method.Resolve(); TypeDefinition currentType = context.TypeContext.CurrentType; if (methodDefinition == null || methodDefinition.DeclaringType != currentType && !methodDefinition.DeclaringType.IsNestedIn(currentType)) { return(base.VisitMethodReferenceExpression(node)); } if ((!methodDefinition.IsGetter) && (!methodDefinition.IsSetter) && (methodDefinition.IsCompilerGenerated() || CheckTypeForCompilerGeneratedAttribute(methodDefinition.DeclaringType))) { BlockStatement statement = null; if (methodDefinition.Body != null) { DecompilationContext innerContext = CreateDecompilationContext(methodDefinition); statement = methodDefinition.Body.DecompileLambda(Language, innerContext); if ((statement.Statements.Count == 1) && (statement.Statements[0].CodeNodeType == CodeNodeType.ExpressionStatement) && ((statement.Statements[0] as ExpressionStatement).Expression.CodeNodeType == CodeNodeType.ReturnExpression)) { ReturnExpression returnExpression = (statement.Statements[0] as ExpressionStatement).Expression as ReturnExpression; ShortFormReturnExpression shortFormReturnExpression = new ShortFormReturnExpression(returnExpression.Value, returnExpression.MappedInstructions); statement = new BlockStatement(); statement.Statements.Add(new ExpressionStatement(shortFormReturnExpression)); } this.context.MethodContext.VariableDefinitionToNameMap.AddRange(innerContext.MethodContext.VariableDefinitionToNameMap); this.context.MethodContext.VariableNamesCollection.UnionWith(innerContext.MethodContext.VariableNamesCollection); this.context.MethodContext.AddInnerMethodParametersToContext(innerContext.MethodContext); this.context.MethodContext.GotoStatements.AddRange(innerContext.MethodContext.GotoStatements); this.context.MethodContext.GotoLabels.AddRange(innerContext.MethodContext.GotoLabels); } ExpressionCollection expressionCollection = new ExpressionCollection(); bool hasAnonymousParameter = LambdaExpressionsHelper.HasAnonymousParameter(methodDefinition.Parameters); foreach (ParameterDefinition parameter in methodDefinition.Parameters) { expressionCollection.Add(new LambdaParameterExpression(parameter, !hasAnonymousParameter, null)); } return(new LambdaExpression(expressionCollection, statement, methodDefinition.IsAsync(), methodDefinition.IsFunction(), node.Method.Parameters, false, node.MappedInstructions)); } return(base.VisitMethodReferenceExpression(node)); }
public override ICodeNode VisitMethodReferenceExpression(MethodReferenceExpression node) { MethodDefinition methodDefinition = node.Method.Resolve(); TypeDefinition currentType = context.TypeContext.CurrentType; if (methodDefinition == null || methodDefinition.DeclaringType != currentType && !methodDefinition.DeclaringType.IsNestedIn(currentType)) { return base.VisitMethodReferenceExpression(node); } if ((!methodDefinition.IsGetter) && (!methodDefinition.IsSetter) && (methodDefinition.IsCompilerGenerated() || CheckTypeForCompilerGeneratedAttribute(methodDefinition.DeclaringType))) { BlockStatement statement = null; if (methodDefinition.Body != null) { DecompilationContext innerContext = CreateDecompilationContext(methodDefinition); statement = methodDefinition.Body.DecompileLambda(Language, innerContext); if ((statement.Statements.Count == 1) && (statement.Statements[0].CodeNodeType == CodeNodeType.ExpressionStatement) && ((statement.Statements[0] as ExpressionStatement).Expression.CodeNodeType == CodeNodeType.ReturnExpression)) { ReturnExpression returnExpression = (statement.Statements[0] as ExpressionStatement).Expression as ReturnExpression; ShortFormReturnExpression shortFormReturnExpression = new ShortFormReturnExpression(returnExpression.Value, returnExpression.MappedInstructions); statement = new BlockStatement(); statement.Statements.Add(new ExpressionStatement(shortFormReturnExpression)); } this.context.MethodContext.VariableDefinitionToNameMap.AddRange(innerContext.MethodContext.VariableDefinitionToNameMap); this.context.MethodContext.VariableNamesCollection.UnionWith(innerContext.MethodContext.VariableNamesCollection); this.context.MethodContext.AddInnerMethodParametersToContext(innerContext.MethodContext); this.context.MethodContext.GotoStatements.AddRange(innerContext.MethodContext.GotoStatements); this.context.MethodContext.GotoLabels.AddRange(innerContext.MethodContext.GotoLabels); } ExpressionCollection expressionCollection = new ExpressionCollection(); bool hasAnonymousParameter = LambdaExpressionsHelper.HasAnonymousParameter(methodDefinition.Parameters); foreach (ParameterDefinition parameter in methodDefinition.Parameters) { expressionCollection.Add(new LambdaParameterExpression(parameter, !hasAnonymousParameter, null)); } return new LambdaExpression(expressionCollection, statement, methodDefinition.IsAsync(), methodDefinition.IsFunction(), node.Method.Parameters, false, node.MappedInstructions); } return base.VisitMethodReferenceExpression(node); }
private Set GetOnPropertyChangedLambdaSetter(ElementBuilder eb, Property propertyClone, string varName) { Set setter = eb.BuildSetter(); If ifStatement = eb.BuildIf(eb.OpNotEquals("value", varName)); ifStatement.AddNode(eb.BuildAssignment(varName, "value")); ExpressionCollection args = new ExpressionCollection(); LambdaExpression lambda = new LambdaExpression(); var propAccess = new ElementReferenceExpression(propertyClone.Name); lambda.AddNode(propAccess); args.Add(lambda); var propChangedCall = eb.BuildMethodCall("RaisePropertyChanged", args, null); ifStatement.AddNode(propChangedCall); setter.AddNode(ifStatement); return(setter); }
public void TestToXmlStringWithCollectionOfOneItemReturnsItemXmlString( [Values] bool withXmlTag) { // Create expected string of xml nodes const string value = "Value_1"; const string xmlTag = "name_1"; // With tag includes parent xml tag, without is just value string expected = withXmlTag ? NUnitFilterTestHelper.CreateXmlNode(xmlTag, value) : value; ExpressionCollection <INUnitFilterBaseElement> collection = // ReSharper disable once UseObjectOrCollectionInitializer new ExpressionCollection <INUnitFilterBaseElement>(NUnitFilterTestHelper.XmlAndTag); // Add expression to collection collection.Add(new XmlSerializableElementForTest(xmlTag, value, NUnitElementType.And)); Assert.AreEqual(1, collection.Count); Assert.AreEqual(expected, collection.ToXmlString(withXmlTag)); }
public ExpressionCollection <T> Build(List <ISequenceSymbol> sequenceOfSymbols) { var expressionCollection = new ExpressionCollection <T>(); for (var i = 0; i < sequenceOfSymbols.Count(); i++) { var sequenceSymbol = sequenceOfSymbols.ElementAt(i); var expressionBaseToAdd = (ExpressionBase <T>)null; switch (sequenceSymbol) { case ParenthesisOpenSymbol _: var nextParenthesisCloseSymbolIndex = sequenceOfSymbols.FindIndex(i, x => x is ParenthesisCloseSymbol); var subSequenceOfSymbols = sequenceOfSymbols.Skip(i + 1).Take(nextParenthesisCloseSymbolIndex - i).ToList(); // extracting subsequence of symbols inside parentheses expressionBaseToAdd = Build(subSequenceOfSymbols); i = nextParenthesisCloseSymbolIndex; // going to closing parenthesis position break; case ExpressionSymbol <T> _: expressionBaseToAdd = new ExpressionItem <T>((sequenceSymbol as ExpressionSymbol <T>).Expression); break; default: // should not happen // ParenthesisCloseSymbol // LogicalOperatorAndSymbol // LogicalOperatorOrSymbol throw new NotImplementedException(string.Format(GeneralResources.Exception_UnexpectedTokenDuringAnalysisOfSequenceOfSymbols, sequenceSymbol.GetType())); } var nextLogicalOperator = sequenceOfSymbols.ElementAtOrDefault(++i) as ILogicalOperatorSymbol; // going to next position (after closing parenthesis or expression symbol) if (nextLogicalOperator != null) { expressionBaseToAdd.LogicalOperator = nextLogicalOperator.ToLogicalOperator(); } expressionCollection.Add(expressionBaseToAdd); } return(expressionCollection); }
internal static IExpressionCollection DeserializeExpressionCollection(string baseName, SerializationInfo info) { int count = info.GetInt32(baseName); if (count == -1) { return(null); } IExpressionCollection result = new ExpressionCollection(); for (int i = 0; i < count; i++) { string itemBaseName = string.Format("{0}.[{1}]", baseName, i); IExpression current = DeserializeExpression(itemBaseName, info); if (current != null) { result.Add(current); } } return(result); }
public void RebuildDimensions(ref ExpressionCollection elements, ExpressionCollection dimensions) { int count = elements.Count; for (int i = dimensions.Count - 1; i > 0; i--) { ExpressionCollection currentCollection = new ExpressionCollection(); int currentDimension = (int)(dimensions[i] as LiteralExpression).Value; for (int j = 0; j < count; j += currentDimension) { BlockExpression currentBlock = new BlockExpression(null); currentBlock.Expressions = new ExpressionCollection(); for (int k = 0; k < currentDimension; k++) { currentBlock.Expressions.Add(elements[j + k]); } currentCollection.Add(currentBlock); } elements = currentCollection; count /= currentDimension; } }
// int[] arr = new int[] { 1, 2 }; // // == // // int[] arr = new int[2]; // arr[0] = 1; // arr[1] = 2; protected override bool TryMatchInternal(StatementCollection statements, int startIndex, out Statement result, out int replacedStatementsCount) { result = null; replacedStatementsCount = 0; ArrayCreationExpression arrayCreation; Expression assignee; if (!TryGetArrayCreation(statements, startIndex, out arrayCreation, out assignee)) { return false; } if (arrayCreation.Initializer != null && arrayCreation.Initializer.Expressions.Count != 0) { return false; } uint arraySize = GetCreatedArraySize(arrayCreation); Dictionary<uint, Expression> inlinedExpressions = new Dictionary<uint, Expression>(); long lastElementIndex = -1; for (int i = startIndex + 1; i < statements.Count; i++) { Expression expression; if (!TryGetNextExpression(statements[i], out expression)) { break; } BinaryExpression assignment = (statements[i] as ExpressionStatement).Expression as BinaryExpression; if (!IsArrayElementAssignment(assignment, assignee)) { break; } uint currentElementIndex = GetAssignmentIndex(assignment.Left); if (currentElementIndex >= arraySize) { // This happens in System.String System.Runtime.InteropServices.CustomMarshalers.Resource::GetString(System.String) method // from CustomMarshalers.dll (.NET 2 and .NET 4 tests) break; } // Preserve order of initialisation if (currentElementIndex <= lastElementIndex) { break; } List<Instruction> instructions = new List<Instruction>(assignment.Left.UnderlyingSameMethodInstructions); instructions.AddRange(assignment.MappedInstructions); inlinedExpressions[currentElementIndex] = assignment.Right.CloneAndAttachInstructions(instructions); lastElementIndex = currentElementIndex; } if (inlinedExpressions.Count == 0 || (arraySize - inlinedExpressions.Count) > MaxDefaultValues) { return false; } TypeReference arrayElementType = arrayCreation.ElementType; ExpressionCollection expressions = new ExpressionCollection(); for (uint i = 0; i < arraySize; i++) { Expression currentExpression; if (!inlinedExpressions.ContainsKey(i)) { currentExpression = GetTypeDefaultLiteralExpression(arrayElementType); } else { currentExpression = inlinedExpressions[i]; } expressions.Add(currentExpression); } arrayCreation.Initializer = new InitializerExpression(expressions, InitializerType.ArrayInitializer); result = statements[startIndex]; replacedStatementsCount = inlinedExpressions.Count + 1; return true; }
private ExpressionCollection ConvertInitialValues(byte[] initialValues, string typeName) { V_0 = new ExpressionCollection(); if (typeName != null) { if (String.op_Equality(typeName, "Boolean")) { V_2 = 0; while (V_2 < (int)initialValues.Length) { V_0.Add(this.GetLiteralExpression(initialValues[V_2] != 0)); V_2 = V_2 + 1; } return(V_0); } if (String.op_Equality(typeName, "SByte")) { V_3 = 0; while (V_3 < (int)initialValues.Length) { V_0.Add(this.GetLiteralExpression((sbyte)initialValues[V_3])); V_3 = V_3 + 1; } return(V_0); } if (String.op_Equality(typeName, "Byte")) { V_4 = 0; while (V_4 < (int)initialValues.Length) { V_0.Add(this.GetLiteralExpression(initialValues[V_4])); V_4 = V_4 + 1; } return(V_0); } if (String.op_Equality(typeName, "Char")) { V_5 = 0; while (V_5 < (int)initialValues.Length / 2) { V_0.Add(this.GetLiteralExpression(BitConverter.ToChar(initialValues, V_5 * 2))); V_5 = V_5 + 1; } return(V_0); } if (String.op_Equality(typeName, "Int16")) { V_6 = 0; while (V_6 < (int)initialValues.Length / 2) { V_0.Add(this.GetLiteralExpression(BitConverter.ToInt16(initialValues, V_6 * 2))); V_6 = V_6 + 1; } return(V_0); } if (String.op_Equality(typeName, "UInt16")) { V_7 = 0; while (V_7 < (int)initialValues.Length / 2) { V_0.Add(this.GetLiteralExpression(BitConverter.ToUInt16(initialValues, V_7 * 2))); V_7 = V_7 + 1; } return(V_0); } if (String.op_Equality(typeName, "Int32")) { V_8 = 0; while (V_8 < (int)initialValues.Length / 4) { V_0.Add(this.GetLiteralExpression(BitConverter.ToInt32(initialValues, V_8 * 4))); V_8 = V_8 + 1; } return(V_0); } if (String.op_Equality(typeName, "UInt32")) { V_9 = 0; while (V_9 < (int)initialValues.Length / 4) { V_0.Add(this.GetLiteralExpression(BitConverter.ToUInt32(initialValues, V_9 * 4))); V_9 = V_9 + 1; } return(V_0); } if (String.op_Equality(typeName, "Int64")) { V_10 = 0; while (V_10 < (int)initialValues.Length / 8) { V_0.Add(this.GetLiteralExpression(BitConverter.ToInt64(initialValues, V_10 * 8))); V_10 = V_10 + 1; } return(V_0); } if (String.op_Equality(typeName, "UInt64")) { V_11 = 0; while (V_11 < (int)initialValues.Length / 8) { V_0.Add(this.GetLiteralExpression(BitConverter.ToUInt64(initialValues, V_11 * 8))); V_11 = V_11 + 1; } return(V_0); } if (String.op_Equality(typeName, "Single")) { V_12 = 0; while (V_12 < (int)initialValues.Length / 4) { V_0.Add(this.GetLiteralExpression(BitConverter.ToSingle(initialValues, V_12 * 4))); V_12 = V_12 + 1; } return(V_0); } if (String.op_Equality(typeName, "Double")) { V_13 = 0; while (V_13 < (int)initialValues.Length / 8) { V_0.Add(this.GetLiteralExpression(BitConverter.ToDouble(initialValues, V_13 * 8))); V_13 = V_13 + 1; } return(V_0); } } return(null); }
protected override bool TryMatchInternal(StatementCollection statements, int startIndex, out Statement result, out int replacedStatementsCount) { result = null; replacedStatementsCount = 0; if (!this.TryGetObjectCreation(statements, startIndex, out V_0, out V_1)) { return(false); } if (V_0.get_Initializer() != null && V_0.get_Initializer().get_InitializerType() != InitializerType.CollectionInitializer) { return(false); } if (!this.ImplementsInterface(V_0.get_Type(), "System.Collections.IEnumerable")) { return(false); } V_2 = new ExpressionCollection(); V_3 = startIndex + 1; while (V_3 < statements.get_Count() && this.TryGetNextExpression(statements.get_Item(V_3), out V_4) && V_4.get_CodeNodeType() == 19) { V_5 = V_4 as MethodInvocationExpression; V_6 = V_5.get_MethodExpression().get_MethodDefinition(); if (!this.CompareTargets(V_1, V_5.get_MethodExpression().get_Target()) || String.op_Inequality(V_6.get_Name(), "Add") || V_5.get_Arguments().get_Count() == 0) { break; } if (V_5.get_Arguments().get_Count() != 1) { stackVariable88 = V_5.get_Arguments(); stackVariable89 = CollectionInitializationPattern.u003cu003ec.u003cu003e9__1_0; if (stackVariable89 == null) { dummyVar0 = stackVariable89; stackVariable89 = new Func <Expression, Expression>(CollectionInitializationPattern.u003cu003ec.u003cu003e9.u003cTryMatchInternalu003eb__1_0); CollectionInitializationPattern.u003cu003ec.u003cu003e9__1_0 = stackVariable89; } V_7 = new BlockExpression(new ExpressionCollection(stackVariable88.Select <Expression, Expression>(stackVariable89)), null); V_2.Add(V_7); } else { V_2.Add(V_5.get_Arguments().get_Item(0).Clone()); } V_3 = V_3 + 1; } if (V_2.get_Count() == 0) { return(false); } if (V_0.get_Initializer() != null) { V_9 = V_2.GetEnumerator(); try { while (V_9.MoveNext()) { V_10 = V_9.get_Current(); V_0.get_Initializer().get_Expressions().Add(V_10); } } finally { if (V_9 != null) { V_9.Dispose(); } } } else { V_8 = new InitializerExpression(V_2, 0); V_8.set_IsMultiLine(true); V_0.set_Initializer(V_8); } result = statements.get_Item(startIndex); replacedStatementsCount = V_2.get_Count() + 1; return(true); }
private void AddDestructorMember(ElementBuilder elementBuilder) { Method destructor = elementBuilder.AddMethod(null, null, _ActiveClass.Name); destructor.MethodType = MethodTypeEnum.Destructor; ExpressionCollection arguments = new ExpressionCollection(); arguments.Add(GetBooleanLiteral(false)); elementBuilder.AddMethodCall(destructor, STR_Dispose, arguments, null); }
private static void AddDisposeImplementer(ElementBuilder elementBuilder) { Method disposeMethod = elementBuilder.AddMethod(null, null, STR_Dispose); // If implicit interface implementation is supported by the language? disposeMethod.Visibility = MemberVisibility.Public; Expression newCollection = new ElementReferenceExpression("IDisposable.Dispose"); disposeMethod.AddImplementsExpression(newCollection); PrimitiveExpression booleanTrue = GetBooleanLiteral(true); ExpressionCollection argumentsCollection = new ExpressionCollection(); argumentsCollection.Add(booleanTrue); elementBuilder.AddMethodCall(disposeMethod, STR_Dispose, argumentsCollection, null); string thisReference = CodeRush.Language.GenerateElement(new ThisReferenceExpression()); elementBuilder.AddMethodCall(disposeMethod, "GC.SuppressFinalize", new string[] { thisReference }); }
// MyCollection list = new MyCollection() { 1, { 2, 2 } , 3 }; // // == // // MyCollection temp = new MyCollection(); // temp.Add(1); // temp.Add(2, 2); // temp.Add(3); // MyCollection list = temp; protected override bool TryMatchInternal(StatementCollection statements, int startIndex, out Statement result, out int replacedStatementsCount) { result = null; replacedStatementsCount = 0; ObjectCreationExpression objectCreation; Expression assignee; if (!TryGetObjectCreation(statements, startIndex, out objectCreation, out assignee)) { return false; } if (objectCreation.Initializer != null && objectCreation.Initializer.InitializerType != InitializerType.CollectionInitializer) { return false; } if (!ImplementsInterface(objectCreation.Type, "System.Collections.IEnumerable")) { return false; } ExpressionCollection addedExpressions = new ExpressionCollection(); for (int i = startIndex + 1; i < statements.Count; i++) { Expression expression; if (!TryGetNextExpression(statements[i], out expression)) { break; } if (expression.CodeNodeType != CodeNodeType.MethodInvocationExpression) { break; } MethodInvocationExpression methodInvocation = (expression as MethodInvocationExpression); MethodDefinition methodDefinition = methodInvocation.MethodExpression.MethodDefinition; if (!CompareTargets(assignee, methodInvocation.MethodExpression.Target)) { break; } if (methodDefinition.Name != "Add") { break; } if (methodInvocation.Arguments.Count == 0) { break; } else if (methodInvocation.Arguments.Count == 1) { addedExpressions.Add(methodInvocation.Arguments[0].Clone()); } else { ExpressionCollection currentArguments = new ExpressionCollection( methodInvocation.Arguments.Select(x => x.Clone())); BlockExpression blockExpression = new BlockExpression(currentArguments, null); addedExpressions.Add(blockExpression); } } if (addedExpressions.Count == 0) { return false; } if (objectCreation.Initializer == null) { var initializer = new InitializerExpression(addedExpressions, InitializerType.CollectionInitializer); initializer.IsMultiLine = true; objectCreation.Initializer = initializer; } else { foreach (var item in addedExpressions) { objectCreation.Initializer.Expressions.Add(item); } } result = statements[startIndex]; replacedStatementsCount = addedExpressions.Count + 1; return true; }
private ExpressionCollection ConvertInitialValues(byte[] initialValues, string typeName) { ExpressionCollection literals = new ExpressionCollection(); switch (typeName) { case "Boolean": for (int j = 0; j < initialValues.Length; j++) { literals.Add(GetLiteralExpression(initialValues[j] != 0)); } return literals; case "SByte": for (int j = 0; j < initialValues.Length; j++) { literals.Add(GetLiteralExpression((sbyte)initialValues[j])); } return literals; case "Byte": for (int j = 0; j < initialValues.Length; j++) { literals.Add(GetLiteralExpression(initialValues[j])); } return literals; case "Char": for (int j = 0; j < initialValues.Length / 2; j++) { literals.Add(GetLiteralExpression(BitConverter.ToChar(initialValues, j * 2))); } return literals; case "Int16": for (int j = 0; j < initialValues.Length / 2; j++) { literals.Add(GetLiteralExpression(BitConverter.ToInt16(initialValues, j * 2))); } return literals; case "UInt16": for (int j = 0; j < initialValues.Length / 2; j++) { literals.Add(GetLiteralExpression(BitConverter.ToUInt16(initialValues, j * 2))); } return literals; case "Int32": for (int j = 0; j < initialValues.Length / 4; j++) { literals.Add(GetLiteralExpression(BitConverter.ToInt32(initialValues, j * 4))); } return literals; case "UInt32": for (int j = 0; j < initialValues.Length / 4; j++) { literals.Add(GetLiteralExpression(BitConverter.ToUInt32(initialValues, j * 4))); } return literals; case "Int64": for (int j = 0; j < initialValues.Length / 8; j++) { literals.Add(GetLiteralExpression(BitConverter.ToInt64(initialValues, j * 8))); } return literals; case "UInt64": for (int j = 0; j < initialValues.Length / 8; j++) { literals.Add(GetLiteralExpression(BitConverter.ToUInt64(initialValues, j * 8))); } return literals; case "Single": for (int j = 0; j < initialValues.Length / 4; j++) { literals.Add(GetLiteralExpression(BitConverter.ToSingle(initialValues, j * 4))); } return literals; case "Double": for (int j = 0; j < initialValues.Length / 8; j++) { literals.Add(GetLiteralExpression(BitConverter.ToDouble(initialValues, j * 8))); } return literals; default: return null; } }
private Set GetSetter(ElementBuilder eb, Property propertyClone, string varName) { Set setter = eb.BuildSetter(); If ifStatement = eb.BuildIf(eb.OpNotEquals("value", varName)); ifStatement.AddNode(eb.BuildAssignment(varName, "value")); ExpressionCollection args = new ExpressionCollection(); args.Add(new SnippetExpression(CodeRush.StrUtil.AddQuotes(propertyClone.Name))); ExpressionCollection arguments = new ExpressionCollection(); arguments.Add(eb.BuildThisReferenceExpression()); arguments.Add(eb.BuildObjectCreationExpression("PropertyChangedEventArgs", args)); if (CodeRush.Language.IsCSharp) { ifStatement.AddNode(eb.BuildMethodCall("PropertyChanged", arguments, null /* qualifier */)); } else if (CodeRush.Language.IsBasic) { RaiseEvent raiseEvent = new RaiseEvent(eb.BuildMethodCallExpression("PropertyChanged", arguments)); ifStatement.AddNode(raiseEvent); } setter.AddNode(ifStatement); return setter; }
protected override bool TryMatchInternal(StatementCollection statements, int startIndex, out Statement result, out int replacedStatementsCount) { result = null; replacedStatementsCount = 0; if (!this.TryGetObjectCreation(statements, startIndex, out V_0, out V_1)) { return(false); } V_2 = new ExpressionCollection(); V_3 = new HashSet <string>(); if (V_0.get_Initializer() != null) { if (V_0.get_Initializer().get_InitializerType() != 1) { return(false); } V_4 = V_0.get_Initializer().get_Expressions().GetEnumerator(); try { while (V_4.MoveNext()) { V_5 = V_4.get_Current(); V_6 = this.GetName((V_5 as BinaryExpression).get_Left()); dummyVar0 = V_3.Add(V_6); } } finally { if (V_4 != null) { V_4.Dispose(); } } } V_7 = startIndex + 1; while (V_7 < statements.get_Count() && this.TryGetNextExpression(statements.get_Item(V_7), out V_8)) { V_9 = V_8 as BinaryExpression; if (!this.IsObjectPropertyOrFieldAssignment(V_9, V_1)) { break; } V_10 = null; if (V_9.get_Left().get_CodeNodeType() != 42) { if (V_9.get_Left().get_CodeNodeType() == 30) { V_13 = (V_9.get_Left() as FieldReferenceExpression).get_Field().Resolve(); if (!this.Visit(V_13.get_Name(), V_3)) { break; } V_10 = new FieldInitializerExpression(V_13, V_13.get_FieldType(), V_9.get_Left().get_UnderlyingSameMethodInstructions()); } } else { V_12 = (V_9.get_Left() as PropertyReferenceExpression).get_Property(); if (!this.Visit(V_12.get_Name(), V_3)) { break; } V_10 = new PropertyInitializerExpression(V_12, V_12.get_PropertyType(), V_9.get_Left().get_UnderlyingSameMethodInstructions()); } V_11 = new BinaryExpression(26, V_10, V_9.get_Right().Clone(), this.typeSystem, null, false); V_2.Add(V_11); V_7 = V_7 + 1; } if (V_2.get_Count() == 0) { return(false); } if (V_0.get_Initializer() != null) { V_4 = V_2.GetEnumerator(); try { while (V_4.MoveNext()) { V_15 = V_4.get_Current(); V_0.get_Initializer().get_Expressions().Add(V_15); } } finally { if (V_4 != null) { V_4.Dispose(); } } } else { V_14 = new InitializerExpression(V_2, 1); V_14.set_IsMultiLine(true); V_0.set_Initializer(V_14); } result = statements.get_Item(startIndex); replacedStatementsCount = V_2.get_Count() + 1; return(true); }
private string GetNewConstructorCall(ObjectCreationExpression objectCreationWithInitializer, ITypeElement type) { string result = String.Empty; if (type == null || objectCreationWithInitializer == null || objectCreationWithInitializer.ObjectInitializer == null) return result; ExpressionCollection arguments = objectCreationWithInitializer.ObjectInitializer.Initializers; ExpressionCollection newArgs = new ExpressionCollection(); foreach (Expression argument in arguments) { MemberInitializerExpression memberInitializerExpression = argument as MemberInitializerExpression; if (memberInitializerExpression == null) continue; newArgs.Add(memberInitializerExpression.Value); } ObjectCreationExpression newObjectCreationExpression = new ObjectCreationExpression(new TypeReferenceExpression(type.Name), newArgs); if (newObjectCreationExpression != null) result = CodeRush.Language.GenerateElement(newObjectCreationExpression); return result; }
private Set GetOnPropertyChangedLambdaSetter(ElementBuilder eb, Property propertyClone, string varName) { Set setter = eb.BuildSetter(); If ifStatement = eb.BuildIf(eb.OpNotEquals("value", varName)); ifStatement.AddNode(eb.BuildAssignment(varName, "value")); ExpressionCollection args = new ExpressionCollection(); LambdaExpression lambda = new LambdaExpression(); var propAccess = new ElementReferenceExpression(propertyClone.Name); lambda.AddNode(propAccess); args.Add(lambda); var propChangedCall = eb.BuildMethodCall("RaisePropertyChanged", args, null); ifStatement.AddNode(propChangedCall); setter.AddNode(ifStatement); return setter; }
// int[] arr = new int[] { 1, 2 }; // // == // // int[] arr = new int[2]; // arr[0] = 1; // arr[1] = 2; protected override bool TryMatchInternal(StatementCollection statements, int startIndex, out Statement result, out int replacedStatementsCount) { result = null; replacedStatementsCount = 0; ArrayCreationExpression arrayCreation; Expression assignee; if (!TryGetArrayCreation(statements, startIndex, out arrayCreation, out assignee)) { return(false); } if (arrayCreation.Initializer != null && arrayCreation.Initializer.Expressions.Count != 0) { return(false); } uint arraySize = GetCreatedArraySize(arrayCreation); Dictionary <uint, Expression> inlinedExpressions = new Dictionary <uint, Expression>(); long lastElementIndex = -1; for (int i = startIndex + 1; i < statements.Count; i++) { Expression expression; if (!TryGetNextExpression(statements[i], out expression)) { break; } BinaryExpression assignment = (statements[i] as ExpressionStatement).Expression as BinaryExpression; if (!IsArrayElementAssignment(assignment, assignee)) { break; } uint currentElementIndex = GetAssignmentIndex(assignment.Left); if (currentElementIndex >= arraySize) { // This happens in System.String System.Runtime.InteropServices.CustomMarshalers.Resource::GetString(System.String) method // from CustomMarshalers.dll (.NET 2 and .NET 4 tests) break; } // Preserve order of initialisation if (currentElementIndex <= lastElementIndex) { break; } List <Instruction> instructions = new List <Instruction>(assignment.Left.UnderlyingSameMethodInstructions); instructions.AddRange(assignment.MappedInstructions); inlinedExpressions[currentElementIndex] = assignment.Right.CloneAndAttachInstructions(instructions); lastElementIndex = currentElementIndex; } if (inlinedExpressions.Count == 0 || (arraySize - inlinedExpressions.Count) > MaxDefaultValues) { return(false); } TypeReference arrayElementType = arrayCreation.ElementType; ExpressionCollection expressions = new ExpressionCollection(); for (uint i = 0; i < arraySize; i++) { Expression currentExpression; if (!inlinedExpressions.ContainsKey(i)) { currentExpression = GetTypeDefaultLiteralExpression(arrayElementType); } else { currentExpression = inlinedExpressions[i]; } expressions.Add(currentExpression); } arrayCreation.Initializer = new InitializerExpression(expressions, InitializerType.ArrayInitializer); result = statements[startIndex]; replacedStatementsCount = inlinedExpressions.Count + 1; return(true); }
public override ICodeNode VisitObjectCreationExpression(ObjectCreationExpression node) { if (state == State.ReplaceDelegate && node.Arguments != null && node.Arguments.Count == 2 && node.Arguments[0].CodeNodeType == CodeNodeType.VariableReferenceExpression && node.Arguments[1].CodeNodeType == CodeNodeType.MethodReferenceExpression && delegateCopies.Contains((node.Arguments[0] as VariableReferenceExpression).Variable)) { //final check inserted here for optimization TypeDefinition objectType = node.Constructor.DeclaringType.Resolve(); if (objectType == null || objectType.BaseType == null || objectType.BaseType.FullName != "System.MulticastDelegate") { return base.VisitObjectCreationExpression(node); } MethodReference methodReference = (node.Arguments[1] as MethodReferenceExpression).Method; MethodDefinition methodDefinition = (node.Arguments[1] as MethodReferenceExpression).MethodDefinition; MethodSpecificContext delegateMethodContext = new MethodSpecificContext(methodDefinition.Body); DecompilationContext innerContext = new DecompilationContext(delegateMethodContext, context.TypeContext, context.ModuleContext, context.AssemblyContext); delegateMethodContext.FieldToExpression = fieldDefToAssignedValueMap; BlockStatement methodStatements = methodDefinition.Body.DecompileLambda(Language, innerContext); if ((methodStatements.Statements.Count == 1) && (methodStatements.Statements[0].CodeNodeType == CodeNodeType.ExpressionStatement) && ((methodStatements.Statements[0] as ExpressionStatement).Expression.CodeNodeType == CodeNodeType.ReturnExpression)) { ReturnExpression returnExpression = (methodStatements.Statements[0] as ExpressionStatement).Expression as ReturnExpression; ShortFormReturnExpression shortFormReturnExpression = new ShortFormReturnExpression(returnExpression.Value, returnExpression.MappedInstructions); methodStatements = new BlockStatement(); methodStatements.Statements.Add(new ExpressionStatement(shortFormReturnExpression)); } this.context.MethodContext.VariableDefinitionToNameMap.AddRange(innerContext.MethodContext.VariableDefinitionToNameMap); this.context.MethodContext.VariableNamesCollection.UnionWith(innerContext.MethodContext.VariableNamesCollection); this.context.MethodContext.AddInnerMethodParametersToContext(innerContext.MethodContext); this.context.MethodContext.GotoStatements.AddRange(innerContext.MethodContext.GotoStatements); this.context.MethodContext.GotoLabels.AddRange(innerContext.MethodContext.GotoLabels); ExpressionCollection expressionCollection = new ExpressionCollection(); bool hasAnonymousParamterer = LambdaExpressionsHelper.HasAnonymousParameter(methodDefinition.Parameters); foreach (ParameterDefinition parameter in methodDefinition.Parameters) { expressionCollection.Add(new LambdaParameterExpression(parameter, !hasAnonymousParamterer, null)); } delegatesFound.Add(methodStatements); LambdaExpression lambdaExpression = new LambdaExpression(expressionCollection, methodStatements, methodDefinition.IsAsync(), methodDefinition.IsFunction(), methodReference.Parameters, false, node.Arguments[1].MappedInstructions) { ExpressionType = objectType }; DelegateCreationExpression result = new DelegateCreationExpression(node.Constructor.DeclaringType, lambdaExpression, node.Arguments[0], node.MappedInstructions); return result; } return base.VisitObjectCreationExpression(node); }
// Person person = new Person { Name = "John", Age = 20 }; // // == // // Person person = new Person(); // person.Name = "John"; // person.Age = 20; protected override bool TryMatchInternal(StatementCollection statements, int startIndex, out Statement result, out int replacedStatementsCount) { result = null; replacedStatementsCount = 0; ObjectCreationExpression objectCreation; Expression assignee; if (!TryGetObjectCreation(statements, startIndex, out objectCreation, out assignee)) { return(false); } ExpressionCollection inlinedExpressions = new ExpressionCollection(); HashSet <string> visitedPropertyNames = new HashSet <string>(); if (objectCreation.Initializer != null) { if (objectCreation.Initializer.InitializerType != InitializerType.ObjectInitializer) { return(false); } foreach (var item in objectCreation.Initializer.Expressions) { string name = GetName((item as BinaryExpression).Left); visitedPropertyNames.Add(name); } } for (int i = startIndex + 1; i < statements.Count; i++) { Expression expression; if (!TryGetNextExpression(statements[i], out expression)) { break; } BinaryExpression assignment = expression as BinaryExpression; if (!IsObjectPropertyOrFieldAssignment(assignment, assignee)) { break; } Expression initializer = null; if (assignment.Left.CodeNodeType == CodeNodeType.PropertyReferenceExpression) { PropertyDefinition property = (assignment.Left as PropertyReferenceExpression).Property; if (!Visit(property.Name, visitedPropertyNames)) { break; } initializer = new PropertyInitializerExpression(property, property.PropertyType, assignment.Left.UnderlyingSameMethodInstructions); } else if (assignment.Left.CodeNodeType == CodeNodeType.FieldReferenceExpression) { FieldDefinition field = (assignment.Left as FieldReferenceExpression).Field.Resolve(); if (!Visit(field.Name, visitedPropertyNames)) { break; } initializer = new FieldInitializerExpression(field, field.FieldType, assignment.Left.UnderlyingSameMethodInstructions); } var inlinedAssignment = new BinaryExpression(BinaryOperator.Assign, initializer, assignment.Right.Clone(), this.typeSystem, null); inlinedExpressions.Add(inlinedAssignment); } if (inlinedExpressions.Count == 0) { return(false); } if (objectCreation.Initializer == null) { var initializer = new InitializerExpression(inlinedExpressions, InitializerType.ObjectInitializer); initializer.IsMultiLine = true; objectCreation.Initializer = initializer; } else { foreach (var item in inlinedExpressions) { objectCreation.Initializer.Expressions.Add(item); } } result = statements[startIndex]; replacedStatementsCount = inlinedExpressions.Count + 1; return(true); }
private bool ExtendsTheCallerType(IMethodElement method, ITypeElement callerType,Expression qualifier) { if (method == null || callerType == null) return false; if (method.Parameters.Count == 0) return false; ISourceTreeResolver resolver = ParserServices.SourceTreeResolver; ExpressionCollection arguments = new ExpressionCollection(); arguments.Add(qualifier); method = GenericElementActivator.ActivateMemberIfNeeded(resolver, method, arguments, null, ArgumentsHelper.ResolveArgumentTypes(resolver,arguments)) as IMethodElement; if (method == null) return false; IParameterElement extensionParam = method.Parameters[0] as IParameterElement; if (extensionParam == null) return false; ITypeReferenceExpression typeRef = extensionParam.Type; if (typeRef == null) return false; ITypeElement type = typeRef.GetDeclaration() as ITypeElement; if (type == null) return false; IArrayTypeElement arrayType = callerType as IArrayTypeElement; //if (arrayType != null) //{ // return true; //} //else return ArgumentsHelper.HasParamConversion(resolver, extensionParam, callerType, qualifier, TypeConversionMode.ImplicitConversion); }
private ExpressionCollection ConvertInitialValues(byte[] initialValues, string typeName) { ExpressionCollection literals = new ExpressionCollection(); switch (typeName) { case "Boolean": for (int j = 0; j < initialValues.Length; j++) { literals.Add(GetLiteralExpression(initialValues[j] != 0)); } return(literals); case "SByte": for (int j = 0; j < initialValues.Length; j++) { literals.Add(GetLiteralExpression((sbyte)initialValues[j])); } return(literals); case "Byte": for (int j = 0; j < initialValues.Length; j++) { literals.Add(GetLiteralExpression(initialValues[j])); } return(literals); case "Char": for (int j = 0; j < initialValues.Length / 2; j++) { literals.Add(GetLiteralExpression(BitConverter.ToChar(initialValues, j * 2))); } return(literals); case "Int16": for (int j = 0; j < initialValues.Length / 2; j++) { literals.Add(GetLiteralExpression(BitConverter.ToInt16(initialValues, j * 2))); } return(literals); case "UInt16": for (int j = 0; j < initialValues.Length / 2; j++) { literals.Add(GetLiteralExpression(BitConverter.ToUInt16(initialValues, j * 2))); } return(literals); case "Int32": for (int j = 0; j < initialValues.Length / 4; j++) { literals.Add(GetLiteralExpression(BitConverter.ToInt32(initialValues, j * 4))); } return(literals); case "UInt32": for (int j = 0; j < initialValues.Length / 4; j++) { literals.Add(GetLiteralExpression(BitConverter.ToUInt32(initialValues, j * 4))); } return(literals); case "Int64": for (int j = 0; j < initialValues.Length / 8; j++) { literals.Add(GetLiteralExpression(BitConverter.ToInt64(initialValues, j * 8))); } return(literals); case "UInt64": for (int j = 0; j < initialValues.Length / 8; j++) { literals.Add(GetLiteralExpression(BitConverter.ToUInt64(initialValues, j * 8))); } return(literals); case "Single": for (int j = 0; j < initialValues.Length / 4; j++) { literals.Add(GetLiteralExpression(BitConverter.ToSingle(initialValues, j * 4))); } return(literals); case "Double": for (int j = 0; j < initialValues.Length / 8; j++) { literals.Add(GetLiteralExpression(BitConverter.ToDouble(initialValues, j * 8))); } return(literals); default: return(null); } }
// Person person = new Person { Name = "John", Age = 20 }; // // == // // Person person = new Person(); // person.Name = "John"; // person.Age = 20; protected override bool TryMatchInternal(StatementCollection statements, int startIndex, out Statement result, out int replacedStatementsCount) { result = null; replacedStatementsCount = 0; ObjectCreationExpression objectCreation; Expression assignee; if (!TryGetObjectCreation(statements, startIndex, out objectCreation, out assignee)) { return false; } ExpressionCollection inlinedExpressions = new ExpressionCollection(); HashSet<string> visitedPropertyNames = new HashSet<string>(); if (objectCreation.Initializer != null) { if (objectCreation.Initializer.InitializerType != InitializerType.ObjectInitializer) { return false; } foreach (var item in objectCreation.Initializer.Expressions) { string name = GetName((item as BinaryExpression).Left); visitedPropertyNames.Add(name); } } for (int i = startIndex + 1; i < statements.Count; i++) { Expression expression; if (!TryGetNextExpression(statements[i], out expression)) { break; } BinaryExpression assignment = expression as BinaryExpression; if (!IsObjectPropertyOrFieldAssignment(assignment, assignee)) { break; } Expression initializer = null; if (assignment.Left.CodeNodeType == CodeNodeType.PropertyReferenceExpression) { PropertyDefinition property = (assignment.Left as PropertyReferenceExpression).Property; if (!Visit(property.Name, visitedPropertyNames)) { break; } initializer = new PropertyInitializerExpression(property, property.PropertyType, assignment.Right.UnderlyingSameMethodInstructions); } else if (assignment.Left.CodeNodeType == CodeNodeType.FieldReferenceExpression) { FieldDefinition field = (assignment.Left as FieldReferenceExpression).Field.Resolve(); if (!Visit(field.Name, visitedPropertyNames)) { break; } initializer = new FieldInitializerExpression(field, field.FieldType, assignment.Right.UnderlyingSameMethodInstructions); } var inlinedAssignment = new BinaryExpression(BinaryOperator.Assign, initializer, assignment.Right.Clone(), this.typeSystem, null); inlinedExpressions.Add(inlinedAssignment); } if (inlinedExpressions.Count == 0) { return false; } if (objectCreation.Initializer == null) { var initializer = new InitializerExpression(inlinedExpressions, InitializerType.ObjectInitializer); initializer.IsMultiLine = true; objectCreation.Initializer = initializer; } else { foreach (var item in inlinedExpressions) { objectCreation.Initializer.Expressions.Add(item); } } result = statements[startIndex]; replacedStatementsCount = inlinedExpressions.Count + 1; return true; }
// MyCollection list = new MyCollection() { 1, { 2, 2 } , 3 }; // // == // // MyCollection temp = new MyCollection(); // temp.Add(1); // temp.Add(2, 2); // temp.Add(3); // MyCollection list = temp; protected override bool TryMatchInternal(StatementCollection statements, int startIndex, out Statement result, out int replacedStatementsCount) { result = null; replacedStatementsCount = 0; ObjectCreationExpression objectCreation; Expression assignee; if (!TryGetObjectCreation(statements, startIndex, out objectCreation, out assignee)) { return(false); } if (objectCreation.Initializer != null && objectCreation.Initializer.InitializerType != InitializerType.CollectionInitializer) { return(false); } if (!ImplementsInterface(objectCreation.Type, "System.Collections.IEnumerable")) { return(false); } ExpressionCollection addedExpressions = new ExpressionCollection(); for (int i = startIndex + 1; i < statements.Count; i++) { Expression expression; if (!TryGetNextExpression(statements[i], out expression)) { break; } if (expression.CodeNodeType != CodeNodeType.MethodInvocationExpression) { break; } MethodInvocationExpression methodInvocation = (expression as MethodInvocationExpression); MethodDefinition methodDefinition = methodInvocation.MethodExpression.MethodDefinition; if (!CompareTargets(assignee, methodInvocation.MethodExpression.Target)) { break; } if (methodDefinition.Name != "Add") { break; } if (methodInvocation.Arguments.Count == 0) { break; } else if (methodInvocation.Arguments.Count == 1) { addedExpressions.Add(methodInvocation.Arguments[0].Clone()); } else { ExpressionCollection currentArguments = new ExpressionCollection( methodInvocation.Arguments.Select(x => x.Clone())); BlockExpression blockExpression = new BlockExpression(currentArguments, null); addedExpressions.Add(blockExpression); } } if (addedExpressions.Count == 0) { return(false); } if (objectCreation.Initializer == null) { var initializer = new InitializerExpression(addedExpressions, InitializerType.CollectionInitializer); initializer.IsMultiLine = true; objectCreation.Initializer = initializer; } else { foreach (var item in addedExpressions) { objectCreation.Initializer.Expressions.Add(item); } } result = statements[startIndex]; replacedStatementsCount = addedExpressions.Count + 1; return(true); }
public void RebuildDimensions(ref ExpressionCollection elements, ExpressionCollection dimensions) { int count = elements.Count; for (int i = dimensions.Count - 1; i > 0; i--) { ExpressionCollection currentCollection = new ExpressionCollection(); int currentDimension = (int)(dimensions[i] as LiteralExpression).Value; for (int j = 0; j < count; j += currentDimension) { BlockExpression currentBlock = new BlockExpression(null); currentBlock.Expressions = new ExpressionCollection(); for (int k = 0; k < currentDimension; k++) { currentBlock.Expressions.Add(elements[j + k]); } currentCollection.Add(currentBlock); } elements = currentCollection; count /= currentDimension; } }
} // refactoringProvider_Apply(sender, ea) /// <summary> /// Get new delayed property declaration /// </summary> private string GetNewDelayedPropertyDeclaration(ElementBuilder elementBuilder, Property oldProperty) { string propName = oldProperty.Name; string typeName = oldProperty.GetTypeName(); Property newProperty = elementBuilder.AddProperty(null, typeName, propName); newProperty.Visibility = oldProperty.Visibility; newProperty.IsStatic = oldProperty.IsStatic; newProperty.IsVirtual = oldProperty.IsVirtual; newProperty.IsOverride = oldProperty.IsOverride; newProperty.IsExplicitInterfaceMember = oldProperty.IsExplicitInterfaceMember; AttributeSection attrSection = elementBuilder.AddAttributeSection(newProperty); elementBuilder.AddAttribute(attrSection, "Delayed"); if (oldProperty.HasGetter) { Get getter = elementBuilder.AddGetter(newProperty); ExpressionCollection expressionCollection = new ExpressionCollection(); expressionCollection.Add(new PrimitiveExpression(String.Format("\"{0}\"", propName))); string methodName = String.Format("GetDelayedPropertyValue<{0}>", typeName); elementBuilder.AddReturn(getter, elementBuilder.BuildMethodCall(methodName, expressionCollection, null)); } if (oldProperty.HasSetter) { Set setter = elementBuilder.AddSetter(newProperty); ExpressionCollection expressionCollection = new ExpressionCollection(); expressionCollection.Add(new PrimitiveExpression(String.Format("\"{0}\"", propName))); expressionCollection.Add(new ElementReferenceExpression("value")); string methodName = String.Format("SetDelayedPropertyValue<{0}>", typeName); elementBuilder.AddMethodCall(setter, methodName, expressionCollection, null); } // if return elementBuilder.GenerateCode(); } // GetNewDelayedPropertyDeclaration(elementBuilder, oldProperty)
private ExpressionCollection CopyMethodParametersAsArguments(MethodDefinition method) { ExpressionCollection result = new ExpressionCollection(); if (method.HasParameters) { foreach (ParameterDefinition param in method.Parameters) { result.Add(new ArgumentReferenceExpression(param, null)); } } return result; }
} // GetNewDelayedPropertyDeclaration(elementBuilder, oldProperty) /// <summary> /// Get new property declaration /// </summary> private string GetNewPropertyDeclaration(ElementBuilder elementBuilder, Property oldProperty) { string propName = oldProperty.Name; string typeName = oldProperty.GetTypeName(); string fieldVariableName = CodeRush.Strings.Get("FormatFieldName", propName); Variable fieldVar = elementBuilder.AddVariable(null, typeName, fieldVariableName); fieldVar.IsStatic = oldProperty.IsStatic; fieldVar.Visibility = MemberVisibility.Private; Property newProperty = elementBuilder.AddProperty(null, typeName, propName); newProperty.Visibility = oldProperty.Visibility; newProperty.IsStatic = oldProperty.IsStatic; newProperty.IsVirtual = oldProperty.IsVirtual; newProperty.IsOverride = oldProperty.IsOverride; newProperty.IsExplicitInterfaceMember = oldProperty.IsExplicitInterfaceMember; if (oldProperty.HasGetter) { Get getter = elementBuilder.AddGetter(newProperty); elementBuilder.AddReturn(getter, fieldVariableName); } if (oldProperty.HasSetter) { Set setter = elementBuilder.AddSetter(newProperty); ExpressionCollection expressionCollection = new ExpressionCollection(); expressionCollection.Add(new PrimitiveExpression(String.Format("\"{0}\"", propName))); expressionCollection.Add(new ArgumentDirectionExpression(ArgumentDirection.Ref, new ElementReferenceExpression(fieldVariableName))); expressionCollection.Add(new ElementReferenceExpression("value")); elementBuilder.AddMethodCall(setter, "SetPropertyValue", expressionCollection, null); } // if return elementBuilder.GenerateCode(); } // GetNewPropertyDeclaration(elementBuilder, oldProperty)
private void RegisterExpressions() { ExpressionCollection.Add(FilterOperator.Contains, (memberExpression, propertyInfo, value) => { var constant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, value); MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) }); Expression compExpr = Expression.Call(memberExpression, method, constant); return(compExpr); }); ExpressionCollection.Add(FilterOperator.DoesNotContain, (memberExpression, propertyInfo, value) => { var constant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, value); MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) }); Expression compExpr = Expression.Not(Expression.Call(memberExpression, method, constant)); compExpr = HandleNullComparison(compExpr, memberExpression, propertyInfo, value); return(compExpr); }); ExpressionCollection.Add(FilterOperator.IsContainedIn, (memberExpression, propertyInfo, value) => { var constant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, value); Expression compExpr = Expression.Call(constant, "Contains", new Type[] { }, memberExpression); return(compExpr); }); ExpressionCollection.Add(FilterOperator.IsNotContainedIn, (memberExpression, propertyInfo, value) => { var constant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, value); Expression compExpr = Expression.Not(Expression.Call(constant, "Contains", new Type[] { }, memberExpression)); return(compExpr); }); ExpressionCollection.Add(FilterOperator.StartsWith, (memberExpression, propertyInfo, value) => { var constant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, value); MethodInfo method = typeof(string).GetMethod("StartsWith", new[] { typeof(string) }); Expression compExpr = Expression.Call(memberExpression, method, constant); return(compExpr); }); ExpressionCollection.Add(FilterOperator.EndsWith, (memberExpression, propertyInfo, value) => { var constant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, value); MethodInfo method = typeof(string).GetMethod("EndsWith", new[] { typeof(string) }); Expression compExpr = Expression.Call(memberExpression, method, constant); return(compExpr); }); ExpressionCollection.Add(FilterOperator.IsEqualTo, (memberExpression, propertyInfo, value) => { var constant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, value); Expression compExpr = Expression.Equal(memberExpression, constant); return(compExpr); }); ExpressionCollection.Add(FilterOperator.IsEqualToOrNull, (memberExpression, propertyInfo, value) => { var constant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, value); Expression compExpr = Expression.Equal(memberExpression, constant); var nullConstant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, null); Expression nullCompExpr = Expression.Equal(memberExpression, nullConstant); return(Expression.Or(compExpr, nullCompExpr)); }); ExpressionCollection.Add(FilterOperator.IsNotEqualTo, (memberExpression, propertyInfo, value) => { var constant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, value); Expression compExpr = Expression.NotEqual(memberExpression, constant); compExpr = HandleNullComparison(compExpr, memberExpression, propertyInfo, value); return(compExpr); }); ExpressionCollection.Add(FilterOperator.IsGreaterThan, (memberExpression, propertyInfo, value) => { var constant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, value); Expression compExpr = Expression.GreaterThan(memberExpression, constant); return(compExpr); }); ExpressionCollection.Add(FilterOperator.IsGreaterThanOrEqualTo, (memberExpression, propertyInfo, value) => { var constant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, value); Expression compExpr = Expression.GreaterThanOrEqual(memberExpression, constant); return(compExpr); }); ExpressionCollection.Add(FilterOperator.IsLessThan, (memberExpression, propertyInfo, value) => { var constant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, value); Expression compExpr = Expression.LessThan(memberExpression, constant); return(compExpr); }); ExpressionCollection.Add(FilterOperator.IsGreaterThanOrNull, (memberExpression, propertyInfo, value) => { var constant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, value); Expression compExpr = Expression.GreaterThan(memberExpression, constant); var nullConstant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, null); Expression nullCompExpr = Expression.Equal(memberExpression, nullConstant); return(Expression.Or(compExpr, nullCompExpr)); }); ExpressionCollection.Add(FilterOperator.IsGreaterThanOrEqualToOrNull, (memberExpression, propertyInfo, value) => { var constant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, value); Expression compExpr = Expression.GreaterThanOrEqual(memberExpression, constant); var nullConstant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, null); Expression nullCompExpr = Expression.Equal(memberExpression, nullConstant); return(Expression.Or(compExpr, nullCompExpr)); }); ExpressionCollection.Add(FilterOperator.FullText, (memberExpression, propertyInfo, value) => { var ftsValue = FtsInterceptor.Fts(Convert.ToString(value)); var constant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, ftsValue); MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) }); Expression compExpr = Expression.Call(memberExpression, method, constant); return(compExpr); }); }
private void RegisterExpressions() { ExpressionCollection.Add(FilterOperator.IsEqualTo, (memberExpression, propertyInfo, value) => { var interval = (DateInterval)value; var startConstant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, interval.StartDate); var endConstant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, interval.EndDate); Expression startExpression = Expression.GreaterThanOrEqual(memberExpression, startConstant); Expression endExpression = Expression.LessThan(memberExpression, endConstant); return(Expression.AndAlso(startExpression, endExpression)); }); ExpressionCollection.Add(FilterOperator.IsNotEqualTo, (memberExpression, propertyInfo, value) => { var interval = (DateInterval)value; var startConstant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, interval.StartDate); var endConstant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, interval.EndDate); Expression startExpression = Expression.LessThan(memberExpression, startConstant); Expression endExpression = Expression.GreaterThanOrEqual(memberExpression, endConstant); Expression compExpr = Expression.OrElse(startExpression, endExpression); compExpr = HandleNullComparison(compExpr, memberExpression, propertyInfo, value); return(compExpr); }); ExpressionCollection.Add(FilterOperator.IsGreaterThan, (memberExpression, propertyInfo, value) => { var interval = (DateInterval)value; var endConstant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, interval.EndDate); return(Expression.GreaterThanOrEqual(memberExpression, endConstant)); }); ExpressionCollection.Add(FilterOperator.IsGreaterThanOrEqualTo, (memberExpression, propertyInfo, value) => { var interval = (DateInterval)value; var startConstant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, interval.StartDate); return(Expression.GreaterThanOrEqual(memberExpression, startConstant)); }); ExpressionCollection.Add(FilterOperator.IsLessThan, (memberExpression, propertyInfo, value) => { var interval = (DateInterval)value; var startConstant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, interval.StartDate); return(Expression.LessThan(memberExpression, startConstant)); }); ExpressionCollection.Add(FilterOperator.IsLessThanOrEqualTo, (memberExpression, propertyInfo, value) => { var interval = (DateInterval)value; var endConstant = GetConstantWithNullableCastHandle(memberExpression, propertyInfo, interval.EndDate); return(Expression.LessThan(memberExpression, endConstant)); }); }