protected override IClassMemberDeclaration CreateMemberDeclaration(CSharpElementFactory factory)
            {
                var declaration = factory.CreateFieldDeclaration(ExpressionType, "__");
                declaration.SetStatic(IsStatic);

                return declaration;
            }
            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)
        {
            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)
        {
            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 ContextActionExecutorBase(ICSharpStatement statement)
        {
            Contract.Requires(statement != null);

            _psiModule = statement.GetPsiModule();
            _psiServices = statement.GetPsiServices();
            _factory = CSharpElementFactory.GetInstance(statement);
            _currentFile = (ICSharpFile)statement.GetContainingFile();
        }
        private IAttribute createAttributeDeclaration(ITypeElement attributeType, string fixedParamValue, string namedParamName, string namedParamValue, IPsiModule psiModule, IModuleReferenceResolveContext resolveContext, IAttribute originalAttribute)
        {
            var fixedArguments = createFixedArguments(fixedParamValue, psiModule, resolveContext);
            var namedArguments = createNamedArguments(namedParamName, namedParamValue, psiModule, resolveContext, originalAttribute);

            var elementFactory       = CSharpElementFactory.GetInstance(psiModule);
            var attributeDeclaration = elementFactory.CreateAttribute(attributeType, fixedArguments, namedArguments);

            return(attributeDeclaration);
        }
            protected override IThrowStatement CreateStatement(CSharpElementFactory factory, ICSharpExpression expression)
            {
                var settingsStore       = expression.GetSettingsStore();
                var parenthesesType     = settingsStore.GetValue(CodeCompletionSettingsAccessor.ParenthesesInsertType);
                var parenthesesTemplate = parenthesesType.GetParenthesesTemplate(atStatementEnd: true);

                var template = string.Format("throw new {0}{1}", expression.GetText(), parenthesesTemplate);

                return((IThrowStatement)factory.CreateStatement(template, expression.GetText()));
            }
Example #8
0
        public static void SetDocComment(IDocCommentBlockOwner docCommentBlockOwnerNode, string text, ISolution solution)
        {
            text = String.Format("///{0}\r\nclass Tmp {{}}", text.Replace("\n", "\n///"));

            ICSharpTypeMemberDeclaration declaration =
                CSharpElementFactory.GetInstance(docCommentBlockOwnerNode.GetPsiModule()).CreateTypeMemberDeclaration(text, new object[0]);

            docCommentBlockOwnerNode.SetDocCommentBlock(
                ((IDocCommentBlockOwner)declaration).DocCommentBlock);
        }
Example #9
0
        protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
        {
            var awaitExpression     = configureAwaitHighlighting.AwaitExpression;
            var psiModule           = awaitExpression.GetPsiModule();
            var factory             = CSharpElementFactory.GetInstance(psiModule);
            var taskWithConfiguring = factory.CreateExpression($"$0.ConfigureAwait({GetConfigureAwaitValueText()})", awaitExpression.Task);

            awaitExpression.Task.ReplaceBy(taskWithConfiguring);
            return(null);
        }
        public PropertyConverter(CSharpElementFactory factory, IPsiModule psiModule, IClassDeclaration classDeclaration)
        {
            Argument.IsNotNull(() => factory);
            Argument.IsNotNull(() => psiModule);
            Argument.IsNotNull(() => classDeclaration);

            _factory = factory;
            _psiModule = psiModule;
            _classDeclaration = classDeclaration;
        }
Example #11
0
            protected override ICSharpExpression CreateExpression(CSharpElementFactory factory, ICSharpExpression expression)
            {
                if (IsConstructorInvocation(expression))
                {
                    // note: reinterpret constructor call as object creation expression
                    return(factory.CreateExpression("new $0", expression.GetText()));
                }

                return(expression);
            }
Example #12
0
            public void Accept(
                ITextControl textControl, TextRange nameRange, LookupItemInsertType lookupItemInsertType,
                Suffix suffix, ISolution solution, bool keepCaretStill)
            {
                textControl.Document.ReplaceText(nameRange, CASE_COMPLETION_NAME + "()");

                var psiServices = solution.GetPsiServices();

                psiServices.Files.CommitAllDocuments();

                var enumMember = Info.PreferredDeclaredElement;

                if (enumMember == null)
                {
                    return;
                }

                var invocationExpression = FindFakeInvocation(textControl, solution, nameRange.EndOffset);

                if (invocationExpression == null)
                {
                    return;
                }

                var factory  = CSharpElementFactory.GetInstance(invocationExpression);
                var template = (Info.IsFlagsEnum && !Info.IsZeroCase)
          ? (Info.IsMultiBitFlagCase ? "($0 & $1) != $1" : "($0 & $1) != 0")
          : "$0 == $1";

                var referenceExpression = (IReferenceExpression)invocationExpression.InvokedExpression;
                var qualifierExpression = referenceExpression.QualifierExpression;

                var enumMemberCheck = factory.CreateExpression(template, qualifierExpression, enumMember);

                var caretPointer = psiServices.DoTransaction(
                    commandName: typeof(EnumCaseCheckBehavior).FullName,
                    func: () =>
                {
                    using (WriteLockCookie.Create())
                    {
                        var memberCheck = invocationExpression.ReplaceBy(enumMemberCheck);
                        return(memberCheck.CreateTreeElementPointer());
                    }
                });

                if (caretPointer != null)
                {
                    var checkExpression = caretPointer.GetTreeNode();
                    if (checkExpression != null)
                    {
                        var offset = checkExpression.GetDocumentRange().TextRange.EndOffset;
                        textControl.Caret.MoveTo(offset, CaretVisualPlacement.DontScrollIfVisible);
                    }
                }
            }
        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));
        }
Example #14
0
            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 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);
        }
        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()));
        }
Example #17
0
            protected override IIfStatement CreateStatement(CSharpElementFactory factory, ICSharpExpression expression)
            {
                var template  = "if($0)" + EmbeddedStatementBracesTemplate;
                var statement = (IIfStatement)factory.CreateStatement(template, expression);

                var negated = CSharpExpressionUtil.CreateLogicallyNegatedExpression(statement.Condition);

                statement.Condition.ReplaceBy(negated.NotNull());

                return(statement);
            }
        protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
        {
            var factory = CSharpElementFactory.GetInstance(_theclass.GetPsiModule());

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

            AddProxyClass(_theclass, factory);
            return(null);
        }
Example #19
0
        protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
        {
            using (WriteLockCookie.Create())
            {
                var factory    = CSharpElementFactory.GetInstance(_stringLiteral.Expression, false);
                var expression = factory.CreateExpression(
                    $"\"{_stringLiteral.Expression.GetUnquotedText().Insert(_namedProperty.StartIndex + 1, "@")}\"");
                ModificationUtil.ReplaceChild(_stringLiteral.Expression, expression);
            }

            return(null);
        }
Example #20
0
        public static IPropertyDeclaration WithPrivateSetter([NotNull] this IPropertyDeclaration declaration,
                                                             CSharpElementFactory factory)
        {
            if (declaration == null)
            {
                throw new ArgumentNullException(nameof(declaration));
            }
            var setter = factory.CreateAccessorDeclaration(AccessorKind.SETTER, false);

            declaration.AddAccessorDeclarationBefore(setter, null);
            return(declaration);
        }
Example #21
0
        protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
        {
            var callTreeNode = error?.Reference.GetTreeNode();

            if (callTreeNode == null)
            {
                throw new ArgumentNullException();
            }

            if (callMethod == null ||
                !(callTreeNode is IReferenceExpression callExpression) ||
                !(callTreeNode.Parent is IInvocationExpression ctorArgumentOwner))
            {
                return(null);
            }

            var callParams = callMethod.Parameters;

            if (callParams.Count == 0)
            {
                return(null);
            }

            var psiModule = error.Reference.GetAccessContext().GetPsiModule();

            cSharpTypeConversionRule = psiModule.GetTypeConversionRule();
            var factory = CSharpElementFactory.GetInstance(psiModule);

            var methodDeclaration = callTreeNode.FindParent <IMethodDeclaration>();

            var existedArguments = ctorArgumentOwner.AllArguments(false)
                                   .Select(x => new ArgumentInfo
            {
                Type             = x.GetExpressionType()?.ToIType(),
                Expression       = (x as ICSharpArgument)?.Value,
                IsCSharpArgument = x is ICSharpArgument
            })
                                   .ToArray();

            var mockInfos = GenerateNewMockInfos(callParams, existedArguments, factory);

            AddMocksToClassDeclaration(methodDeclaration, ctorArgumentOwner, mockInfos);

            var argExpressions   = GetCtorArgumentExpressions(existedArguments, callParams);
            var argumentsPattern = string.Join(", ", Enumerable.Range(2, argExpressions.Length).Select(x => $"${x}"));
            var newExpression    = factory.CreateExpression($"$0.$1({argumentsPattern});", new[] { callExpression.FirstChild, callExpression.LastChild }.Concat(argExpressions).ToArray());

            ctorArgumentOwner.ReplaceBy(newExpression);

            AddUsings(mockInfos, factory);

            return(null);
        }
Example #22
0
        private static IAttribute CreateAttribute(IClrTypeName attributeTypeName,
                                                  [NotNull] AttributeValue[] attributeValues,
                                                  IPsiModule module,
                                                  CSharpElementFactory elementFactory)
        {
            var typeElement = TypeFactory.CreateTypeByCLRName(attributeTypeName, module).GetTypeElement();

            return(typeElement != null
                ? elementFactory.CreateAttribute(typeElement, attributeValues,
                                                 EmptyArray <Pair <string, AttributeValue> > .Instance)
                : null);
        }
Example #23
0
        /// <summary>
        /// Swap object creation to built in type.
        /// </summary>
        /// <param name="objectCreationExpressionNode">
        /// The object creation expression node.
        /// </param>
        private static void SwapObjectCreationToBuiltInType(IObjectCreationExpression objectCreationExpressionNode)
        {
            IPsiModule project = objectCreationExpressionNode.GetPsiModule();

            using (WriteLockCookie.Create(true))
            {
                IObjectCreationExpression tmpExpression =
                    (IObjectCreationExpression)
                    CSharpElementFactory.GetInstance(project).CreateExpression("new $0?()", new object[] { objectCreationExpressionNode.Type() });
                objectCreationExpressionNode.SetCreatedTypeUsage(tmpExpression.CreatedTypeUsage);
            }
        }
 protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
 {
     using (WriteLockCookie.Create())
     {
         var leftOperand   = myExpression.LeftOperand;
         var rightOperand  = myExpression.RightOperand;
         var factory       = CSharpElementFactory.GetInstance(myExpression);
         var newExpression = factory.CreateExpression("$0?$0:$1", leftOperand, rightOperand);
         ModificationUtil.ReplaceChild(myExpression, newExpression);
     }
     return(null);
 }
        public override MethodInvocation ProcessUsage(IReference reference)
        {
            var referenceExpression = reference.GetTreeNode() as IReferenceExpression;

            if (referenceExpression == null)
            {
                Driver.AddConflict(ReferenceConflict.CreateError(reference, "{0} can not be updated correctly.", "Usage"));
                return(null);
            }

            bool isExtensionMethod           = referenceExpression.IsExtensionMethod();
            IInvocationExpression invocation = InvocationExpressionNavigator.GetByInvokedExpression(referenceExpression);

            if (invocation == null)
            {
                Driver.AddConflict(ReferenceConflict.CreateError(reference, "{0} can not be updated correctly.", "Usage"));
                return(null);
            }

            ITreeNode element = GetArgument(invocation, isExtensionMethod);

            var   argument = element as ICSharpArgument;
            IType type     = argument != null?GetTypeOfValue(argument.Value) : GetTypeOfValue(element);

            if (type == null || !type.CanUseExplicitly(invocation))
            {
                Driver.AddConflict(ReferenceConflict.CreateError(
                                       reference, "Argument of {0} is not valid 'typeof' expression.", "usage"));
                return(null);
            }

            // we can rely on resolve result since method declaration is not yet changed.
            ResolveResultWithInfo resolveResult = reference.Resolve();
            ISubstitution         substitution  = resolveResult.Result.Substitution;
            var method = resolveResult.DeclaredElement as IMethod;

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

            if (argument != null)
            {
                invocation.RemoveArgument(argument);
                return(new MethodInvocation(reference, type, method, substitution));
            }

            CSharpElementFactory factory = CSharpElementFactory.GetInstance(invocation.GetPsiModule());
            IReferenceExpression newInvokedExpression =
                invocation.InvokedExpression.ReplaceBy(factory.CreateReferenceExpression("$0", Executer.Method));

            return(new MethodInvocation(newInvokedExpression.Reference, type, method, substitution));
        }
        private void Generate(CSharpGeneratorContext context,
                              IMethodDeclaration declaration,
                              IList <GeneratorDeclaredElement <ITypeOwner> > elements,
                              CSharpElementFactory factory)
        {
            var builder = new StringBuilder();

            builder.Append("{").AppendFormat("{0}(bytes, 0);", ReadMethodGenerator.Instance.MethodName).Append("}");

            IBlock body = factory.CreateBlock(builder.ToString());

            declaration.SetBody(body);
        }
        public static INamespace GetNamespaceDeclaration(ICSharpExpression expression)
        {
            CSharpElementFactory elementFactory = CSharpElementFactory.GetInstance(expression.GetPsiModule());

            if (expression.ConstantValue.IsString())
            {
                string namespaceName = Convert.ToString(expression.ConstantValue.Value);

                return(elementFactory.CreateNamespaceDeclaration(namespaceName).DeclaredElement);
            }

            return(null);
        }
        protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
        {
            var factory = CSharpElementFactory.GetInstance(myExpression);

            var newScalars    = myScalars.Select(t => t.CopyWithResolve()).ToList();
            var newExpression = RemoveScalars(factory, myExpression);

            var scalars = CreateMulExpression(factory, newScalars);

            myExpression.ReplaceBy(factory.CreateExpression(mul, newExpression, scalars));

            return(null);
        }
        protected override void Process(CSharpGeneratorContext context)
        {
            // this is where you build new code
            // to modify, e.g., an existing class, use context.ClassDeclaration

            CSharpElementFactory elementFactory = CSharpElementFactory.GetInstance(context.Root.GetPsiModule());

            GeneratorDeclaredElement <ITypeOwner>[] typeOwners = context.InputElements.OfType <GeneratorDeclaredElement <ITypeOwner> >().ToArray();
            foreach (var methodGenerator in MethodGenerators.All)
            {
                methodGenerator.Generate(context, typeOwners, elementFactory);
            }
        }
            ICSharpCommentNode CreateCommentNode([NotNull] CSharpElementFactory factory, CommentType commentType)
            {
                Debug.Assert(InjectorProvider.LanguageEqualsCommentTexts != null);

                switch (commentType)
                {
                case CommentType.END_OF_LINE_COMMENT: return(factory.CreateComment("// " + InjectorProvider.LanguageEqualsCommentTexts[0]));

                case CommentType.MULTILINE_COMMENT: return(factory.CreateComment("/* " + InjectorProvider.LanguageEqualsCommentTexts[0] + " */"));

                default: throw new NotSupportedException();
                }
            }
            protected override IClassMemberDeclaration CreateMemberDeclaration(CSharpElementFactory factory)
            {
                var declaration = factory.CreatePropertyDeclaration(ExpressionType, "__");
                declaration.SetAccessRights(AccessRights.PUBLIC);
                var getter = factory.CreateAccessorDeclaration(AccessorKind.GETTER, false);
                var setter = factory.CreateAccessorDeclaration(AccessorKind.SETTER, false);

                declaration.AddAccessorDeclarationAfter(getter, null);
                declaration.AddAccessorDeclarationBefore(setter, null);
                declaration.SetStatic(IsStatic);

                return declaration;
            }
Example #32
0
        public static IClassMemberDeclaration CreatePropertyDeclaration(this CSharpElementFactory factory,
                                                                        IType typeExpression, string memberName, bool isReadOnly, AccessRights accessRights)
        {
            var declaration = factory.CreatePropertyDeclaration(typeExpression, memberName);

            declaration.SetAccessRights(accessRights);
            declaration.WithPrivateGetter(factory);
            if (!isReadOnly)
            {
                declaration.WithPrivateSetter(factory);
            }
            return(declaration);
        }
        protected override Action <ITextControl> ExecutePsiTransaction(ISolution _, IProgressIndicator __)
        {
            var classLikeDeclaration = Highlighting.HighlightingNode;

            var elementFactory = CSharpElementFactory.GetInstance(classLikeDeclaration, applyCodeFormatter: true);

            var serializableAttributeType = PredefinedType.SERIALIZABLE_ATTRIBUTE_CLASS.CreateTypeInContextOf(classLikeDeclaration);
            var attribute = elementFactory.CreateAttribute(serializableAttributeType.GetTypeElement().NotNull());

            classLikeDeclaration.AddAttributeBefore(attribute, null);

            return(null);
        }
        protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
        {
            using (WriteLockCookie.Create())
            {
                // ReSharper disable once AssignNullToNotNullAttribute
                var factory = CSharpElementFactory.GetInstance(_argument.Expression, false);

                var expression = factory.CreateExpression($"\"{_suggestedName}\"");
                ModificationUtil.ReplaceChild(_argument.Expression, expression);
            }

            return(null);
        }
Example #35
0
        private static void ProcessImports(
            IList <IUsingDirective> newImportsList,
            AlphabeticalUsingsStyle organiseUsingsFormatOption,
            ExpandUsingsStyle expandUsingsFormatOption,
            ICSharpTypeAndNamespaceHolderDeclaration declaration)
        {
            if (newImportsList == null || newImportsList.Count == 0)
            {
                return;
            }

            List <IUsingDirective> arrayList = new List <IUsingDirective>();

            arrayList.AddRange(newImportsList);

            if (organiseUsingsFormatOption == AlphabeticalUsingsStyle.Alphabetical)
            {
                arrayList.Sort(new UsingStatementSorter());
            }

            foreach (IUsingDirective directive in arrayList)
            {
                IUsingDirective newUsingDirective;

                if (expandUsingsFormatOption == ExpandUsingsStyle.FullyQualify)
                {
                    if (directive is IUsingAliasDirective)
                    {
                        IUsingAliasDirective aliasDirective = directive as IUsingAliasDirective;
                        newUsingDirective =
                            CSharpElementFactory.GetInstance(declaration.GetPsiModule())
                            .CreateUsingDirective(aliasDirective.AliasName + " = " + directive.GetFullyQualifiedNamespace());

                        IUsingAliasDirective n = newUsingDirective as IUsingAliasDirective;
                        n.SetImportedSymbolName(aliasDirective.ImportedSymbolName);
                    }
                    else
                    {
                        newUsingDirective = CSharpElementFactory.GetInstance(declaration.GetPsiModule()).CreateUsingDirective(directive.GetFullyQualifiedNamespace());
                    }
                }
                else
                {
                    newUsingDirective = directive.CopyWithResolve();
                }

                declaration.RemoveImport(directive);
                declaration.AddImportBefore(newUsingDirective, null);
            }
        }
        private void GenerateRefereingProperty()
        {
            var fieldDeclaration = _highlighing.FieldDeclaration;
            var factory          = CSharpElementFactory.GetInstance(fieldDeclaration);

            var propertyDeclaration =
                (IClassMemberDeclaration)factory.CreateTypeMemberDeclaration(
                    "public $0 $1 {get {return $2;}}",
                    fieldDeclaration.Type, _highlighing.PropertyName, fieldDeclaration.NameIdentifier);

            var typeDeclaration = (IClassLikeDeclaration)fieldDeclaration.GetContainingTypeDeclaration();

            typeDeclaration.AddClassMemberDeclarationAfter(propertyDeclaration, fieldDeclaration);
        }
        public override ITypeParameter AddTypeParameter(IDeclaration declaration)
        {
            var methodDeclaration = declaration as IMethodDeclaration;

            if (methodDeclaration != null)
            {
                CSharpElementFactory factory = CSharpElementFactory.GetInstance(declaration.GetPsiModule());
                ITypeParameterOfMethodDeclaration parameter =
                    methodDeclaration.AddTypeParameterBefore(
                        factory.CreateTypeParameterOfMethodDeclaration(Workflow.TypeParameterName), null);
                return(parameter.DeclaredElement);
            }
            return(null);
        }
Example #38
0
        public static IClassMemberDeclaration CreatePrivatePropertyDeclaration(this CSharpElementFactory factory,
                                                                               IType typeExpression, string memberName)
        {
            var declaration = factory.CreatePropertyDeclaration(typeExpression, memberName);

            declaration.SetAccessRights(AccessRights.PRIVATE);
            var getter = factory.CreateAccessorDeclaration(AccessorKind.GETTER, false);
            var setter = factory.CreateAccessorDeclaration(AccessorKind.SETTER, false);

            declaration.AddAccessorDeclarationAfter(getter, null);
            declaration.AddAccessorDeclarationBefore(setter, null);

            return(declaration);
        }
        protected ContextActionExecutorBase(ICSharpContextActionDataProvider provider)
        {
            Contract.Requires(provider != null);


            _factory = provider.ElementFactory;

            Contract.Assert(provider.SelectedElement != null,
                "Can't create executor if SelectedElement is null");

            _currentFile = (ICSharpFile)provider.SelectedElement.GetContainingFile();
            _psiServices = provider.PsiServices;
            _psiModule = provider.PsiModule;
        }
        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 void PlaceExpression(
 IForStatement forStatement, ICSharpExpression expression, CSharpElementFactory factory)
     {
         var condition = (IRelationalExpression) forStatement.Condition;
         if (LengthPropertyName == null)
         {
           condition.RightOperand.ReplaceBy(expression);
         }
         else
         {
           var lengthAccess = factory.CreateReferenceExpression("expr.$0", LengthPropertyName);
           lengthAccess = condition.RightOperand.ReplaceBy(lengthAccess);
           lengthAccess.QualifierExpression.NotNull().ReplaceBy(expression);
         }
     }
        public AddContractClassExecutor(ICSharpContextActionDataProvider provider, AddContractClassAvailability addContractForAvailability, 
            ICSharpFunctionDeclaration requiredFunction = null)
        {
            Contract.Requires(provider != null);
            Contract.Requires(addContractForAvailability != null);
            Contract.Requires(addContractForAvailability.IsAvailable);

            _addContractForAvailability = addContractForAvailability;
            _provider = provider;
            _requiredFunction = requiredFunction;

            _factory = _provider.ElementFactory;
            // TODO: look at this class CSharpStatementNavigator

            Contract.Assert(provider.SelectedElement != null);
            
            _currentFile = (ICSharpFile)provider.SelectedElement.GetContainingFile();
        }
        public AddContractForExecutor(AddContractForAvailability addContractForAvailability,
            ICSharpContextActionDataProvider provider)
        {
            Contract.Requires(addContractForAvailability != null);
            Contract.Requires(addContractForAvailability.IsAvailable);
            Contract.Requires(provider != null);

            _addContractForAvailability = addContractForAvailability;
            _provider = provider;

            _factory = CSharpElementFactory.GetInstance(provider.PsiModule);
            // TODO: look at this class CSharpStatementNavigator

            _classDeclaration = provider.GetSelectedElement<IClassLikeDeclaration>(true, true);

            Contract.Assert(provider.SelectedElement != null);
            _currentFile = (ICSharpFile)provider.SelectedElement.GetContainingFile();

        }
            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));
                }
            }
            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 static void EnsureNamespaceExists(ICSharpFile file, CSharpElementFactory factory)
        {
            var namespaceExists =
                file.NamespaceDeclarationNodes.Any(
                    n => n.Imports.Any(d => d.ImportedSymbolName.QualifiedName == AsObservableNamespace));

            if (!namespaceExists)
            {
                var directive = factory.CreateUsingDirective(AsObservableNamespace);

                var namespaceNode = file.NamespaceDeclarationNodes.FirstOrDefault();
                if (namespaceNode != null)
                {
                    UsingUtil.AddImportTo(namespaceNode, directive);
                }
                else
                {
                    UsingUtil.AddImportTo(file, directive);
                }
            }
        }
        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);
        }
 private static void SortEnumMembers(ISolution solution, IEnumDeclaration enumDeclaration,
                                     CSharpElementFactory factory)
 {
     try {
         var enumMembers = new SortedDictionary<string, IEnumMemberDeclaration>();
         foreach (IEnumMemberDeclaration enumMember in enumDeclaration.EnumMemberDeclarations) {
             enumMembers.Add(enumMember.DeclaredName, enumMember);
         }
         IEnumMemberDeclaration firstEnumMember = null;
         foreach (IEnumMemberDeclaration enumMember in enumMembers.Values) {
             firstEnumMember = enumMember;
             break;
         }
         foreach (IEnumMemberDeclaration enumMember in enumMembers.Values) {
             if (enumMember != firstEnumMember) {
                 enumDeclaration.RemoveEnumMemberDeclaration(enumMember);
             }
         }
         IEnumMemberDeclaration lastEnumMember = enumDeclaration.EnumMemberDeclarations[0];
         foreach (IEnumMemberDeclaration enumMember in enumMembers.Values) {
             if (enumMember != firstEnumMember) {
                 IEnumMemberDeclaration newMember = factory.CreateEnumMemberDeclaration(enumMember.DeclaredName);
                 newMember.SetValueExpression(enumMember.ValueExpression);
                 lastEnumMember = enumDeclaration.AddEnumMemberDeclarationAfter(newMember, lastEnumMember);
             }
         }
     }
     catch (Exception err) {
         Exception e = err;
     }
 }
        /// <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);
        }
        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);
        }
 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());
 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("!string.{0}($0)", nameof(string.IsNullOrEmpty)), contractExpression);
        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 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);
        }
 public SplitCallChainContextAction([NotNull] ICSharpContextActionDataProvider provider)
 {
   myProvider = provider;
   myFactory = CSharpElementFactory.GetInstance(provider.PsiModule);
 }
Example #59
0
 private IDeclarationStatement CreateStubDeclaration(CSharpElementFactory factory, IExpectedTypeConstraint typeConstraint)
 {
     return (IDeclarationStatement)factory.CreateStatement(
         "var $0 = MockRepository.GenerateStub<$1>();",
         _referenceName,
         GetStubInterfaceName(typeConstraint));
 }
        /// <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);
        }