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 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)); }
/// <summary> /// Creates an element that represents an aggregation of facts. /// </summary> /// <param name="resultType">Type of the aggregate result.</param> /// <param name="name">Aggregate name.</param> /// <param name="expressions">Expressions used to construct aggregates from individual facts.</param> /// <param name="source">Pattern that matches facts for aggregation.</param> /// <param name="customFactoryType">Factory type used construct aggregators for this aggregation.</param> /// <returns>Created element.</returns> public static AggregateElement Aggregate(Type resultType, string name, IEnumerable <NamedExpressionElement> expressions, PatternElement source, Type customFactoryType) { if (resultType == null) { throw new ArgumentNullException(nameof(resultType), "Aggregate result type not provided"); } if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name), "Aggregate name not provided"); } if (expressions == null) { throw new ArgumentNullException(nameof(expressions), "Aggregate expressions not provided"); } if (source == null) { throw new ArgumentNullException(nameof(source), "Aggregate source pattern not provided"); } var expressionCollection = new ExpressionCollection(expressions); var element = new AggregateElement(resultType, name, expressionCollection, source, customFactoryType); ElementValidator.ValidateAggregate(element); return(element); }
/// <summary> /// Initialize a new instance of the <see cref="ScriptConstructor"/> class using the specified parameter. /// </summary> /// <param name="cls">The class that the constructor belongs to.</param> /// <param name="parameters">The parameters of the constructor.</param> /// <param name="statements">The statements in the constructor body.</param> /// <param name="closure">The closure scope of the constructor.</param> /// <exception cref="ArgumentNullException"><paramref name="closure"/> or <paramref name="cls"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentException"><paramref name="parameters"/> is invalid.</exception> public ScriptConstructor( ScriptClass cls, ParameterCollection parameters, StatementCollection statements, RuntimeContext closure) { if (closure == null || cls == null) { throw new ArgumentNullException(); } FunctionHelper.CheckParameters(parameters); Class = cls; Parameters = parameters; Closure = closure; Statements = statements; if (statements != null && statements.Count > 0) { var expStat = statements[0] as ExpressionStatement; if (expStat != null) { var funcInv = expStat.Expression as FunctionInvokeExpression; if (funcInv != null) { if (funcInv.Target is SuperReferenceExpression) { var list = statements.ToList(); list.RemoveAt(0); Statements = new StatementCollection(list); SuperCall = funcInv.Parameters; } } } } }
public void TestXmlTagPropertyReturnsXmlTagProvidedWithConstructor() { ExpressionCollection <INUnitFilterBaseElement> collection = new ExpressionCollection <INUnitFilterBaseElement>(NUnitFilterTestHelper.XmlAndTag); Assert.AreEqual(NUnitFilterTestHelper.XmlAndTag, collection.XmlTag); }
private void FixArguments(MethodReference method, ExpressionCollection arguments) { TypeDefinition declaringTypeDefinition = method.DeclaringType.Resolve(); if (declaringTypeDefinition == null) { return; } List<MethodDefinition> sameNameMethods = GetSameNameMethods(declaringTypeDefinition, method, arguments); if (sameNameMethods.Count > 0) { for (int i = 0; i < arguments.Count; i++) { TypeReference paramType = method.Parameters[i].ResolveParameterType(method); if (!arguments[i].HasType) { continue; } if (arguments[i].ExpressionType.FullName == paramType.FullName) { continue; } if (ShouldAddCast(arguments[i], sameNameMethods, i, paramType)) { arguments[i] = new CastExpression(arguments[i], paramType, null); } } } }
private DynamicIndexerExpression(Expression target, ExpressionCollection indices, TypeReference expressionType, IEnumerable<Instruction> instructions) :base(instructions) { this.Target = target; this.Indices = indices; this.ExpressionType = expressionType; }
public override void Invoke(SpoolSpace Memory) { // Get the table source // if (this._Parameters[0].TypeOf() != CellAffinity.TREF) { throw new Exception("Table loops require a tabular expression"); } // Get the fields // this._Fields = ExpressionCollection.Unpack(this._Parameters[1]); // Add memory this.AddSpools(Memory); // Get the table Table t = this._Parameters[0].Select(Memory); // Loop using (RecordReader rr = t.OpenReader()) { while (rr.CanAdvance) { Memory[this._SpoolName].Set(rr.ReadNext()); Memory[this._SpoolNameLive].Set(this._Fields.ToRecord(Memory)); if (this._Filter.Evaluate(Memory).valueBOOL) { this.InvokeChildren(Memory); } } } this.RemoveSpools(Memory); }
private void CastMethodArguments(MethodReference method, ExpressionCollection arguments) { for (int i = 0; i < arguments.Count; i++) { Expression argument = arguments[i]; TypeReference parameterType = method.Parameters[i].ResolveParameterType(method); if (argument.HasType && parameterType != null && !(argument is LiteralExpression)) { TypeReference argumentType = argument.ExpressionType; if ((IsUnsignedIntegerType(argumentType) && IsSignedIntegerType(parameterType)) || (IsSignedIntegerType(argumentType) && IsUnsignedIntegerType(parameterType))) { Expression toCast = argument; if (argument is ExplicitCastExpression) { ExplicitCastExpression argumentCast = argument as ExplicitCastExpression; if (IsIntegerType(argumentCast.TargetType)) { toCast = argumentCast.Expression; } } arguments[i] = new ExplicitCastExpression(toCast, parameterType, null); } } } }
public bool IsValidVargsInvocation(IParameter[] parameters, ExpressionCollection args) { int lastIndex = parameters.Length - 1; if (args.Count < lastIndex) { return(false); } if (!parameters[lastIndex].Type.IsArray) { return(false); } if (!IsValidInvocation(parameters, args, lastIndex)) { return(false); } if (args.Count > 0) { return(CheckVarArgsParameter(parameters, args)); } return(true); }
/// <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 virtual void VisitExpressionCollection(ExpressionCollection value) { for (int i = 0; i < value.Count; i++) { VisitExpression(value[i]); } }
public DelegateInvokeExpression(Expression target, ExpressionCollection arguments, MethodReference invokeMethodReference, IEnumerable<Instruction> instructions) :base(instructions) { this.Target = target; this.Arguments = arguments; this.InvokeMethodReference = invokeMethodReference; }
public Expression <Func <T, bool> > Build(ExpressionCollection <T> expressionCollection) { Expression <Func <T, bool> > expression = null; foreach (var expressionBase in expressionCollection) { switch (expressionBase) { case ExpressionItem <T> _: expression = this.appendToExpression(expression, (expressionBase as ExpressionItem <T>).Expression, expressionBase.LogicalOperator); break; case ExpressionCollection <T> _: var collectionExpressionBuilder = new ExpressionBuilder <T>(); var collectionExpression = collectionExpressionBuilder.Build(expressionBase as ExpressionCollection <T>); expression = this.appendToExpression(expression, collectionExpression, expressionBase.LogicalOperator); break; default: throw new NotImplementedException(string.Format(GeneralResources.Exception_UnknownSubtypeOfExpressionBase, expressionBase.GetType())); } } return(expression); }
public void MapToConcreteExpressionTypes(ExpressionCollection items) { foreach (Expression item in items) { GetConcreteExpressionType(item); } }
public Statement(Host Host, Statement Parent) { this._Host = Host; this._Parent = Parent; this._Children = new List <Statement>(); this._Parameters = new ExpressionCollection(); }
public IEntity ResolveCallableReference(ExpressionCollection args, IEntity[] candidates) { Reset(args); FindApplicableCandidates(candidates); if (ValidCandidates.Count == 0) { return(null); } if (ValidCandidates.Count == 1) { return(((Candidate)ValidCandidates[0]).Method); } List dataPreserving = ValidCandidates.Collect(DoesNotRequireConversions); if (dataPreserving.Count > 0) { if (dataPreserving.Count == 1) { return(((Candidate)dataPreserving[0]).Method); } IEntity found = BestMethod(dataPreserving); if (null != found) { return(found); } } return(BestCandidate()); }
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; }
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); }
public static MethodInvocationExpression GenerateIExpressionInvocationFor(string expressionName, params Expression[] arguments) { var @this = new SelfLiteralExpression(); var invoke = new MemberReferenceExpression(@this, "InvokeExpression"); Expression args; if (arguments == null) { args = new NullLiteralExpression(); } else if (arguments.Length == 1) { args = arguments[0]; } else { args = new ArrayLiteralExpression { Items = ExpressionCollection.FromArray(arguments) } }; return(new MethodInvocationExpression(invoke, new StringLiteralExpression(expressionName), args, new ReferenceExpression("context") )); }
private void FixArguments(MethodReference method, ExpressionCollection arguments) { TypeDefinition declaringTypeDefinition = method.DeclaringType.Resolve(); if (declaringTypeDefinition == null) { return; } List <MethodDefinition> sameNameMethods = GetSameNameMethods(declaringTypeDefinition, method, arguments); if (sameNameMethods.Count > 0) { for (int i = 0; i < arguments.Count; i++) { TypeReference paramType = method.Parameters[i].ResolveParameterType(method); if (!arguments[i].HasType) { continue; } if (arguments[i].ExpressionType.FullName == paramType.FullName) { continue; } if (ShouldAddCast(arguments[i], sameNameMethods, i, paramType)) { arguments[i] = new CastExpression(arguments[i], paramType, null); } } } }
private void OnEval(MethodInvocationExpression node) { BoundSpillSequenceBuilder valueBuilder = null; var value = VisitExpression(ref valueBuilder, node.Arguments.Last); BoundSpillSequenceBuilder builder = null; var seCollection = new ExpressionCollection(); seCollection.AddRange(node.Arguments.Where(a => a != node.Arguments.Last)); var sideEffects = VisitExpressionList(ref builder, seCollection, forceSpill: valueBuilder != null, sideEffectsOnly: true); if (builder == null && valueBuilder == null) { node.Arguments = sideEffects; node.Arguments.Add(value); return; } if (builder == null) { builder = new BoundSpillSequenceBuilder(); } builder.AddExpressions(sideEffects); builder.Include(valueBuilder); ReplaceCurrentNode(builder.Update(value)); }
void ResolveMethodInType(IReturnType containingType, string methodName, ExpressionCollection arguments) { List <IMethod> methods = new List <IMethod>(); bool isClassInInheritanceTree = false; if (callingClass != null) { isClassInInheritanceTree = callingClass.IsTypeInInheritanceTree(containingType.GetUnderlyingClass()); } foreach (IMethod m in containingType.GetMethods()) { if (IsSameName(m.Name, methodName) && m.IsAccessible(callingClass, isClassInInheritanceTree) ) { methods.Add(m); } } if (methods.Count == 0) { ArrayList list = new ArrayList(); ResolveResult.AddExtensions(callingClass.ProjectContent.Language, list, callingClass, containingType); foreach (IMethodOrProperty mp in list) { if (IsSameName(mp.Name, methodName) && mp is IMethod) { IMethod m = (IMethod)mp.CreateSpecializedMember(); m.Parameters.RemoveAt(0); methods.Add(m); } } } ResolveInvocation(methods, arguments); }
private void CastMethodArguments(MethodReference method, ExpressionCollection arguments) { V_0 = 0; while (V_0 < arguments.get_Count()) { V_1 = arguments.get_Item(V_0); V_2 = method.get_Parameters().get_Item(V_0).ResolveParameterType(method); if (V_1.get_HasType() && V_2 != null && V_1 as LiteralExpression == null) { V_3 = V_1.get_ExpressionType(); if (this.IsUnsignedIntegerType(V_3) && this.IsSignedIntegerType(V_2) || this.IsSignedIntegerType(V_3) && this.IsUnsignedIntegerType(V_2)) { V_4 = V_1; if (V_1 as ExplicitCastExpression != null) { V_5 = V_1 as ExplicitCastExpression; if (this.IsIntegerType(V_5.get_TargetType())) { V_4 = V_5.get_Expression(); } } arguments.set_Item(V_0, new ExplicitCastExpression(V_4, V_2, null)); } } V_0 = V_0 + 1; } return; }
private IList ConvertToSingleDeclarationStatements(MultipleVariableDeclarationStatement varDecl) { IList newStmts = new ArrayList(); int index = 0; ExpressionCollection initExps = varDecl.InitExpressions; foreach (Identifier ident in varDecl.Identifiers) { // Here we are converting expression from // x:int, y:long = 1, 2L // to an AST representation equivalent to // x:int = 1; y:long = 2L SingleVariableDeclarationStatement svStmt = new SingleVariableDeclarationStatement(ident); if (index < initExps.Count) { svStmt.InitExp = initExps[index]; EnsureNoPostFixStatement(svStmt.InitExp); } index++; newStmts.Add(svStmt); } // We don't need them anymore initExps.Clear(); return(newStmts); }
public override void LeaveMethodInvocationExpression(Boo.Lang.Compiler.Ast.MethodInvocationExpression node) { ICallableType callable = node.Target.ExpressionType as ICallableType; if (callable == null) { return; } CallableSignature signature = callable.GetSignature(); if (!signature.AcceptVarArgs) { return; } if (node.Arguments.Count > 0 && AstUtil.IsExplodeExpression(node.Arguments[-1])) { // explode the arguments node.Arguments.ReplaceAt(-1, ((UnaryExpression)node.Arguments[-1]).Operand); return; } IParameter[] parameters = signature.Parameters; int lenMinusOne = parameters.Length - 1; IType varArgType = parameters[lenMinusOne].Type; ExpressionCollection varArgs = node.Arguments.PopRange(lenMinusOne); node.Arguments.Add(CodeBuilder.CreateArray(varArgType, varArgs)); }
private void CastMethodArguments(MethodReference method, ExpressionCollection arguments) { for (int i = 0; i < arguments.Count; i++) { Expression argument = arguments[i]; TypeReference parameterType = method.Parameters[i].ResolveParameterType(method); if (argument.HasType && parameterType != null && !(argument is LiteralExpression)) { TypeReference argumentType = argument.ExpressionType; if ((IsUnsignedIntegerType(argumentType) && IsSignedIntegerType(parameterType)) || (IsSignedIntegerType(argumentType) && IsUnsignedIntegerType(parameterType))) { Expression toCast = argument; if (argument is CastExpression) { CastExpression argumentCast = argument as CastExpression; if (IsIntegerType(argumentCast.TargetType)) { toCast = argumentCast.Expression; } } arguments[i] = new CastExpression(toCast, parameterType, null); } } } }
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 AggregateNode(ITupleSource leftSource, IObjectSource rightSource, string name, ExpressionCollection expressions, IAggregatorFactory aggregatorFactory, bool isSubnetJoin) : base(leftSource, rightSource, isSubnetJoin) { Name = name; Expressions = expressions; _aggregatorFactory = aggregatorFactory; _isSubnetJoin = isSubnetJoin; }
public void TestConstructorWithXmlTag() { ExpressionCollection <INUnitFilterBaseElement> collection = new ExpressionCollection <INUnitFilterBaseElement>(NUnitFilterTestHelper.XmlAndTag); Assert.AreEqual(NUnitFilterTestHelper.XmlAndTag, collection.XmlTag); Assert.AreEqual(0, collection.Count); }
public void TestCountReturnsNumberOfItems([Range(0, 3)] int count) { // Create collection ExpressionCollection <INUnitFilterBaseElement> collection = NUnitFilterTestHelper.CreateCollection(count, out _); Assert.AreEqual(count, collection.Count); }
public void TestIsReadOnlyReturnsFalse() { // ReSharper disable once CollectionNeverQueried.Local ExpressionCollection <INUnitFilterBaseElement> collection = new ExpressionCollection <INUnitFilterBaseElement>(NUnitFilterTestHelper.XmlAndTag); Assert.IsFalse(collection.IsReadOnly); }
public ArrayAssignmentFieldReferenceExpression(FieldReferenceExpression field, TypeReference arrayType, ExpressionCollection dimensions, bool hasInitializer, IEnumerable<Instruction> instructions) : base(instructions) { this.Field = field; this.ArrayType = arrayType; this.Dimensions = dimensions; this.HasInitializer = hasInitializer; }
public void AddReturnExpression(Expression expression) { if (null == _returnExpressions) { _returnExpressions = new ExpressionCollection(); } _returnExpressions.Add(expression); }
public void TestToXmlStringWithCollectionEmptyReturnsEmptyString([Values] bool withXmlTag) { ExpressionCollection <INUnitFilterBaseElement> collection = new ExpressionCollection <INUnitFilterBaseElement>(NUnitFilterTestHelper.XmlAndTag); Assert.AreEqual(0, collection.Count); Assert.AreEqual(string.Empty, collection.ToXmlString(withXmlTag)); }
public ArrayVariableDeclarationExpression(VariableDeclarationExpression variable, TypeReference arrayType, ExpressionCollection dimensions, bool hasInitializer, IEnumerable<Instruction> instructions) : base(instructions) { this.Variable = variable; this.ArrayType = arrayType; this.Dimensions = dimensions; this.HasInitializer = hasInitializer; }
public LambdaExpression(ExpressionCollection arguments, BlockStatement body, bool isAsync, bool isFunction, IEnumerable<ParameterReference> parameters, bool isExpressionTreeLambda, IEnumerable<Instruction> instructions) :base(instructions) { this.Arguments = arguments; this.Body = body; this.IsAsync = isAsync; this.IsFunction = isFunction; this.Parameters = parameters.ToArray(); this.IsExpressionTreeLambda = isExpressionTreeLambda; }
public static object Call(string path, CodeTree codeTree, string staticMethodName, string methodName, string functionName, BuiltinFunction builtinFunction, Type type, ExpressionCollection typeArguments, IEnumerable<object> args, Engine engine) { if (path != null) return engine.CallPath(path, codeTree, args); if (functionName != null) return engine.CallFunction(functionName, args); if (builtinFunction != 0) return engine.CallBuiltinFunction(builtinFunction, args); var typeArgs = typeArguments.Count != 0 ? typeArguments.Get(engine).Cast<Type>().ToArray() : null; if (staticMethodName != null) return CallHelper.CallMethod(staticMethodName, true, type, null, args, typeArgs, engine); if (methodName != null) return CallHelper.CallMethod(methodName, false, type ?? engine.Context.GetType(), engine.Context, args, typeArgs, engine); return engine.Throw("nothing to call"); }
private void TraverseMethodParameters(MethodReference method, ExpressionCollection arguments) { for (int i = 0; i < method.Parameters.Count; i++) { if (arguments[i].CodeNodeType == CodeNodeType.DelegateCreationExpression) { DelegateCreationExpression theDelegateCreation = (DelegateCreationExpression)arguments[i]; ParameterDefinition parameter = method.Parameters[i]; if (CanInferTypeOfDelegateCreation(parameter.ParameterType)) { theDelegateCreation.TypeIsImplicitlyInferable = true; } } } }
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 void ProcessAnonymousType(TypeDefinition anonymousTypeDefinition, GenericInstanceType anonymousInstanceType, MethodDefinition constructorDefinition, ExpressionCollection constructorArguments) { for (int i = 0; i < constructorDefinition.Parameters.Count; i++) { ParameterDefinition currentParameter = constructorDefinition.Parameters[i]; int genericParameterIndex = anonymousTypeDefinition.GenericParameters.IndexOf(currentParameter.ParameterType as GenericParameter); PropertyDefinition property = FindPropertyOfType(anonymousTypeDefinition, currentParameter.ParameterType); TypeReference propertyType = anonymousInstanceType.GenericArguments[genericParameterIndex]; if (anonymousInstanceType.PostionToArgument.ContainsKey(genericParameterIndex)) { propertyType = anonymousInstanceType.PostionToArgument[genericParameterIndex]; } Expression parameterExpression = new AnonymousPropertyInitializerExpression(property, propertyType); int argumentIndex = GetParameterIndexWithType(constructorDefinition, currentParameter.ParameterType); Expression argumentExpression = transformer.Visit(constructorArguments[argumentIndex].CloneExpressionOnly()) as Expression; initializerExpressions.Expressions.Add( new BinaryExpression(BinaryOperator.Assign, parameterExpression, argumentExpression, this.typeSystem, null)); } }
private void FixArguments(MethodReference methodRef, ExpressionCollection arguments) { if (methodRef == null) { return; } for (int i = 0; i < arguments.Count; i++) { TypeReference parameterType = methodRef.Parameters[i].ResolveParameterType(methodRef); LiteralExpression literalArgument = arguments[i] as LiteralExpression; if (literalArgument != null) { HandleLiteralArgument(parameterType, literalArgument); } CastExpression castArgument = arguments[i] as CastExpression; if (castArgument != null) { HandleCastArgument(parameterType, castArgument); } } }
private void VisitInvocationArguments(ExpressionCollection arguments, MethodReference method) { Collection<ParameterDefinition> parameters = method.Parameters; for (int index = 0; index < arguments.Count; index++) { TypeReference paramType = parameters[index].ResolveParameterType(method); if (NeedsCast(arguments[index].ExpressionType, paramType)) { if (arguments[index].CodeNodeType == CodeNodeType.LiteralExpression) { arguments[index] = EnumHelper.GetEnumExpression(paramType.Resolve(), (arguments[index] as LiteralExpression), typeSystem); } else { arguments[index] = new CastExpression(arguments[index], paramType, null); } } } }
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; }
// 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; }
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 void VisitMultilineList(ExpressionCollection expressions) { for (int i = 0; i < expressions.Count; i++) { Visit(expressions[i]); if (i != expressions.Count - 1) { WriteToken(","); WriteLine(); } } }
} // 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 New() { TypeArguments = new ExpressionCollection(); }
private bool ArgumentsMatchParameters(Collection<ParameterDefinition> parameters, ExpressionCollection arguments) { for (int i = 0; i < parameters.Count; i++) { // generics? TypeDefinition parameterType = parameters[i].ParameterType.Resolve(); Expression currentArgument = arguments[i]; if (!currentArgument.HasType) { return true; } TypeDefinition argumentType = currentArgument.ExpressionType.Resolve(); if (parameterType == null || argumentType == null) { return true; } if (currentArgument.CodeNodeType == CodeNodeType.LiteralExpression && ((LiteralExpression)currentArgument).Value == null && !parameterType.IsValueType) { continue; } if (parameterType.FullName != argumentType.FullName) { if (!IsTypeDescendantOf(argumentType, parameterType)) { return false; } } } return true; }
private List<MethodDefinition> GetSameNameMethods(TypeDefinition declaringTypeDefinition, MethodReference method, ExpressionCollection arguments) { //TODO: Get only the methods, for which the arguments might match List<MethodDefinition> result = new List<MethodDefinition>(); MethodDefinition methodResolved = method.Resolve(); if (methodResolved == null) { return result; } foreach (MethodDefinition typeMethod in declaringTypeDefinition.Methods) { if (typeMethod.Name != method.Name) { continue; } if (typeMethod.HasParameters != method.HasParameters) { continue; } if (typeMethod.Parameters.Count != method.Parameters.Count) { continue; } if (typeMethod == methodResolved) { continue; } if (typeMethod.HasGenericParameters != methodResolved.HasGenericParameters) { continue; } if (!ArgumentsMatchParameters(typeMethod.Parameters, arguments)) { continue; } result.Add(typeMethod); } return result; }
} // 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; }
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); }
protected virtual void WriteArrayDimensions(ExpressionCollection dimensions, TypeReference arrayType, bool isInitializerPresent) { List<int> emptyDimensions = new List<int>(); TypeReference elementType = arrayType; while (elementType is ArrayType) { ArrayType arr = elementType as ArrayType; emptyDimensions.Add(arr.Dimensions.Count); elementType = arr.ElementType; } #region Indexes WriteToken(IndexLeftBracket); for (int i = 0; i < dimensions.Count; i++) { if (i > 0) { WriteToken(","); if (!isInitializerPresent) { WriteToken(" "); } } if (!isInitializerPresent) { Visit(dimensions[i]); } } WriteToken(IndexRightBracket); #endregion //remaining brackets foreach (int dimentionSize in emptyDimensions) { WriteToken(IndexLeftBracket); for (int i = 1; i < dimentionSize; i++) { WriteToken(","); } WriteToken(IndexRightBracket); } }
public static IElementCollection FindConstructors(this ITypeElement typeElement, ExpressionCollection parameters) { return ParserServices.SourceTreeResolver.FindConstructors(typeElement, parameters); }
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; }
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 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 }); }
protected override void WriteArrayDimensions(ExpressionCollection dimensions, TypeReference arrayType, bool isInitializerPresent) { ExpressionCollection clonedDimensions = dimensions.Clone(); TypeSystem typeSystem = this.ModuleContext.Module.TypeSystem; for (int i = 0; i < clonedDimensions.Count; i++) { if (clonedDimensions[i] is LiteralExpression) { LiteralExpression literal = clonedDimensions[i] as LiteralExpression; literal.Value = GetDecrementedValue(literal); } else { clonedDimensions[i] = new BinaryExpression(BinaryOperator.Subtract, clonedDimensions[i], new LiteralExpression(1, typeSystem, null), typeSystem, null); } } base.WriteArrayDimensions(clonedDimensions, arrayType, isInitializerPresent); }