private static bool ConvertCallWithWaitToAwaitCall([NotNull] IInvocationExpression invocationExpression, [NotNull] CSharpElementFactory factory) { var reference = invocationExpression.Parent as IReferenceExpression; //TODO: AwaitResult our custom method extension, it must be moved to settings if (reference?.NameIdentifier?.Name == "AwaitResult" || reference?.NameIdentifier?.Name == "Wait") { var call = factory.CreateExpression("await $0($1).ConfigureAwait(false)", invocationExpression.ConditionalQualifier, invocationExpression.ArgumentList); var parentInvocation = reference.Parent as IInvocationExpression; if (parentInvocation == null) { return(false); } parentInvocation.ReplaceBy(call); return(true); } if (reference?.NameIdentifier?.Name == "Result") { var call = factory.CreateExpression("await $0($1).ConfigureAwait(false)", invocationExpression.ConditionalQualifier, invocationExpression.ArgumentList); reference.ReplaceBy(call); return(true); } return(false); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { file.AddUsing("log4net", factory); var log4netType = CreateIType("log4net.ILog"); var logField = log4netType != null ? classDeclaration.FieldDeclarations.FirstOrDefault(x => x.Type.IsSubtypeOf(log4netType)) : classDeclaration.FieldDeclarations.FirstOrDefault(x => x.Type.GetInterfaceType()?.ShortName == "ILog"); if (log4netType == null && logField == null) { return(null); } if (logField == null) { logField = CreateFieldDeclaration(log4netType); AddKeywords(logField, CSharpTokenType.READONLY_KEYWORD, CSharpTokenType.STATIC_KEYWORD); AddInitializer(logField, $"LogManager.GetLogger(typeof({classDeclaration.DeclaredName}))"); classDeclaration.AddClassMemberDeclaration(logField); } literalExpression.ReplaceBy(factory.CreateExpression($"{logField.NameIdentifier.Name}.Info($0)", literalExpression)); return(null); }
private void ConvertArrayCreationWithoutInitializer(CSharpElementFactory factory) { var currentCreation = myArrayCreationExpression; var firstSize = currentCreation.Sizes[0].NotNull("currentCreation.Sizes[0] != null").CopyWithResolve(); var secondSize = currentCreation.Sizes[1].NotNull("currentCreation.Sizes[1] != null").CopyWithResolve(); IArrayCreationExpression newCreation; if (currentCreation.TypeUsage == null) { newCreation = factory.CreateExpression("new [$0][]", currentCreation.Sizes[0]) as IArrayCreationExpression; } else { newCreation = factory.CreateExpression("new $0[$1][]", currentCreation.TypeUsage, currentCreation.Sizes[0]) as IArrayCreationExpression; } Assertion.Assert(newCreation != null, "newCreation != null"); newCreation = currentCreation.ReplaceBy(newCreation); if (myVariableDeclaration is ILocalVariableDeclaration) { var statement = newCreation.GetContainingStatement().NotNull("statement != null"); var forInitializer = factory.CreateStatement( "for (int index = 0; index < $0; index++) {$1[index] = new $2[$3];}", firstSize, factory.CreateReferenceExpression(myVariableDeclaration.DeclaredName), myType.ElementType, secondSize); StatementUtil.InsertStatement(forInitializer, ref statement, false); } }
protected override IExpression GetExpression(CSharpElementFactory factory, IExpression contractExpression) { var expression = isDictionary ? factory.CreateExpression( string.Format("$0.{0}(pair => pair.{1} != null)", nameof(Enumerable.All), nameof(KeyValuePair<int, int>.Value)), contractExpression) : factory.CreateExpression(string.Format("$0.{0}(item => item != null)", nameof(Enumerable.All)), contractExpression); var invokedExpression = (IReferenceExpression)((IInvocationExpression)expression).InvokedExpression; Debug.Assert(invokedExpression != null); var allMethodReference = invokedExpression.Reference; var enumerableType = new DeclaredTypeFromCLRName(ClrTypeNames.Enumerable, Provider.PsiModule).GetTypeElement(); Debug.Assert(enumerableType != null); var allMethod = enumerableType.Methods.First(method => method.AssertNotNull().ShortName == nameof(Enumerable.All)); Debug.Assert(allMethod != null); allMethodReference.BindTo(allMethod); return expression; }
protected override IExpression GetExpression(CSharpElementFactory factory, IExpression contractExpression) { var expression = isDictionary ? factory.CreateExpression( string.Format("$0.{0}(pair => pair.{1} != null)", nameof(Enumerable.All), nameof(KeyValuePair <int, int> .Value)), contractExpression) : factory.CreateExpression(string.Format("$0.{0}(item => item != null)", nameof(Enumerable.All)), contractExpression); var invokedExpression = (IReferenceExpression)((IInvocationExpression)expression).InvokedExpression; Debug.Assert(invokedExpression != null); var allMethodReference = invokedExpression.Reference; var enumerableType = TypeElementUtil.GetTypeElementByClrName(PredefinedType.ENUMERABLE_CLASS, Provider.PsiModule); Debug.Assert(enumerableType != null); var allMethod = enumerableType.Methods.First(method => method.AssertNotNull().ShortName == nameof(Enumerable.All)); Debug.Assert(allMethod != null); allMethodReference.BindTo(allMethod); return(expression); }
protected override IExpression GetExpression(CSharpElementFactory factory, IExpression contractExpression) { Debug.Assert(NumericTypeInfo != null); return NumericTypeInfo.EpsilonLiteral != null ? factory.CreateExpression( string.Format("$1.{0}($0 - 0{1}) > {2}", nameof(Math.Abs), NumericTypeInfo.LiteralSuffix, NumericTypeInfo.EpsilonLiteral), contractExpression, new DeclaredTypeFromCLRName(ClrTypeNames.Math, Provider.PsiModule).GetTypeElement()) : factory.CreateExpression(string.Format("$0 != 0{0}", NumericTypeInfo.LiteralSuffix), contractExpression); }
protected override IExpression GetExpression(CSharpElementFactory factory, IExpression contractExpression) { Debug.Assert(NumericTypeInfo != null); return(NumericTypeInfo.EpsilonLiteral != null ? factory.CreateExpression( string.Format("$1.{0}($0 - 0{1}) < {2}", nameof(Math.Abs), NumericTypeInfo.LiteralSuffix, NumericTypeInfo.EpsilonLiteral), contractExpression, TypeElementUtil.GetTypeElementByClrName(ClrTypeNames.Math, Provider.PsiModule)) : factory.CreateExpression(string.Format("$0 == 0{0}", NumericTypeInfo.LiteralSuffix), contractExpression)); }
protected override IForStatement CreateStatement(CSharpElementFactory factory, ICSharpExpression expression) { var hasLength = (LengthName != null); var template = hasLength ? "for(var x=$0;x>=0;x--)" : "for(var x=$0;x>0;x--)"; var forStatement = (IForStatement) factory.CreateStatement( template + EmbeddedStatementBracesTemplate, expression); var variable = (ILocalVariableDeclaration) forStatement.Initializer.Declaration.Declarators[0]; var initializer = (IExpressionInitializer) variable.Initial; if (!hasLength) { var value = initializer.Value.ReplaceBy(expression); value.ReplaceBy(value); } else { var lengthAccess = factory.CreateReferenceExpression("expr.$0", LengthName); lengthAccess = initializer.Value.ReplaceBy(lengthAccess); lengthAccess.QualifierExpression.NotNull().ReplaceBy(expression); lengthAccess.ReplaceBy(factory.CreateExpression("$0 - 1", lengthAccess)); } return forStatement; }
/// <summary> /// The execute inner. /// </summary> /// <param name="solution"> /// The solution. /// </param> /// <param name="textControl"> /// The text control. /// </param> public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl) { IAttributesOwnerDeclaration declaration = Utils.GetTypeClosestToTextControl <IAttributesOwnerDeclaration>(solution, textControl); if (declaration != null) { string rulesNamespace = this.Rule.Namespace; string ruleText = string.Format("{0}:{1}", this.Rule.CheckId, this.Rule.Name); IContextBoundSettingsStore settingsStore = PsiSourceFileExtensions.GetSettingsStore(null, solution); string justificationText = settingsStore.GetValue((StyleCopOptionsSettingsKey key) => key.SuppressStyleCopAttributeJustificationText); CSharpElementFactory factory = CSharpElementFactory.GetInstance(declaration.GetPsiModule()); ITypeElement typeElement = Utils.GetTypeElement(declaration, "System.Diagnostics.CodeAnalysis.SuppressMessageAttribute"); IAttribute attribute = factory.CreateAttribute(typeElement); ICSharpArgument newArg1 = attribute.AddArgumentAfter(Utils.CreateConstructorArgumentValueExpression(declaration.GetPsiModule(), rulesNamespace), null); ICSharpArgument newArg2 = attribute.AddArgumentAfter(Utils.CreateConstructorArgumentValueExpression(declaration.GetPsiModule(), ruleText), newArg1); IPropertyAssignment propertyAssignment = factory.CreatePropertyAssignment( "Justification", factory.CreateExpression("\"$0\"", justificationText)); attribute.AddPropertyAssignmentAfter(propertyAssignment, null); declaration.AddAttributeAfter(attribute, null); } }
public void Process(IPsiSourceFile sourceFile, IRangeMarker rangeMarker, CodeCleanupProfile profile, IProgressIndicator progressIndicator) { var file = sourceFile.GetNonInjectedPsiFile <CSharpLanguage>(); if (file == null) { return; } if (!profile.GetSetting(DescriptorInstance)) { return; } CSharpElementFactory elementFactory = CSharpElementFactory.GetInstance(sourceFile.PsiModule); file.GetPsiServices().PsiManager.DoTransaction( () => { using (_shellLocks.UsingWriteLock()) file.ProcessChildren <IExpression>( expression => { ConstantValue value = expression.ConstantValue; if (value.IsInteger() && Convert.ToInt32(value.Value) == int.MaxValue) { ModificationUtil.ReplaceChild(expression, elementFactory.CreateExpression("int.MaxValue")); } } ); }, "Code cleanup"); }
private void SetInvocationTarget([NotNull] IInvocationExpression invocation, [NotNull] string variableName) { var identifier = myFactory.CreateExpression("$0", variableName); var referenceExpression = (IReferenceExpression)invocation.InvokedExpression; referenceExpression.SetQualifierExpression(identifier); }
private static IConstructorInitializer CreateBaseConstructorInitializer( CSharpElementFactory elementFactory, IParameterDeclaration infoParameterDeclaration, IParameterDeclaration contextParameterDeclaration) { var result = elementFactory.CreateBaseConstructorInitializer(); var infoArgumentExpression = elementFactory.CreateExpression("$0", infoParameterDeclaration.DeclaredName); result.AddArgumentBefore(elementFactory.CreateArgument(ParameterKind.VALUE, infoArgumentExpression), null); var contextArgumentExpression = elementFactory.CreateExpression("$0", contextParameterDeclaration.DeclaredName); result.AddArgumentBefore(elementFactory.CreateArgument(ParameterKind.VALUE, contextArgumentExpression), null); return(result); }
private IAttribute CreateContractClassAttribute(IClassDeclaration contractClass) { ITypeElement attributeType = TypeFactory.CreateTypeByCLRName( typeof(ContractClassAttribute).FullName, _provider.PsiModule).GetTypeElement(); var declaredType = contractClass.DeclaredElement; var typeofExpression = _factory.CreateExpression("typeof($0)", declaredType); var attribute = _factory.CreateAttribute(attributeType); attribute.AddArgumentAfter( _factory.CreateArgument(ParameterKind.VALUE, typeofExpression), null); return(attribute); }
public static void ReplaceCallToAsync([NotNull] IInvocationExpression invocationExpression, [NotNull] CSharpElementFactory factory, bool useAsync) { var returnType = invocationExpression.Type(); var referenceExpression = invocationExpression.FirstChild as IReferenceExpression; if (referenceExpression?.NameIdentifier == null) { return; } var newMethodName = GenerateAsyncMethodName(referenceExpression.NameIdentifier.Name); var newReferenceExpression = referenceExpression.QualifierExpression == null ? factory.CreateReferenceExpression("$0", newMethodName) : factory.CreateReferenceExpression("$0.$1", referenceExpression.QualifierExpression, newMethodName); newReferenceExpression.SetTypeArgumentList(referenceExpression.TypeArgumentList); var callFormat = useAsync ? "await $0($1).ConfigureAwait(false)" : returnType.IsVoid() ? "$0($1).Wait()" : "$0($1).Result"; var awaitExpression = factory.CreateExpression(callFormat, newReferenceExpression, invocationExpression.ArgumentList); invocationExpression.ReplaceBy(awaitExpression); }
public void Execute(ISolution solution, ITextControl textControl) { if (!_literalExpression.IsValid()) { return; } IFile containingFile = _literalExpression.GetContainingFile(); CSharpElementFactory elementFactory = CSharpElementFactory.GetInstance(_literalExpression.GetPsiModule()); IExpression newExpression = null; _literalExpression.GetPsiServices().PsiManager.DoTransaction( () => { using (solution.GetComponent <IShellLocks>().UsingWriteLock()) newExpression = ModificationUtil.ReplaceChild( _literalExpression, elementFactory.CreateExpression("System.Int16.MaxValue")); }, GetType().Name); if (newExpression != null) { IRangeMarker marker = newExpression.GetDocumentRange().CreateRangeMarker(solution.GetComponent <DocumentManager>()); containingFile.OptimizeImportsAndRefs( marker, false, true, NullProgressIndicator.Instance); } }
private ICSharpExpression CreateMulExpression(CSharpElementFactory factory, List <ICSharpExpression> elements) { if (elements.Count == 1) { return(elements[0].CopyWithResolve()); } var newExpr = factory.CreateExpression(mul, elements[0].CopyWithResolve(), elements[1].CopyWithResolve()); for (int i = 2; i < elements.Count; i++) { newExpr = factory.CreateExpression(mul, newExpr, elements[i].CopyWithResolve()); } return(newExpr); }
private ICSharpExpression RemoveScalars(CSharpElementFactory elementFactory, ICSharpExpression expression) { if (!MultiplicationOrderAnalyzer.IsMatrixType(expression)) { return(null); } var multiplication = MultiplicationOrderAnalyzer.GetMulOperation(expression.GetOperandThroughParenthesis()); if (multiplication == null) { return(expression); } var left = RemoveScalars(elementFactory, multiplication.LeftOperand); var right = RemoveScalars(elementFactory, multiplication.RightOperand); if (left == null) { Assertion.Assert(right != null, "right != null"); return(right); } if (right == null) { Assertion.Assert(left != null, "left != null"); return(left); } return(elementFactory.CreateExpression(mul, left.CopyWithResolve(), right.CopyWithResolve())); }
protected override IForStatement CreateStatement(CSharpElementFactory factory, ICSharpExpression expression) { var hasLength = (LengthName != null); var template = hasLength ? "for(var x=$0;x>=0;x--)" : "for(var x=$0;x>0;x--)"; var forStatement = (IForStatement)factory.CreateStatement( template + EmbeddedStatementBracesTemplate, expression); var variable = (ILocalVariableDeclaration)forStatement.Initializer.Declaration.Declarators[0]; var initializer = (IExpressionInitializer)variable.Initial; if (!hasLength) { var value = initializer.Value.ReplaceBy(expression); value.ReplaceBy(value); } else { var lengthAccess = factory.CreateReferenceExpression("expr.$0", LengthName); lengthAccess = initializer.Value.ReplaceBy(lengthAccess); lengthAccess.QualifierExpression.NotNull().ReplaceBy(expression); lengthAccess.ReplaceBy(factory.CreateExpression("$0 - 1", lengthAccess)); } return(forStatement); }
protected override IExpression GetExpression(CSharpElementFactory factory, IExpression contractExpression) { Debug.Assert(members != null); var pattern = new StringBuilder(); var args = new object[members.Count + 1]; args[0] = contractExpression; for (var i = 0; i < members.Count; i++) { if (i > 0) { pattern.Append(" || "); } var index = i + 1; pattern.Append($"$0 == ${index.ToString()}"); args[index] = members[i]; } return(factory.CreateExpression(pattern.ToString(), args)); }
private static IArrayCreationExpression CreateArrayCreationExpression(IType elementType, CSharpElementFactory factory) { IArrayCreationExpression expression = (IArrayCreationExpression)factory.CreateExpression("new[]{}", new object[0]); IArrayType arrayType = TypeFactory.CreateArrayType(elementType, 1, null); return(factory.CreateArrayCreationExpression(arrayType, expression.ArrayInitializer)); }
private MockInfo[] GenerateNewMockInfos(IList <IParameter> ctorParams, IClass[] superClassTypes, ArgumentInfo[] existedArguments, CSharpElementFactory factory) { var mockInfos = new List <MockInfo>(); foreach (var ctorParam in ctorParams) { var isArray = ctorParam.Type is IArrayType; var interfaceType = ctorParam.Type.GetScalarType().GetInterfaceType(); if (!ctorParam.Type.IsInterfaceType() && !(isArray && interfaceType != null) || ParamIsQeuryExecutorFactoryAndAvailable(ctorParam.Type, superClassTypes)) { continue; } if (existedArguments.Where(x => x.IsCSharpArgument).Any(x => x.Type.IsImplicitlyConvertibleTo(ctorParam.Type, cSharpTypeConversionRule))) { continue; } var ctorParamName = ctorParam.ShortName; if (isArray) { var scalarType = interfaceType; var singleName = GetSingleName(ctorParamName); var arrayParamNames = Enumerable.Range(1, 2).Select(x => $"{singleName}{x}").ToArray(); foreach (var arrayParamName in arrayParamNames) { // ReSharper disable once PossibleNullReferenceException var expression = factory.CreateExpression("NewMock<$0>();", scalarType.ShortName); mockInfos.Add(new MockInfo { Statement = factory.CreateStatement("$0 = $1;", arrayParamName, expression), Type = ((IArrayType)ctorParam.Type).ElementType, Name = arrayParamName }); } mockInfos.Add(new MockInfo { Statement = factory.CreateStatement("$0 = $1;", ctorParam.ShortName, factory.CreateExpression($"new[] {{ {string.Join(", ", arrayParamNames)} }}")), Type = ctorParam.Type, Name = ctorParam.ShortName }); } else { mockInfos.Add(new MockInfo { Statement = factory.CreateStatement("$0 = $1;", ctorParam.ShortName, factory.CreateExpression("NewMock<$0>();", ctorParam.Type)), Type = ctorParam.Type, Name = ctorParam.ShortName }); } } return(mockInfos.ToArray()); }
private void AddColumnAttributes() { foreach (var propertyDeclaration in classDeclaration.PropertyDeclarations) { if (propertyDeclaration.HasAttribute(Constants.Column)) { continue; } if (!propertyDeclaration.HasGetSet()) { continue; } var columnAttribute = CreateSchemaAttribute(Constants.Column); if (columnAttribute == null) { return; } var columnName = propertyDeclaration.NameIdentifier.Name; var columnNameArgument = factory.CreateArgument(ParameterKind.VALUE, factory.CreateStringLiteralExpression($"{columnName}")); columnAttribute.AddArgumentBefore(columnNameArgument, null); var propertyType = propertyDeclaration.Type; var typeNameArgument = factory.CreateArgument(ParameterKind.VALUE, factory.CreateExpression($"{Constants.TypeName} = $0", GetMappingTypeName(propertyType))); columnAttribute.AddArgumentBefore(typeNameArgument, null); propertyDeclaration.AddAttributeAfter(columnAttribute, propertyDeclaration.Attributes.LastOrDefault()); AddAnnotationAttributesIfNeed(propertyDeclaration); } }
protected override IExpression GetExpression(CSharpElementFactory factory, IExpression contractExpression) { Debug.Assert(nameof(IntPtr.Zero) == nameof(UIntPtr.Zero)); return(factory.CreateExpression( string.Format("$0 != $1.{0}", nameof(IntPtr.Zero)), contractExpression, TypeElementUtil.GetTypeElementByClrName(IsSigned ? PredefinedType.INTPTR_FQN : PredefinedType.UINTPTR_FQN, Provider.PsiModule))); }
protected override IExpression GetExpression(CSharpElementFactory factory, IExpression contractExpression) { Debug.Assert(nameof(IntPtr.Zero) == nameof(UIntPtr.Zero)); return factory.CreateExpression( string.Format("$0 == $1.{0}", nameof(IntPtr.Zero)), contractExpression, new DeclaredTypeFromCLRName(IsSigned ? PredefinedType.INTPTR_FQN : PredefinedType.UINTPTR_FQN, Provider.PsiModule).GetTypeElement()); }
protected override ICSharpExpression CreateExpression(CSharpElementFactory factory, ICSharpExpression expression) { if (myIsConstructorCall) { return(factory.CreateExpression("new $0", expression.GetText())); } return(expression); }
protected override IExpressionStatement CreateStatement(CSharpElementFactory factory, ICSharpExpression expression) { if (myIsConstructorCall) { expression = factory.CreateExpression("new $0", expression.GetText()); } return((IExpressionStatement)factory.CreateStatement("$0;", expression)); }
protected override IExpressionStatement CreateStatement(CSharpElementFactory factory, ICSharpExpression expression) { if (IsConstructorInvocation(expression)) { // note: reinterpret constructor call as object creation expression expression = factory.CreateExpression("new $0", expression.GetText()); } return((IExpressionStatement)factory.CreateStatement("$0;", expression)); }
protected override void PlaceExpression( IForStatement forStatement, ICSharpExpression expression, CSharpElementFactory factory) { var variable = (ILocalVariableDeclaration)forStatement.Initializer.Declaration.Declarators[0]; var initializer = (IExpressionInitializer)variable.Initial; if (LengthPropertyName == null) { var value = initializer.Value.ReplaceBy(expression); value.ReplaceBy(factory.CreateExpression("$0 - 1", value)); } else { var lengthAccess = factory.CreateReferenceExpression("expr.$0", LengthPropertyName); lengthAccess = initializer.Value.ReplaceBy(lengthAccess); lengthAccess.QualifierExpression.NotNull().ReplaceBy(expression); lengthAccess.ReplaceBy(factory.CreateExpression("$0 - 1", lengthAccess)); } }
public override void ProcessParameterReference(IReference reference) { var referenceExpression = reference as IReferenceExpression; if (referenceExpression != null) { CSharpElementFactory factory = CSharpElementFactory.GetInstance(referenceExpression.GetPsiModule()); referenceExpression.ReplaceBy(factory.CreateExpression("typeof($0)", Workflow.TypeParameterName)); } }
private static void HandleExpressionBody(IBlock body, CSharpElementFactory factory, IType type, string name, DisposableMarker <IReferenceExpression> marker, IReferenceExpression originValue) { var statement = body.Statements.First().NotNull("body.Statements.First() != null"); StatementUtil.InsertStatement(factory.CreateStatement("$0 $1;", type, name), ref statement, true); var updatedReference = marker.Find(body).NotNull("marker.Find(body) != null"); updatedReference.ReplaceBy(factory.CreateExpression("($0 = $1)", name, originValue.Copy())); }
protected override IObjectCreationExpression CreateExpression(CSharpElementFactory factory, ICSharpExpression expression) { // todo: not sure it will always work, let's make it safier var referenceExpression = (IReferenceExpression)expression.NotNull("referenceExpression != null"); var resolveResult = referenceExpression.Reference.Resolve().Result; var typeElement = (ITypeElement)resolveResult.DeclaredElement.NotNull("typeElement != null"); var referencedType = TypeFactory.CreateType(typeElement, resolveResult.Substitution); return((IObjectCreationExpression)factory.CreateExpression("new $0()", referencedType)); }
protected override IIfStatement CreateStatement(CSharpElementFactory factory, ICSharpExpression expression) { // automatically fix 'as'-expression to became 'is'-expression var asExpression = expression as IAsExpression; if (asExpression != null && asExpression.TypeOperand != null && asExpression.Operand != null) { expression = factory.CreateExpression("$0 is $1", asExpression.Operand, asExpression.TypeOperand); } var template = "if($0)" + EmbeddedStatementBracesTemplate; return((IIfStatement)factory.CreateStatement(template, expression)); }
public override IReference BindTo(IDeclaredElement element) { if (GetName() != element.ShortName) { CSharpElementFactory instance = CSharpElementFactory.GetInstance(myOwner, true); if (_resolveResult.ResolveErrorType == ResolveErrorType.OK) { var elementNameExpression = myOwner.ReplaceBy(instance.CreateExpression("\"$0\"", element.ShortName)); return(new ReflectedMemberReference(elementNameExpression, new ResolveResultWithInfo(ResolveResultFactory.CreateResolveResult(element), ResolveErrorType.OK), _typeElement)); } } return(this); }
private void ConvertUsages(CSharpElementFactory factory) { foreach (var usage in myTreeNodePointers) { var node = usage.GetTreeNode() as ICSharpExpression; var elementAccessExpression = ElementAccessExpressionNavigator.GetByOperand(node as ICSharpExpression) .NotNull("ElementAccessExpressionNavigator.GetByOperand(node as ICSharpExpression) != null"); var arguments = elementAccessExpression.Arguments; if (node == null || arguments.Count < 2) { continue; } var newUsage = factory.CreateExpression("$0[$1][$2]", node, arguments[0], arguments[1]); elementAccessExpression.ReplaceBy(newUsage); } }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { var type = ctorExpression.Type(); if (!type.IsResolved) { return(null); } var properties = type.GetClassType()?.Properties; if (properties == null) { return(null); } var objectInitializer = ctorExpression.Initializer as IObjectInitializer ?? factory.CreateObjectInitializer(); var initializedProperties = new HashSet <string>(objectInitializer.MemberInitializers.OfType <IPropertyInitializer>().Select(x => x.MemberName)); var classDeclaration = provider.GetSelectedElement <IClassDeclaration>(); var hasTestBaseSuperType = classDeclaration.GetAllSuperTypes().Any(x => x.GetClassType()?.ShortName.Contains("TestBase") ?? false); var dummyHelper = new DummyHelper(); var properiesToInitialize = new List <(string Name, string Value)>(); foreach (var property in properties.Where(x => !initializedProperties.Contains(x.ShortName))) { var propertyDummyValue = hasTestBaseSuperType ? dummyHelper.GetParamValue(property.Type, property.ShortName) : "TODO"; properiesToInitialize.Add((Name: property.ShortName, Value: propertyDummyValue)); } foreach (var(name, value) in properiesToInitialize) { var initializer = factory.CreateObjectPropertyInitializer(name, factory.CreateExpression("$0", value)); objectInitializer.AddMemberInitializerBefore(initializer, null); } ctorExpression.SetInitializer(objectInitializer); return(null); }
protected override IExpression GetExpression(CSharpElementFactory factory, IExpression contractExpression) { Debug.Assert(members != null); var pattern = new StringBuilder(); var args = new object[members.Count + 1]; args[0] = contractExpression; for (var i = 0; i < members.Count; i++) { if (i > 0) { pattern.Append(" || "); } var index = i + 1; pattern.Append($"$0 == ${index}"); args[index] = members[i]; } return factory.CreateExpression(pattern.ToString(), args); }
/// <summary> /// Negates the literal expression. /// </summary> /// <param name="factory"> /// The factory. /// </param> /// <param name="literalExpression"> /// The literal expression. /// </param> private static void NegateLiteralExpression(CSharpElementFactory factory, ILiteralExpression literalExpression) { ICSharpExpression csharpExpression = literalExpression as ICSharpExpression; if (csharpExpression == null) { return; } var text = literalExpression.GetText(); if (text == "true") { text = "false"; } else if (text == "false") { text = "true"; } else { return; } var expression = factory.CreateExpression(text); ExpressionUtil.ReplaceExpression(csharpExpression, expression); }
private static void CallExtensionMethodsAsStatic(IFile file, INamespace importedNs, CSharpElementFactory factory) { var targetsCollector = new TypeUsagesCollector(file, file.GetDocumentRange()); var references = targetsCollector.Run(); foreach (var reference in references) { var resolve = reference.Resolve(); var declaredElement = resolve.DeclaredElement; var imethod = declaredElement as IMethod; var methodExecution = reference.GetTreeNode(); var method = methodExecution as IReferenceExpression; var containingNsQualifiedName = imethod.IfNotNull(m => m.GetContainingType()) .IfNotNull(t => t.GetContainingNamespace()) .IfNotNull(ns => ns.QualifiedName); if (imethod != null && method.IsExtensionMethod() && containingNsQualifiedName == importedNs.QualifiedName) { var invocate = InvocationExpressionNavigator.GetByInvokedExpression(method); //if (invocate == null) return null; // build string like $0($1,$2,..argc) var tokens = string.Format( "$0({0})", string.Join( ",", new[] { "$1" }.Concat(invocate.Arguments.Select((a, i) => "$" + (i + 2).ToString("G"))).ToArray())); var funcAndThis = new object[] { "faketobind", (invocate.InvokedExpression as IReferenceExpression).QualifierExpression }; var paramsObject = funcAndThis.Concat(invocate.Arguments).ToArray(); var cSharpExpression = (IInvocationExpression)factory.CreateExpression(tokens, paramsObject); var replaceResult = invocate.ReplaceBy(cSharpExpression); (replaceResult.InvokedExpression as IReferenceExpression).Reference.BindTo(declaredElement); } } }
/// <summary> /// Negates the relational expression. /// </summary> /// <param name="factory"> /// The factory. /// </param> /// <param name="relationalExpression"> /// The relational expression. /// </param> private static void NegateRelationalExpression(CSharpElementFactory factory, IRelationalExpression relationalExpression) { var operatorSign = relationalExpression.OperatorSign.GetText(); switch (operatorSign) { case "<": operatorSign = ">="; break; case ">": operatorSign = "<="; break; case "<=": operatorSign = ">"; break; case ">=": operatorSign = "<"; break; } var expression = factory.CreateExpression(string.Format("{0} {1} {2}", relationalExpression.LeftOperand.GetText(), operatorSign, relationalExpression.RightOperand.GetText())); relationalExpression.ReplaceBy(expression); }
/// <summary> /// Negates the unary expression. /// </summary> /// <param name="factory"> /// The factory. /// </param> /// <param name="unaryOperatorExpression"> /// The unary operator expression. /// </param> private static void NegateUnaryExpression(CSharpElementFactory factory, IUnaryOperatorExpression unaryOperatorExpression) { if (unaryOperatorExpression.OperatorSign.GetText() != "!") { return; } var text = unaryOperatorExpression.Operand.GetText().Trim(); if (text.StartsWith("(") && text.EndsWith(")")) { text = text.Substring(1, text.Length - 2); } var expression = factory.CreateExpression(text); unaryOperatorExpression.ReplaceBy(expression); }
/// <summary> /// Negates the invocation expression. /// </summary> /// <param name="factory"> /// The factory. /// </param> /// <param name="invocationExpression"> /// The invocation expression. /// </param> private static void NegateInvocationExpression(CSharpElementFactory factory, IInvocationExpression invocationExpression) { var expression = factory.CreateExpression("!" + invocationExpression.GetText()); invocationExpression.ReplaceBy(expression); }
/// <summary> /// Adds to expression. /// </summary> /// <param name="factory"> /// The factory. /// </param> /// <param name="expression"> /// To. /// </param> /// <param name="sign"> /// The sign. /// </param> /// <returns> /// </returns> private static ICSharpExpression AddToExpression(CSharpElementFactory factory, ICSharpExpression expression, char sign) { var sign2 = sign == '-' ? '+' : '-'; var text = expression.GetText(); if (text.StartsWith("(") && text.EndsWith(")")) { text = text.Substring(1, text.Length - 2); } var match = Regex.Match(text, "\\" + sign2 + "\\s*1\\s*$"); if (match.Success) { text = text.Substring(0, text.Length - match.Value.Length).Trim(); if (text.StartsWith("(") && text.EndsWith(")")) { text = text.Substring(1, text.Length - 2); } } else { if (expression is IBinaryExpression) { text = "(" + text + ") " + sign + " 1"; } else { text += sign + " 1"; } } text = text.Trim(); var result = factory.CreateExpression(text); if (result.IsConstantValue()) { result = factory.CreateExpressionByValue(result.ConstantValue); } return result; }
protected override IExpression GetExpression(CSharpElementFactory factory, IExpression contractExpression) => factory.CreateExpression("$0 != null", contractExpression);
protected override IExpression GetExpression(CSharpElementFactory factory, IExpression contractExpression) { Debug.Assert(NumericTypeInfo != null); return factory.CreateExpression(string.Format("$0 >= 0{0}", NumericTypeInfo.LiteralSuffix), contractExpression); }
protected override IExpression GetExpression(CSharpElementFactory factory, IExpression contractExpression) => isArray ? factory.CreateExpression(string.Format("$0.{0} > 0", nameof(Array.Length)), contractExpression) : factory.CreateExpression(string.Format("$0.{0} > 0", nameof(ICollection<int>.Count)), contractExpression);
protected override IExpression GetExpression(CSharpElementFactory factory, IExpression contractExpression) => factory.CreateExpression( string.Format("$0 < $1.{0}", nameof(System.TimeSpan.Zero)), contractExpression, new DeclaredTypeFromCLRName(ClrTypeNames.TimeSpan, Provider.PsiModule).GetTypeElement());
/// <summary> /// Gets the condition. /// </summary> /// <param name="factory"> /// The factory. /// </param> /// <param name="leftOperand"> /// The left operand. /// </param> /// <param name="operatorSign"> /// The operator sign. /// </param> /// <param name="rightOperand"> /// The right operand. /// </param> /// <returns> /// </returns> private static ICSharpExpression GetCondition(CSharpElementFactory factory, ICSharpExpression leftOperand, string operatorSign, ICSharpExpression rightOperand) { switch (operatorSign) { case "<": operatorSign = ">="; break; case ">": operatorSign = "<="; break; case "<=": operatorSign = ">"; break; case ">=": operatorSign = "<"; break; } return factory.CreateExpression(string.Format("{0} {1} {2}", leftOperand.GetText(), operatorSign, rightOperand.GetText())); }
protected override IExpression GetExpression(CSharpElementFactory factory, IExpression contractExpression) => factory.CreateExpression(string.Format("!string.{0}($0)", nameof(string.IsNullOrEmpty)), contractExpression);
/// <summary> /// Negates the expression. /// </summary> /// <param name="factory"> /// The factory. /// </param> /// <param name="condition"> /// The condition. /// </param> private static void NegateExpression(CSharpElementFactory factory, ICSharpExpression condition) { var expression = factory.CreateExpression("!(" + condition.GetText() + ")"); condition.ReplaceBy(expression); }
/// <summary> /// Negates the equality expression. /// </summary> /// <param name="factory"> /// The factory. /// </param> /// <param name="equalityExpression"> /// The equality expression. /// </param> private static void NegateEqualityExpression(CSharpElementFactory factory, IEqualityExpression equalityExpression) { var operatorSign = equalityExpression.OperatorSign.GetText(); operatorSign = operatorSign == "==" ? "!=" : "=="; var expression = factory.CreateExpression(string.Format("{0} {1} {2}", equalityExpression.LeftOperand.GetText(), operatorSign, equalityExpression.RightOperand.GetText())); equalityExpression.ReplaceBy(expression); }