public override bool IsAvailable(IUserDataHolder cache)
 {
     myClassDeclaration = myProvider.GetSelectedElement<IClassDeclaration>(true, true);
       // this context action is available on every class at the moment
       // TODO: add some constraints, like: there is already a test for this class
       return myClassDeclaration != null;
 }
Exemple #2
0
 private UnitTestElementLocation GetUnitTestElementLocation(IClassDeclaration declaration)
 {
     var navigationRange = declaration.GetNameDocumentRange().TextRange;
       var containingRange = declaration.GetDocumentRange().TextRange;
       var projectFile = declaration.GetContainingFile().AssertNotNull().GetSourceFile().ToProjectFile();
       return new UnitTestElementLocation(projectFile, navigationRange, containingRange);
 }
        public static IPropertyDeclaration GetPropertyDeclaration(IClassDeclaration classDeclaration, IInvocationExpression invocationExpression)
        {
            IPropertyDeclaration propertyDeclaration = null;
            if (invocationExpression.ArgumentList.Arguments.Count >= 1)
            {
                string propertyName = null;
                var argument = invocationExpression.ArgumentList.Arguments[0];
                if (argument.Value is ILambdaExpression)
                {
                    var lambdaExpression = argument.Value as ILambdaExpression;
                    var referenceExpression = lambdaExpression.BodyExpression as IReferenceExpression;
                    if (referenceExpression != null)
                    {
                        propertyName = referenceExpression.NameIdentifier.Name;
                    }
                }
                else if (argument.Value != null && argument.Value.ConstantValue != null)
                {
                    propertyName = argument.Value.ConstantValue.Value.ToString();
                }

                if (!string.IsNullOrEmpty(propertyName) && classDeclaration.DeclaredElement != null)
                {
                    var property = (from member in classDeclaration.DeclaredElement.GetMembers().OfType<IProperty>() where member.ShortName == propertyName select member).FirstOrDefault();
                    if (property != null)
                    {
                        propertyDeclaration = (IPropertyDeclaration) property.GetDeclarations().FirstOrDefault();
                    }
                }
            }

            return propertyDeclaration;
        }
        public PropertyConverter(CSharpElementFactory factory, IPsiModule psiModule, IClassDeclaration classDeclaration)
        {
            Argument.IsNotNull(() => factory);
            Argument.IsNotNull(() => psiModule);
            Argument.IsNotNull(() => classDeclaration);

            _factory = factory;
            _psiModule = psiModule;
            _classDeclaration = classDeclaration;
        }
        private void ImplementInterfaceOrBaseClass(IClassDeclaration contractClass, IProgressIndicator progress)
        {
            
            string generateKind = GeneratorStandardKinds.Implementations;
            if (_addContractForAvailability.IsAbstractClass)
                generateKind = GeneratorStandardKinds.Overrides;

            using (var workflow = GeneratorWorkflowFactory.CreateWorkflowWithoutTextControl(
                generateKind,
                contractClass,
                contractClass))
                //_addContractForAvailability.TypeDeclaration))
            {
                Contract.Assert(workflow != null);

                

                workflow.Context.SetGlobalOptionValue(CSharpBuilderOptions.PropertyBody,
                    CSharpBuilderOptions.PropertyBodyDefault);

                workflow.Context.SetGlobalOptionValue(
                  CSharpBuilderOptions.ImplementationKind,
                  CSharpBuilderOptions.ImplementationKindExplicit);
                
                //var globalActions = workflow.Context.GlobalOptions;
                //var dd = globalActions
                //    .FirstOrDefault(g => g.ID == CSharpBuilderOptions.ImplementationKind);
                //if (dd != null)
                //{
                //    dd.OverridesGlobalOption = true;
                //    dd.Value = CSharpBuilderOptions.ImplementationKindPublicMember;
                //}

                workflow.Context.Anchor = contractClass;
                workflow.Context.InputElements.Clear();

                Contract.Assert(workflow.Context.ProvidedElements.Count != 0);
                workflow.Context.InputElements.AddRange(workflow.Context.ProvidedElements);
                //foreach (var e in workflow.Context.ProvidedElements)
                //{
                //    workflow.Context.InputElements.Add(e);
                //}


                //workflow.Context.GlobalOptions.Clear();
                
                

                

                workflow.GenerateAndFinish("Generate contract class", progress);
            }
        }
Exemple #6
0
 public ClassTestDeclaration(
 IIdentity identity,
 IProject project,
 string text,
 IEnumerable<ITestDeclaration> testDeclarations,
 IClassDeclaration classDeclaration)
     : base(classDeclaration)
 {
     _identity = identity;
       _project = project;
       _text = text;
       _testDeclarations = testDeclarations;
 }
Exemple #7
0
        public string Present(IClassDeclaration classDeclaration)
        {
            var clazz = (IClass) classDeclaration.DeclaredElement;

              var subjectAttributeData = clazz.GetAttributeData<SubjectAttributeBase>();
              if (subjectAttributeData == null)
            return null;

              var subjectAttribute = subjectAttributeData.ToCommon();
              var subjectAttributeClass = subjectAttributeData.GetAttributeType().GetTypeElement<IClass>().AssertNotNull();
              var subjectAttributeConstructor = subjectAttributeClass.Constructors.Single();
              var displayFormatAttribute = subjectAttributeConstructor.GetAttributeData<DisplayFormatAttribute>().ToCommon();
              return _introspectionPresenter.Present(displayFormatAttribute, subjectAttribute);
        }
Exemple #8
0
        public string Present(IClassDeclaration classDeclaration)
        {
            var clazz = (IClass) classDeclaration.DeclaredElement;

              var subjectAttributeData = clazz.GetAttributeData<SuiteAttributeBase>();
              if (subjectAttributeData == null)
            return null;

              var subjectAttribute = subjectAttributeData.ToCommon();

              var subjectAttributeConstructor = subjectAttributeData.Constructor;
              var displayFormatAttribute = subjectAttributeConstructor.GetAttributeData<DisplayFormatAttribute>().ToCommon();

              return _introspectionPresenter.Present(displayFormatAttribute, clazz.ToCommon(), subjectAttribute);
        }
        public override bool IsAvailable(IUserDataHolder cache)
        {
            using (ReadLockCookie.Create())
            {
                if (Provider.SelectedElement != null)
                {
                    _superType = TypeHelper.CreateTypeByCLRName(SuperTypeName, Provider.PsiModule, Provider.SelectedElement.GetResolveContext());
                    if (_superType.GetTypeElement() != null)
                    {
                        _classDeclaration = Provider.SelectedElement.Parent as IClassDeclaration;
                    }
                }
            }

            // !_classDeclaration.IsStatic doesn't work, IsStatic is returns true
            return _classDeclaration != null && !_classDeclaration.IsStaticEx() && _classDeclaration.SuperTypes.IsEmpty();
        }
		public override void VisitClassDeclaration(IClassDeclaration classDeclarationParam, IHighlightingConsumer context) {
			base.VisitClassDeclaration(classDeclarationParam, context);

			if (!classDeclarationParam.IsSynthetic()
			|| !T4CSharpCodeGenerator.ClassName.Equals(classDeclarationParam.DeclaredName, StringComparison.Ordinal))
				return;

			IDeclaredTypeUsage superTypeUsage = classDeclarationParam.SuperTypeUsageNodes.FirstOrDefault();
			if (superTypeUsage == null
			|| T4CSharpCodeGenerator.DefaultBaseClassName.Equals(superTypeUsage.GetText(), StringComparison.Ordinal))
				return;

			ITypeElement typeElement = CSharpTypeFactory.CreateDeclaredType(superTypeUsage).GetTypeElement();
			if (typeElement == null)
				return;

			if (!typeElement.Methods.Any(IsTransformTextMethod))
				context.AddHighlighting(new MissingTransformTextMethodHighlighting(superTypeUsage));
		}
        private void SetClassAndMembersUsed(IClassDeclaration classDeclaration)
        {
            ITypeElement typeElement = classDeclaration.DeclaredElement;
            if (typeElement == null || (typeElement is IClass == false))
            {
                return;
            }

            foreach (ITypeMember typeMember in typeElement.GetMembers())
            {
                var method = typeMember as IMethod;
                if (method != null)
                {
                    usages.SetElementState(method, UsageState.ALL_MASK);
                }
            }

            usages.SetElementState(typeElement, UsageState.ALL_MASK);
        }
        public override sealed bool IsAvailable(IUserDataHolder cache)
        {
            using (ReadLockCookie.Create())
            {
                var selectedElement = Provider.SelectedElement;
                var moduleReferenceResolveContext = selectedElement.GetResolveContext();
                if (selectedElement != null && selectedElement.Parent is IPropertyDeclaration)
                {
                    _propertyDeclaration = selectedElement.Parent as IPropertyDeclaration;
                    if (_propertyDeclaration.IsAuto && _propertyDeclaration.Parent != null
                        && _propertyDeclaration.Parent.Parent is IClassDeclaration)
                    {
                        _classDeclaration = _propertyDeclaration.Parent.Parent as IClassDeclaration;
                    }
                }
            }

            return _classDeclaration != null && _classDeclaration.DeclaredElement != null
                   && (_classDeclaration.DeclaredElement.IsDescendantOf(CatelCore.GetDataObjectBaseTypeElement(Provider.PsiModule, _classDeclaration.GetResolveContext()))
                       || _classDeclaration.DeclaredElement.IsDescendantOf(CatelCore.GetModelBaseTypeElement(Provider.PsiModule, _classDeclaration.GetResolveContext())));
        }
        public override bool IsAvailable(IUserDataHolder cache)
        {
            //reset
            this._class = null;

            ITreeNode element = this._actionDataProvider.SelectedElement;

            if (null == element)
            {
                return false;
            }

            this._class = element.Parent as IClassDeclaration;

            if (null == this._class)
            {
                return false;
            }

            return this.HasDataMembers(this._class);
        }
        /// <summary>
        /// Adds <paramref name="contractClass"/> after implemented interface into the physical tree.
        /// </summary>
        /// <remarks>
        /// This method is absolutely crucial, because all R# "generate workflows" works correcntly
        /// only if TreeNode.IsPhysical() returns true.
        /// </remarks>
        private IClassDeclaration AddToPhysicalDeclaration(IClassDeclaration contractClass)
        {
            var holder = CSharpTypeAndNamespaceHolderDeclarationNavigator.GetByTypeDeclaration(
                _addContractForAvailability.TypeDeclaration);
            Contract.Assert(holder != null);
            
            var physicalContractClassDeclaration =
                (IClassDeclaration) holder.AddTypeDeclarationAfter(contractClass,
                    _addContractForAvailability.TypeDeclaration);

            return physicalContractClassDeclaration;
        }
        private IAttribute CreateContractClassAttribute(IClassDeclaration contractClass)
        {
            ITypeElement attributeType = TypeFactory.CreateTypeByCLRName(
                typeof(ContractClassAttribute).FullName,
                _provider.PsiModule, _currentFile.GetResolveContext()).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;
        }
 private void ImplementInterfaceOrBaseClass(IClassDeclaration contractClass)
 {
     if (_addContractForAvailability.IsAbstractClass)
     {
         ImplementContractForAbstractClass(contractClass, _addContractForAvailability.ClassDeclaration);
     }
     else
     {
         ImplementContractForInterface(contractClass, _addContractForAvailability.InterfaceDeclaration);
     }
 }
        private void AddNonDefaultConstructorIfNeeded(IClassDeclaration contractClass)
        {
            if (!_addContractForAvailability.IsAbstractClass)
                return;

            var abstractBaseClass = _addContractForAvailability.ClassDeclaration;

            using (var workflow = GeneratorWorkflowFactory.CreateWorkflowWithoutTextControl(
                GeneratorStandardKinds.Constructor,
                contractClass,
                abstractBaseClass))
            {
                Contract.Assert(workflow != null);

                var ctor = 
                    workflow.Context.ProvidedElements
                    .OfType<GeneratorDeclaredElement<IConstructor>>()
                    .FirstOrDefault(c => !c.DeclaredElement.IsDefault);

                if (ctor != null)
                { 
                    workflow.Context.InputElements.Clear();
                    workflow.Context.InputElements.Add(ctor);
                    workflow.BuildOptions();
                    workflow.Generate("Generate missing constructor", NullProgressIndicator.Instance);
                }
            }

        }
        private void ImplementContractForAbstractClass(IClassDeclaration contractClass,
            IClassDeclaration abstractClass)
        {
            Contract.Requires(contractClass != null);
            Contract.Requires(contractClass.DeclaredElement != null);
            Contract.Requires(abstractClass != null);
            Contract.Requires(abstractClass.DeclaredElement != null);

            using (var workflow = GeneratorWorkflowFactory.CreateWorkflowWithoutTextControl(
                GeneratorStandardKinds.Overrides,
                contractClass,
                abstractClass))
            {
                Contract.Assert(workflow != null);

                // By default this input for this workflow contains too many members:
                // It contains member from the base class (required) and
                // members from the other base classes (i.e. from System.Object).
                // Using some hack to get only members defined in the "abstractClass"

                // So I'm trying to find required elements myself.

                var missingMembers = contractClass.GetMissingMembersOf(abstractClass);
                
                if (_requiredFunction != null)
                {
                    var requiredDeclaration = _requiredFunction.DeclaredElement;
                    missingMembers = 
                        missingMembers.Where(x => GetMembers(x).Any(m => m.Equals(requiredDeclaration)))
                            .ToList();

                    Contract.Assert(missingMembers.Count != 0, "Should be at least one method to add!");
                }

                var membersToOverride =
                    missingMembers
                        .Select(x => new GeneratorDeclaredElement<IOverridableMember>(x.Member, x.Substitution))
                        .ToList();

                workflow.Context.InputElements.Clear();

                workflow.Context.ProvidedElements.Clear();
                workflow.Context.ProvidedElements.AddRange(membersToOverride);

                workflow.Context.InputElements.AddRange(workflow.Context.ProvidedElements);

                workflow.Generate("Generate contract class", NullProgressIndicator.Instance);
            }
        }
        private void ImplementContractForInterface(IClassDeclaration contractClass,
            IInterfaceDeclaration interfaceDeclaration)
        {
            Contract.Requires(contractClass != null);
            Contract.Requires(interfaceDeclaration != null);

            if (interfaceDeclaration.MemberDeclarations.Count == 0)
                return;

            using (var workflow = GeneratorWorkflowFactory.CreateWorkflowWithoutTextControl(
                GeneratorStandardKinds.MissingMembers,
                contractClass,
                interfaceDeclaration))
            {
                Contract.Assert(workflow != null);

                workflow.Context.InputElements.Clear();
                workflow.Context.InputElements.AddRange(workflow.Context.ProvidedElements);

                workflow.Context.SetOption(
                    CSharpBuilderOptions.ImplementationKind,
                    CSharpBuilderOptions.ImplementationKindExplicit);

                workflow.Generate("Generate contract class", NullProgressIndicator.Instance);
            }
        }
 private IConstructEnumerable<IMemberDeclaration> GetPropertiesForWrapping(IClassDeclaration classDeclaration)
 {
     return classDeclaration.ContainedMembers().Where(m => m.Is<IPropertyDeclaration>() && IsPropertyVisibleOutsideClass(m.Modifiers));
 }
        private void AddContractClassForInterface(IClassDeclaration classDeclaration)
        {
            Contract.Assert(_addContractForAvailability.InterfaceDeclaration.DeclaredElement != null);
            var interfaceType = TypeFactory.CreateType(_addContractForAvailability.InterfaceDeclaration.DeclaredElement);
            
            classDeclaration.AddSuperInterface(interfaceType, false);

            //var interfaceDeclaration = _addContractForAvailability.InterfaceDeclaration;
            //IClassMemberDeclaration previousDeclaration = null;
            //foreach (var memberDeclaration in interfaceDeclaration.ClassMemberDeclarations)
            //{
                
            //    classDeclaration.AddClassMemberDeclarationAfter(memberDeclaration, previousDeclaration);

            //    previousDeclaration = memberDeclaration;
            //}

        }
        private List<IPropertyDeclaration> GetPropertiesForWrappingByName(IClassDeclaration classDeclaration, List<string> confirmedPropertiesNamesForWrapping)
        {
            List<IPropertyDeclaration> properties = new List<IPropertyDeclaration>();
            IConstructEnumerable<IDeclaration> containedDeclarations = classDeclaration.ContainedDeclarations;

            foreach (string propertyName in confirmedPropertiesNamesForWrapping)
            {
                IPropertyDeclaration property = containedDeclarations.First(d => string.Equals(propertyName, d.Identifier.Name, StringComparison.Ordinal))
                    .As<IPropertyDeclaration>();
                if (property.Exists)
                {
                    properties.Add(property);
                }
            }

            return properties;
        }
 private bool ImplementsINotifyPropertyChanged(IClassDeclaration classDeclaration)
 {
     return classDeclaration.Type().AllSuperTypesIncludingThis.Any(t => t.Is(PropertyChangedQualifiedTypeName));
 }
        private IClassDeclaration ImplementINotifyPropertyChangedInterface(IClassDeclaration viewModel, IClassDeclaration wrappedClass)
        {
            UsingDirectiveHelper.AddUsingDirectiveIfNeeded(wrappedClass, "System", "ComponentModel");

            IConstructLanguage language = viewModel.Language;
            IIdentifier identifier = language.Identifier(PropertyChangedSimpleTypeName);
            ITypeName typeName = language.SimpleTypeName(identifier, language.None<ITypeArguments>());
            viewModel.IntroduceInterface(typeName);

            wrappedClass.Append(viewModel);
            string name = viewModel.Identifier.Name;
            viewModel = RebuildSolutionModel(wrappedClass, name);

            AddStubsHelper.CreateAllUnimplementedMembers(viewModel, new AddStubsOptions());

            return RebuildSolutionModel(wrappedClass, name);
        }
        private void InsertWrappedProperties(IClassDeclaration viewModel, List<IPropertyDeclaration> confirmedPropertiesForWrapping, IFieldDeclaration wrappedClassField, IIdentifier onPropertyChangedIdentifier)
        {
            IConstructLanguage language = viewModel.Language;

            foreach (IPropertyDeclaration property in confirmedPropertiesForWrapping)
            {
                IMemberAccess propertyMemberAccess = language.MemberAccess(
                    language.MemberAccess(language.None<IExpression>(), wrappedClassField.Identifier),
                    property.Identifier);

                IAccessor getterOfWrapper = language.None<IAccessor>();
                IAccessor propertyGetter = property.Getter();

                if (propertyGetter.Exists && IsAccessorVisibleOutsideClass(propertyGetter.Modifiers))
                {
                    getterOfWrapper = language.Getter(
                        language.Modifiers(propertyGetter.Modifiers.Modifiers),
                        language.Block(
                            language.ReturnStatement(propertyMemberAccess)));
                }

                IAccessor setterOfWrapper = language.None<IAccessor>();
                IAccessor propertySetter = property.Setter();

                if (propertySetter.Exists && IsAccessorVisibleOutsideClass(propertySetter.Modifiers))
                {
                    IStatement assignment = language.AssignmentStatement(propertyMemberAccess, language.Expression("value"));

                    IMethodInvocation onPropertyChangedInvocation =
                        language.MethodInvocation(
                            language.None<IExpression>(),
                            onPropertyChangedIdentifier,
                            language.None<ITypeArguments>(),
                            language.Arguments(
                                language.Argument(language.StringLiteral(property.Identifier.Name))));

                    IIfStatement ifStatement =
                        language.IfStatement(
                            language.BinaryExpression(propertyMemberAccess,
                                Operator.NotEqual,
                                language.Expression("value")),
                            language.Block(assignment, language.ExpressionStatement(onPropertyChangedInvocation)));

                    setterOfWrapper = language.Setter(
                        language.Modifiers(propertyGetter.Modifiers.Modifiers),
                        language.Block(ifStatement));
                }

                if (getterOfWrapper.Exists || setterOfWrapper.Exists)
                {
                    IPropertyDeclaration wrapperProperty = language.Property(
                                                            language.None<IDocComment>(),
                                                            language.None<IAttributes>(),
                                                            property.Modifiers,
                                                            property.TypeName,
                                                            property.Identifier,
                                                            getterOfWrapper,
                                                            setterOfWrapper);
                    viewModel.Insert(wrapperProperty);
                }
            }
        }
 private IClassDeclaration RebuildSolutionModel(IClassDeclaration wrappedClass, string name)
 {
     wrappedClass.SolutionModel.RebuildWithCurrentModifications();
     IClassDeclaration viewModel = wrappedClass.FileModel.All<IClassDeclaration>().First(c => string.Equals(c.Identifier.Name, name, System.StringComparison.Ordinal));
     return viewModel;
 }
 private void AddContractClassAttributeIfNeeded(IClassDeclaration contractClass)
 {
     if (!_addContractForAvailability.TypeDeclaration.HasAttribute(typeof (ContractClassAttribute)))
     {
         var attribute = CreateContractClassAttribute(contractClass);
         _addContractForAvailability.TypeDeclaration.AddAttributeAfter(attribute, null);
     }
 }
 private void AddExcludeFromCodeCoverageAttributeIfNeeded(IClassDeclaration contractClass)
 {
     if (ShouldUseExcludeFromCodeCoverageAttribute())
     { 
         var attribute = CreateExcludeFromCodeCoverageAttribute();
         contractClass.AddAttributeAfter(attribute, null);
     }
 }
 private void AddContractClassForAttributeTo(IClassDeclaration contractClass)
 {
     var attribute = CreateContractClassForAttribute(_addContractForAvailability.TypeDeclaration);
     contractClass.AddAttributeAfter(attribute, null);
 }
 private void AddContractClassForAbstractClass(IClassDeclaration classDeclaration)
 {
     throw new System.NotImplementedException();
 }