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>Creates a variable declaration for catch clause.</summary> /// <param name="exceptionType">The type of a created variable.</param> /// <param name="context">The context. </param> public ICatchVariableDeclaration CreateCatchVariableDeclarationNode(IDeclaredType exceptionType, ITreeNode context) { var tryStatement = _factory.CreateStatement("try {} catch(Exception e) {}") as ITryStatement; if (tryStatement == null) { return(null); } var catchClause = tryStatement.Catches[0] as ISpecificCatchClause; if (catchClause == null) { return(null); } var exceptionDeclaration = catchClause.ExceptionDeclaration; if (exceptionDeclaration == null) { return(null); } if (exceptionType != null) { #if R8 var declaredTypeUsageNode = _factory.CreateDeclaredTypeUsageNode(exceptionType); #else var declaredTypeUsageNode = _factory.CreateTypeUsage(exceptionType, context); #endif #if R2016_3 || R2017_1 catchClause.SetExceptionTypeUsage(declaredTypeUsageNode); #else exceptionDeclaration.SetDeclaredTypeUsage(declaredTypeUsageNode); #endif } return(exceptionDeclaration); }
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)); }
private ICSharpStatement CreateContractEnsures(CSharpElementFactory factory, ICSharpFunctionDeclaration functionDeclaration) { Contract.Requires(factory != null); Contract.Requires(functionDeclaration != null); Contract.Ensures(Contract.Result <ICSharpStatement>() != null); // TODO: IsValid returns true even if resulting expression would not compiles! // To check this, please remove semicolon in the string below. // Maybe Resolve method would be good! // Contract.Ensures(Contract.Result<ICSharpStatement>().IsValid()); string format = "$0.Ensures(Contract.Result<$1>() != null);"; var returnType = (IDeclaredType)functionDeclaration.DeclaredElement.ReturnType; return(factory.CreateStatement(format, ContractType, returnType)); }
private void CreateStatement(CSharpElementFactory factory, ICSharpExpression expression, IPsiSourceFile sourceFile, AccessRights accessRights) { var statement = (IExpressionStatement)factory.CreateStatement("'__' = expression;"); var propertyDeclaration = factory.CreatePropertyDeclaration(Context.Type, Context.SuggestedPropertyName, IsReadOnly, accessRights); var assignment = (IAssignmentExpression)statement.Expression; assignment.SetSource(expression); var psiServices = expression.GetPsiServices(); var suggestionManager = psiServices.Naming.Suggestion; var classDeclaration = Context.ParameterDeclaration.GetContainingNode <IClassDeclaration>().NotNull(); var suggestion = suggestionManager.CreateEmptyCollection( PluralityKinds.Unknown, expression.Language, true, sourceFile); suggestion.Add(expression, new EntryOptions { SubrootPolicy = SubrootPolicy.Decompose, PredefinedPrefixPolicy = PredefinedPrefixPolicy.Remove }); suggestion.Prepare(propertyDeclaration.DeclaredElement, new SuggestionOptions { UniqueNameContext = (ITreeNode)classDeclaration.Body ?? classDeclaration }); propertyDeclaration.SetName(suggestion.FirstName()); var memberAnchor = GetAnchorMember(classDeclaration.MemberDeclarations.ToList()); classDeclaration.AddClassMemberDeclarationAfter(propertyDeclaration, (IClassMemberDeclaration)memberAnchor); var languageHelper = LanguageManager.Instance.TryGetService <IIntroducePropertyFromParameterLanguageHelper>( Context.Parameter.PresentationLanguage); if (languageHelper == null) { return; } var anchorInitializationAnchorMember = GetAnchorInitializationAnchorMember(Context.ConstructorDeclaration); languageHelper.AddAssignmentToBody(Context.ConstructorDeclaration, anchorInitializationAnchorMember, false, Context.Parameter, propertyDeclaration.DeclaredElement); }
protected override IForStatement CreateStatement(CSharpElementFactory factory, ICSharpExpression expression) { var template = "for(var x=0;x<$0;x++)" + EmbeddedStatementBracesTemplate; var forStatement = (IForStatement)factory.CreateStatement(template, expression); var condition = (IRelationalExpression)forStatement.Condition; if (LengthName == null) { condition.RightOperand.ReplaceBy(expression); } else { var lengthAccess = factory.CreateReferenceExpression("expr.$0", LengthName); lengthAccess = condition.RightOperand.ReplaceBy(lengthAccess); lengthAccess.QualifierExpression.NotNull().ReplaceBy(expression); } return(forStatement); }
protected override IForStatement CreateStatement(CSharpElementFactory factory, ICSharpExpression expression) { var template = "for(var x=0;x<$0;x++)" + EmbeddedStatementBracesTemplate; var forStatement = (IForStatement) factory.CreateStatement(template, expression); var condition = (IRelationalExpression) forStatement.Condition; if (LengthName == null) { condition.RightOperand.ReplaceBy(expression); } else { var lengthAccess = factory.CreateReferenceExpression("expr.$0", LengthName); lengthAccess = condition.RightOperand.ReplaceBy(lengthAccess); lengthAccess.QualifierExpression.NotNull().ReplaceBy(expression); } return forStatement; }
private void CreateStatement(CSharpElementFactory factory, ICSharpExpression expression, IPsiSourceFile sourceFile) { var statement = (IExpressionStatement) factory.CreateStatement("'__' = expression;"); var propertyDeclaration = factory.CreatePrivatePropertyDeclaration(Context.Type, Context.SuggestedPropertyName); var assignment = (IAssignmentExpression) statement.Expression; assignment.SetSource(expression); var psiServices = expression.GetPsiServices(); var suggestionManager = psiServices.Naming.Suggestion; var classDeclaration = Context.ParameterDeclaration.GetContainingNode<IClassDeclaration>().NotNull(); var suggestion = suggestionManager.CreateEmptyCollection( PluralityKinds.Unknown, expression.Language, true, sourceFile); suggestion.Add(expression, new EntryOptions { SubrootPolicy = SubrootPolicy.Decompose, PredefinedPrefixPolicy = PredefinedPrefixPolicy.Remove }); suggestion.Prepare(propertyDeclaration.DeclaredElement, new SuggestionOptions { UniqueNameContext = (ITreeNode) classDeclaration.Body ?? classDeclaration }); propertyDeclaration.SetName(suggestion.FirstName()); var memberAnchor = GetAnchorMember(classDeclaration.MemberDeclarations.ToList()); classDeclaration.AddClassMemberDeclarationAfter(propertyDeclaration, (IClassMemberDeclaration) memberAnchor); var languageHelper = LanguageManager.Instance.TryGetService<IIntroducePrivatePropertyFromParameterLanguageHelper>( Context.Parameter.PresentationLanguage); if (languageHelper == null) return; var anchorInitializationAnchorMember = GetAnchorInitializationAnchorMember(Context.ConstructorDeclaration); languageHelper.AddAssignmentToBody(Context.ConstructorDeclaration, anchorInitializationAnchorMember, false, Context.Parameter, propertyDeclaration.DeclaredElement); }
private string AddDeclaration( [NotNull] IInvocationExpression invocation, [NotNull] IType variableType, ref LocalList <IDeclarationStatement> declarations, ref LocalList <IList <string> > variableNameSuggestions) { var declaration = (IDeclarationStatement)myFactory.CreateStatement("$0 $1 = $2;", variableType, "__", invocation); var variable = declaration.VariableDeclarations[0]; var variableNames = NameHelper.SuggestVariableNames(invocation, variable.DeclaredElement, variableType); NameHelper.EnsureFirstSuggestionIsUnique(variableNames, ref variableNameSuggestions); variableNameSuggestions.Add(variableNames); variable.SetName(variableNames[0]); declarations.Add(declaration); return(variableNames[0]); }
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 IReturnStatement CreateStatement(CSharpElementFactory factory, ICSharpExpression expression) { return((IReturnStatement)factory.CreateStatement("return $0;", expression)); }
protected override IUsingStatement CreateStatement(CSharpElementFactory factory, ICSharpExpression expression) { var template = (myShouldCreateVariable ? "using(T x=$0)" : "using($0)"); return((IUsingStatement)factory.CreateStatement(template + EmbeddedStatementBracesTemplate, expression)); }
private ICSharpStatement CreateContractEnsures(CSharpElementFactory factory, ICSharpFunctionDeclaration functionDeclaration) { Contract.Requires(factory != null); Contract.Requires(functionDeclaration != null); Contract.Ensures(Contract.Result<ICSharpStatement>() != null); // TODO: IsValid returns true even if resulting expression would not compiles! // To check this, please remove semicolon in the string below. // Maybe Resolve method would be good! // Contract.Ensures(Contract.Result<ICSharpStatement>().IsValid()); string format = "$0.Ensures(Contract.Result<$1>() != null);"; var returnType = (IDeclaredType)functionDeclaration.DeclaredElement.ReturnType; return factory.CreateStatement(format, ContractType, returnType); }
/// <summary> /// Generates Arrange/Act/Assert stub for test method based on original method declaration /// </summary> /// <param name="factory"></param> /// <param name="testMethod"></param> /// <param name="originalMethod"></param> /// <param name="psiModule"></param> private void GenerateTestMethodBody(CSharpElementFactory factory, IPsiModule psiModule, IMethodDeclaration testMethod, IMethod originalMethod) { ICSharpStatement anchorStatement = null; var paramsList = new StringBuilder(); // Arrange foreach (var parameterDeclaration in originalMethod.Parameters) { var type = parameterDeclaration.Type; var stmt = factory.CreateStatement("$0 " + parameterDeclaration.ShortName + " = $1;", type, DefaultValueUtil.GetDefaultValue(type, testMethod.Language, psiModule)); anchorStatement = testMethod.Body.AddStatementAfter(stmt, anchorStatement); if (paramsList.Length == 0) // First parameter ModificationUtil.AddChildBefore(anchorStatement, factory.CreateComment("// Arrange" + Environment.NewLine)); else paramsList.Append(", "); paramsList.Append(parameterDeclaration.ShortName); } if (!originalMethod.ReturnType.IsVoid()) { var stmt = factory.CreateStatement("$0 expected = $1;", originalMethod.ReturnType, DefaultValueUtil.GetDefaultValue(originalMethod.ReturnType, testMethod.Language, psiModule)); anchorStatement = testMethod.Body.AddStatementAfter(stmt, anchorStatement); if (originalMethod.Parameters.IsEmpty()) ModificationUtil.AddChildBefore(anchorStatement, factory.CreateComment("// Arrange")); } // Act var methodInvocation = (originalMethod.IsStatic ? "$1" : "my" + originalMethod.GetContainingType().ShortName + "Instance") + "." + originalMethod.ShortName; var invocationStatement = !originalMethod.ReturnType.IsVoid() ? factory.CreateStatement("$0 result = " + methodInvocation + "(" + paramsList + ");", originalMethod.ReturnType, originalMethod.GetContainingType()) : factory.CreateStatement(methodInvocation + "(" + paramsList + ");", null, originalMethod.GetContainingType()); anchorStatement = testMethod.Body.AddStatementAfter(invocationStatement, anchorStatement); AddCommentWithNewLineBefore(factory, anchorStatement, "// Act"); // Assert if (!originalMethod.ReturnType.IsVoid()) { var stmt = factory.CreateStatement("Assert.AreEqual(expected, result);"); anchorStatement = testMethod.Body.AddStatementAfter(stmt, anchorStatement); AddCommentWithNewLineBefore(factory, anchorStatement, "// Assert"); } }
private void UpdateExistingTryCatchBlock(CSharpElementFactory elementFactory, ITryStatement block, string exceptionTypeName) { // There is no way to create a catch clause so we need to create a fake try statement with our // catch clause and copy it to the currently selected clause. var statement = elementFactory.CreateStatement("try{}catch($0 ex){}", exceptionTypeName); ITryStatement tempTryStatement = statement as ITryStatement; if (null == tempTryStatement) return; block.AddCatchClause(tempTryStatement.Catches[0]); }
private ITryStatement CreateNewTryCatchBlock(CSharpElementFactory elementFactory, string exceptionTypeName) { StringBuilder statementBuilder = new StringBuilder("try{"); _statement.GetText(statementBuilder); statementBuilder.Append("}catch("); statementBuilder.Append(exceptionTypeName); statementBuilder.Append(" ex){}"); ICSharpStatement newStatement = elementFactory.CreateStatement(statementBuilder.ToString()); ITryStatement result = _statement.ReplaceBy(newStatement) as ITryStatement; return result; }
protected override IForeachStatement CreateStatement(CSharpElementFactory factory, ICSharpExpression expression) { var template = "foreach(var x in $0)" + EmbeddedStatementBracesTemplate; return((IForeachStatement)factory.CreateStatement(template, expression)); }
protected override ILockStatement CreateStatement(CSharpElementFactory factory, ICSharpExpression expression) { var template = "lock($0)" + EmbeddedStatementBracesTemplate; return((ILockStatement)factory.CreateStatement(template, expression)); }
// switch statement can't be without braces protected override ISwitchStatement CreateStatement(CSharpElementFactory factory, ICSharpExpression expression) { var template = "switch($0)" + RequiredBracesTemplate; return((ISwitchStatement)factory.CreateStatement(template, expression)); }
protected override IThrowStatement CreateStatement(CSharpElementFactory factory, ICSharpExpression expression) { var template = myInsertNewExpression ? "throw new $0;" : "throw $0;"; return((IThrowStatement)factory.CreateStatement(template, expression.GetText())); }
protected override ICSharpStatement CreateStatement(CSharpElementFactory factory, ICSharpExpression expression) { return(factory.CreateStatement("var testee = $0;", expression)); }
private IDeclarationStatement CreateStubDeclaration(CSharpElementFactory factory, IExpectedTypeConstraint typeConstraint) { return (IDeclarationStatement)factory.CreateStatement( "var $0 = MockRepository.GenerateStub<$1>();", _referenceName, GetStubInterfaceName(typeConstraint)); }
private MockInfo[] GenerateNewMockInfos(IList <IParameter> callParams, ArgumentInfo[] existedArguments, CSharpElementFactory factory) { var existedArgumentsList = existedArguments.ToList(); var mockInfos = new List <MockInfo>(); var dummyHelper = new DummyHelper(); foreach (var callParam in callParams) { var isArray = callParam.Type is IArrayType; var callParamType = callParam.Type; var existArgument = existedArgumentsList.Pop(x => x.IsCSharpArgument && x.Type.IsImplicitlyConvertibleTo(callParam.Type, cSharpTypeConversionRule)); if (existArgument != null) { continue; } var ctorParamName = callParam.ShortName; if (isArray) { var scalarType = callParamType.GetScalarType(); var singleName = GetSingleName(ctorParamName); var arrayParamNames = Enumerable.Range(1, 2).Select(x => $"{singleName}{x}").ToArray(); var existedParamNames = new HashSet <string>(mockInfos.Select(x => x.Name)); while (true) { if (arrayParamNames.Any(x => existedParamNames.Contains(x))) { for (var i = 0; i < arrayParamNames.Length; ++i) { arrayParamNames[i] = $"{arrayParamNames[i]}{i + 1}"; } } else { break; } } foreach (var arrayParamName in arrayParamNames) { // ReSharper disable once PossibleNullReferenceException var expression = factory.CreateExpression("$0;", dummyHelper.GetParamValue(scalarType.ToIType(), arrayParamName)); mockInfos.Add(new MockInfo { Statement = factory.CreateStatement("var $0 = $1;", arrayParamName, expression), Type = ((IArrayType)callParam.Type).ElementType, Name = arrayParamName }); } mockInfos.Add(new MockInfo { Statement = factory.CreateStatement("var $0 = $1;", callParam.ShortName, factory.CreateExpression($"new[] {{ {string.Join(", ", arrayParamNames)} }}")), Type = callParam.Type, Name = callParam.ShortName }); } else { mockInfos.Add(new MockInfo { Statement = factory.CreateStatement("var $0 = $1;", callParam.ShortName, factory.CreateExpression("$0;", dummyHelper.GetParamValue(callParam.Type, callParam.ShortName))), Type = callParam.Type, Name = callParam.ShortName }); } } return(mockInfos.ToArray()); }