private List <ITreeNode> FindArrayUsages(IDeclaredElement declaredElement, IClassLikeDeclaration container, IDaemonProcess daemonProcess, DaemonProcessKind processKind)
        {
            var result = new List <ITreeNode>();

            if (processKind != DaemonProcessKind.GLOBAL_WARNINGS)
            {
                var collectUsagesStageProcess = daemonProcess?.GetStageProcess <CollectUsagesStageProcess>();
                if (collectUsagesStageProcess == null)
                {
                    return(result);
                }

                foreach (var usage in collectUsagesStageProcess.GetDeclaredElementUsages(declaredElement)
                         .Where(container.Contains))
                {
                    result.Add(usage);
                }

                return(result);
            }

            var finder = declaredElement.GetPsiServices().Finder;

            foreach (var reference in finder.FindAllReferences(declaredElement))
            {
                result.Add(reference.GetTreeNode());
            }

            return(result);
        }
示例#2
0
        public Action <ITextControl> ExecutePsiTransaction(ICSharpContextActionDataProvider dataProvider, ISolution solution, IClassLikeDeclaration classDeclaration, IEnumerable <IInterface> interfaces)
        {
            IInterface[] interfacesArray = interfaces.ToArray();
            IInterface   firstInterface  = interfacesArray[0];
            string       typeParameters  = firstInterface.TypeParameters.AggregateString(",", (builder, parameter) => builder.Append(parameter.ShortName));

            if (firstInterface.TypeParameters.Count != 0)
            {
                typeParameters = "<" + typeParameters + ">";
            }
            string className = classDeclaration.DeclaredName;

            classDeclaration.AddClassMemberDeclaration((IClassMemberDeclaration)dataProvider.ElementFactory.CreateTypeMemberDeclaration($"private {className}(){{}}"));

            IClassLikeDeclaration builderClass = BuildMethod(dataProvider, interfacesArray, className, typeParameters);

            ProcessInterface(dataProvider, classDeclaration, interfacesArray, builderClass);

            classDeclaration.AddClassMemberDeclaration(builderClass);

            return(textControl =>
            {
                IntentionTemplateUtil.ExecuteTemplate(solution, textControl, DocumentRange.InvalidRange);
            });
        }
示例#3
0
        public int GetScriptUsagesCount(IClassLikeDeclaration classLikeDeclaration, out bool estimatedResult)
        {
            myShellLocks.AssertReadAccessAllowed();

            // TODO : prefabs
            estimatedResult = false;

            var sourceFile = classLikeDeclaration.GetSourceFile();

            if (sourceFile == null)
            {
                return(0);
            }

            var declaredElement = classLikeDeclaration.DeclaredElement;

            if (declaredElement == null)
            {
                return(0);
            }

            var guid = AssetUtils.GetGuidFor(myMetaFileGuidCache, declaredElement);

            if (guid == null)
            {
                return(0);
            }

            return(myUsagesCount.GetCount(guid.Value));
        }
        /// <summary>
        /// Return "the only" invariant method with "ObjectInvariant" name.
        /// </summary>
        public static IMethodDeclaration GetInvariantMethod(this IClassLikeDeclaration classDeclaration)
        {
            Contract.Requires(classDeclaration != null);

            return(classDeclaration.MethodDeclarations
                   .FirstOrDefault(mi => mi.DeclaredName == InvariantUtils.InvariantMethodName));
        }
示例#5
0
        public override bool IsAvailable(IUserDataHolder cache)
        {
            var testProjectProvider = ComponentResolver.GetComponent <ITestProjectProvider>(_dataProvider);

            _parameterProvider = ComponentResolver.GetComponent <IParameterProvider>(_dataProvider);
            _selectedElement   = _dataProvider.GetSelectedElement <IObjectCreationExpression>(false, false);
            _block             = _dataProvider.GetSelectedElement <IBlock>();
            _classBody         = _dataProvider.GetSelectedElement <IClassBody>();
            _classDeclaration  = _classBody?.GetContainingTypeDeclaration() as IClassLikeDeclaration;

            if (_classDeclaration == null || _block == null || _selectedElement == null)
            {
                return(false);
            }

            if (!(_selectedElement.TypeReference?.Resolve().DeclaredElement is IClass c))
            {
                return(false);
            }

            _parameterNumber = _selectedElement.ArgumentList.Arguments.Count(x => x.Kind != ParameterKind.UNKNOWN);
            _constructor     = c.Constructors.ToArray().FirstOrDefault(x => !x.IsParameterless && x.Parameters.Count > _parameterNumber);
            if (_constructor == null)
            {
                return(false);
            }

            return(testProjectProvider.IsTestProject(_dataProvider.PsiModule));
        }
示例#6
0
        private static bool isTypeParameter(ICSharpTypeMemberDeclaration declaration, string word)
        {
            IMethodDeclaration method = declaration as IMethodDeclaration;
            if (method != null)
            {
                foreach (ITypeParameterOfMethodDeclaration decl in method.TypeParameterDeclarations)
                {
                    if (decl.DeclaredName == word)
                    {
                        return true;
                    }
                }
            }

            ICSharpTypeDeclaration containingType = declaration.GetContainingTypeDeclaration();
            if (containingType != null)
            {
                IClassLikeDeclaration classDecl = containingType as IClassLikeDeclaration;
                if (classDecl != null)
                {
                    foreach (ITypeParameterOfTypeDeclaration decl in classDecl.TypeParameters)
                    {
                        if (decl.DeclaredName == word)
                        {
                            return true;
                        }
                    }
                }
            }
            return false;
        }
 FieldContractInfo([NotNull] IFieldDeclaration declaration, [NotNull] IClassLikeDeclaration classLikeDeclaration, [NotNull] IType type) : base(
         ContractKind.Invariant,
         type)
 {
     this.declaration          = declaration;
     this.classLikeDeclaration = classLikeDeclaration;
 }
示例#8
0
        protected ITreeNode GetTypeDeclarationIdentifierNode(IType type)
        {
            ITypeElement          typeElement = type.GetTypeElement();
            IClassLikeDeclaration declaration = typeElement?.GetSingleDeclaration <IClassLikeDeclaration>();

            return(declaration?.NameIdentifier);
        }
        /// <summary>
        /// Return all invariant assertions (like Contract.Invariant(Prop != null)) for
        /// the specified <paramref name="classLikeDeclaration"/>.
        /// </summary>
        public static IEnumerable <ContractInvariant> GetInvariants(this IClassLikeDeclaration classLikeDeclaration)
        {
            Contract.Requires(classLikeDeclaration != null);
            Contract.Ensures(Contract.Result <IEnumerable <ContractInvariant> >() != null);

            return(classLikeDeclaration.GetInvariantMethods().SelectMany(GetInvariants));
        }
        public static IClassDeclaration GetContractClassDeclaration(this IClassLikeDeclaration classLikeDeclaration)
        {
            Contract.Requires(classLikeDeclaration != null);
            Contract.Requires(classLikeDeclaration.DeclaredElement != null);

            var contractClassAttributeType     = new ClrTypeName(typeof(ContractClassAttribute).FullName);
            var contractClassAttributeInstance =
                classLikeDeclaration.DeclaredElement.GetAttributeInstances(contractClassAttributeType, true)
                .FirstOrDefault();

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

            Contract.Assert(contractClassAttributeInstance.PositionParameterCount == 1);

            return(contractClassAttributeInstance.PositionParameters()
                   .FirstOrDefault()
                   .With(x => x.TypeValue)
                   .With(x => x.GetScalarType())
                   .With(x => x.Resolve())
                   .With(x => x.DeclaredElement)
                   .With(x => x.GetDeclarations().FirstOrDefault())
                   .Return(x => x as IClassDeclaration));
        }
        private bool CheckPosition(CSharpCodeCompletionContext context, out IClassLikeDeclaration classDeclaration,
                                   out bool hasVisibilityModifier, out bool hasReturnType)
        {
            classDeclaration      = null;
            hasVisibilityModifier = false;
            hasReturnType         = false;

            // Make sure we're completing an identifier
            if (!(context.UnterminatedContext.TreeNode is ICSharpIdentifier identifier))
            {
                return(false);
            }

            // Make sure we're in the correct place for showing Unity event functions.
            if (!ShouldComplete(context.NodeInFile, identifier))
            {
                return(false);
            }

            // We know we're in a place where we can complete, so now configure what we
            // complete and what we display
            hasReturnType         = HasExistingReturnType(identifier, out var typeUsage);
            hasVisibilityModifier = HasExisitingVisibilityModifier(typeUsage);
            classDeclaration      = GetClassDeclaration(context.NodeInFile);

            return(true);
        }
        public int GetUsagesCount(IClassLikeDeclaration classLikeDeclaration, out bool estimatedResult)
        {
            myShellLocks.AssertReadAccessAllowed();

            // TODO : prefabs
            estimatedResult = false;

            var sourceFile = classLikeDeclaration.GetSourceFile();

            if (sourceFile == null)
            {
                return(0);
            }

            var declaredElement = classLikeDeclaration.DeclaredElement;

            if (declaredElement == null)
            {
                return(0);
            }

            var guid = GetGuidFor(declaredElement);

            return(myAssetUsages.GetOrEmpty(guid).Count);
        }
示例#13
0
        private static ILookupItem CreateMethodItem(CSharpCodeCompletionContext context, UnityMessage message,
                                                    IClassLikeDeclaration declaration)
        {
            if (CSharpLanguage.Instance == null)
            {
                return(null);
            }

            var method = message.CreateDeclaration(CSharpElementFactory.GetInstance(declaration), declaration);

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

            var instance            = new DeclaredElementInstance(method.DeclaredElement);
            var declaredElementInfo = new DeclaredElementInfo(method.DeclaredName, instance, CSharpLanguage.Instance,
                                                              context.BasicContext.LookupItemsOwner, context, context.BasicContext);

            return(LookupItemFactory.CreateLookupItem(declaredElementInfo).
                   WithPresentation(
                       _ => new GenerateMemberPresentation(declaredElementInfo, PresenterStyles.DefaultPresenterStyle)).
                   WithBehavior(_ =>
            {
                var behavior = new UnityMessageBehavior(declaredElementInfo, message);
                behavior.InitializeRanges(context.CompletionRanges, context.BasicContext);
                return behavior;
            }).
                   WithMatcher(_ => new DeclaredElementMatcher(declaredElementInfo, context.BasicContext.IdentifierMatchingStyle)));
        }
        public static IEnumerable <OverridableMemberInstance> GetOverridenMembers(
            this IClassLikeDeclaration classLikeDeclaration)
        {
            Contract.Requires(classLikeDeclaration != null);
            Contract.Ensures(Contract.Result <IEnumerable <OverridableMemberInstance> >() != null);

            var alreadyOverriden = new List <OverridableMemberInstance>();

            foreach (IOverridableMember member in classLikeDeclaration.DeclaredElement.GetMembers().OfType <IOverridableMember>())
            {
                if (member.IsExplicitImplementation)
                {
                    foreach (IExplicitImplementation implementation in member.ExplicitImplementations)
                    {
                        OverridableMemberInstance element = implementation.Resolve();
                        if (element != null)
                        {
                            alreadyOverriden.Add(element);
                        }
                    }
                }
                else if (member.IsOverride)
                {
                    foreach (OverridableMemberInstance isntance in new OverridableMemberInstance(member).GetImmediateOverride())
                    {
                        alreadyOverriden.Add(isntance);
                    }
                }
            }

            return(alreadyOverriden);
        }
        private static ILookupItem CreateMethodItem(CSharpCodeCompletionContext context, UnityEventFunction eventFunction,
                                                    IClassLikeDeclaration declaration)
        {
            if (CSharpLanguage.Instance == null)
            {
                return(null);
            }

            var method = eventFunction.CreateDeclaration(CSharpElementFactory.GetInstance(declaration), declaration);

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

            var instance = new DeclaredElementInstance(method.DeclaredElement);

            var declaredElementInfo = new DeclaredElementInfo(method.DeclaredName, instance, CSharpLanguage.Instance,
                                                              context.BasicContext.LookupItemsOwner, context)
            {
                Ranges = context.CompletionRanges
            };

            var withMatcher = LookupItemFactory.CreateLookupItem(declaredElementInfo).
                              WithPresentation(_ => new GenerateMemberPresentation(declaredElementInfo, PresenterStyles.DefaultPresenterStyle)).
                              WithBehavior(_ => new UnityEventFunctionBehavior(declaredElementInfo, eventFunction)).
                              WithMatcher(_ => new DeclaredElementMatcher(declaredElementInfo, context.BasicContext.IdentifierMatchingStyle));

            return(withMatcher);
        }
        /// <summary>
        /// Return all methods, marked with <see cref="ContractInvariantMethodAttribute"/>.
        /// </summary>
        /// <remarks>
        /// Any class (or struct) could have any number of "invariant methods".
        /// </remarks>
        public static IEnumerable <IMethodDeclaration> GetInvariantMethods(this IClassLikeDeclaration classDeclaration)
        {
            Contract.Requires(classDeclaration != null);
            Contract.Ensures(Contract.Result <IEnumerable <IMethodDeclaration> >() != null);

            // Class could have any number of invariant methods!
            return(classDeclaration.MethodDeclarations.Where(IsObjectInvariantMethod));
        }
        public sealed override bool IsAvailable()
        {
            this.Class = this.DataProvider.SelectedElement.Parent as IClassLikeDeclaration;

            return
                (this.Class != null &&
                 this.DataProvider.SelectedElement == this.Class.NameIdentifier &&
                 IsAvailableCore());
        }
        public override void Populate(CSharpGeneratorContext context)
        {
            // use context.ProvidedElements.AddRange to add new
            // generator elements (e.g., GeneratorDeclaredElement<T>)
            IClassLikeDeclaration typeDeclaration = context.ClassDeclaration;
            ITypeElement          typeElement     = typeDeclaration.DeclaredElement;

            ListHandler.Initialize(context);
            MethodGeneratorBase.Initialize(context);
            GetBytesMethodGenerator.Initialize(context);
            SetBytesMethodGenerator.Initialize(context);

            if (typeElement is IClass || typeElement is IStruct)
            {
                var ctx = new TypeHandlingContext(context);

                foreach (ITypeMember member in typeElement.GetMembers())
                {
                    ITypeOwner owner = null;

                    var field = member as IField;
                    if (field != null)
                    {
                        if (field.GetAccessRights() != AccessRights.PRIVATE &&
                            !field.IsConstant &&
                            !field.IsReadonly &&
                            !field.IsStatic)
                        {
                            owner = field;
                        }
                    }

                    var property = member as IProperty;
                    if (property != null)
                    {
                        if (property.IsReadable &&
                            property.IsWritable &&
                            !property.IsStatic)
                        {
                            owner = property;
                        }
                    }

                    if (owner != null)
                    {
                        ctx.Resolve(owner);

                        if (TypeHandlers.All.Any(h => h.CanHandle(ctx)))
                        {
                            context.ProvidedElements.Add(new GeneratorDeclaredElement <ITypeOwner>(owner));
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Return list of members from the <paramref name="declaration"/>, that overridable from its base class 
        /// (<paramref name="baseDeclaration"/>).
        /// </summary>
        public static List<OverridableMemberInstance> GetMissingMembersOf(
            this IClassLikeDeclaration declaration,
            IClassLikeDeclaration baseDeclaration)
        {
            Contract.Requires(declaration != null);
            Contract.Requires(declaration.DeclaredElement != null);
            Contract.Requires(baseDeclaration != null);
            Contract.Requires(baseDeclaration.DeclaredElement != null);

            Contract.Ensures(Contract.Result<List<OverridableMemberInstance>>() != null);

            return GetMissingMembersOf(declaration, baseDeclaration.DeclaredElement.GetClrName());        }
        public ClassLikeDeclarationCompiler(IClassLikeDeclaration classLikeDeclaration, AbstractILCompilerParams myParams) : base(myParams)
        {
            myClassLikeDeclaration = classLikeDeclaration;

            var newClass = myParams.CreateClass(myClassLikeDeclaration.DeclaredElement.GetClrName().FullName);

            if (myClassLikeDeclaration is IClassDeclaration classDeclaration)
            {
                var baseClass = new ClassId(classDeclaration.DeclaredElement.GetBaseClassType().GetClrName().FullName);
                newClass.BaseClass = baseClass;
            }
        }
示例#21
0
        public static IConstructorDeclaration GetFirstConstructorWithBody(IClassLikeDeclaration node)
        {
            return(NodeArrayExtensions.ForEachUntil(node.Members, member =>
            {
                if (member.Kind == SyntaxKind.Constructor && NodeIsPresent(member.Cast <ConstructorDeclaration>().Body))
                {
                    return member.Cast <ConstructorDeclaration>();
                }

                return (IConstructorDeclaration)null;
            }));
        }
        private InvariantAvailability(ICSharpContextActionDataProvider provider,
            FieldOrPropertyDeclaration selectedElement)
        {
            Contract.Requires(provider != null);
            
            _classDeclaration = provider.GetSelectedElement<IClassLikeDeclaration>(true, true);
            _selectedElement = selectedElement;

            IsAvailable = AnalyzeAvailability();
            if (IsAvailable)
                SelectedMemberName = _selectedElement.Name;
        }
        public static bool HasAttribute(this IClassLikeDeclaration classLikeDeclaration, Type attributeType)
        {
            Contract.Requires(classLikeDeclaration != null);
            Contract.Requires(classLikeDeclaration.DeclaredElement != null);
            Contract.Requires(attributeType != null);
            Contract.Requires(attributeType.IsAttribute());

            var clrAttribute = new ClrTypeName(attributeType.FullName);

            return(classLikeDeclaration.DeclaredElement.HasAttributeInstance(
                       new ClrTypeName(attributeType.FullName), inherit: true));
        }
        /// <summary>
        /// Return list of members from the <paramref name="declaration"/>, that overridable from its base class
        /// (<paramref name="baseDeclaration"/>).
        /// </summary>
        public static List <OverridableMemberInstance> GetMissingMembersOf(
            this IClassLikeDeclaration declaration,
            IClassLikeDeclaration baseDeclaration)
        {
            Contract.Requires(declaration != null);
            Contract.Requires(declaration.DeclaredElement != null);
            Contract.Requires(baseDeclaration != null);
            Contract.Requires(baseDeclaration.DeclaredElement != null);

            Contract.Ensures(Contract.Result <List <OverridableMemberInstance> >() != null);

            return(GetMissingMembersOf(declaration, baseDeclaration.DeclaredElement.GetClrName()));
        }
示例#25
0
        private void ProcessInterface(ICSharpContextActionDataProvider dataProvider, IClassLikeDeclaration classDeclaration, ICollection <IInterface> interfacesArray, IClassLikeDeclaration builderClass)
        {
            if (interfacesArray.IsEmpty())
            {
                return;
            }

            foreach (IInterface theInterface in interfacesArray)
            {
                ProcessInterface(dataProvider, classDeclaration, theInterface.GetSuperTypes().Select(x => x.GetTypeElement()).OfType <IInterface>().ToArray(), builderClass);

                foreach (IEvent theEvent in theInterface.Events)
                {
                    string eventShortName           = theEvent.ShortName;
                    string eventTypePresentableName = theEvent.Type.GetPresentableName(Languages.Instance.GetLanguageByName("CSHARP"));
                    classDeclaration.AddClassMemberDeclaration((IClassMemberDeclaration)dataProvider.ElementFactory.CreateTypeMemberDeclaration($"public event {eventTypePresentableName} _{eventShortName};"));
                    if (theEvent.Type.GetPresentableName(Languages.Instance.GetLanguageByName("CSHARP")) == "EventHandler")
                    {
                        classDeclaration.AddClassMemberDeclaration((IClassMemberDeclaration)dataProvider.ElementFactory.CreateTypeMemberDeclaration($"public void Trigger{eventShortName}() => _{eventShortName}.Invoke(this, EventArgs.Empty);"));
                    }
                    else
                    {
                        //type.GetScalarType().GetTypeElement().TypeParameters[0]
                        //ITypeParameter x = theEvent.Type.GetScalarType().GetTypeElement().TypeParameters[0];
                        //DeclaredTypeBase con = theEvent.Type as DeclaredTypeFromReferenceName;
                        //classDeclaration.AddClassMemberDeclaration((IClassMemberDeclaration)dataProvider.ElementFactory.CreateTypeMemberDeclaration($"public void Trigger{eventShortName}" +
                        //$"({x.ShortName} val) => _{eventShortName}.Invoke(val);"));
                    }
                }

                foreach (IMethod node in theInterface.Methods)
                {
                    ISignature methodSig = new MockMethod(node, theInterface);
                    classDeclaration.AddClassMemberDeclaration((IClassMemberDeclaration)dataProvider.ElementFactory.CreateTypeMemberDeclaration(methodSig.Signature()));
                    classDeclaration.AddClassMemberDeclaration((IClassMemberDeclaration)dataProvider.ElementFactory.CreateTypeMemberDeclaration(MockClassVariable(node, theInterface).Declaration()));
                }

                foreach (IMethod node in theInterface.Methods)
                {
                    builderClass.AddClassMemberDeclaration((IClassMemberDeclaration)dataProvider.ElementFactory.CreateTypeMemberDeclaration(MockClassVariable(node, theInterface).BuilderDeclaration()));
                    builderClass.AddClassMemberDeclaration((IClassMemberDeclaration)dataProvider.ElementFactory.CreateTypeMemberDeclaration(MockBuilderMethod(node, theInterface).Typed()));
                    builderClass.AddClassMemberDeclaration((IClassMemberDeclaration)dataProvider.ElementFactory.CreateTypeMemberDeclaration(MockBuilderMethod(node, theInterface).Lambdad()));
                }

                foreach (IMethod node in theInterface.Methods)
                {
                    ISignature2 methodSig = MockAssertMethod(node, theInterface);
                    methodSig.Signature(classDeclaration, dataProvider.ElementFactory);
                }
            }
        }
        private static void AddDeclaration([NotNull] IClassLikeDeclaration anchor, [NotNull] IClassLikeDeclaration declaration)
        {
            var holderDeclaration = (ICSharpTypeAndNamespaceHolderDeclaration)CSharpNamespaceDeclarationNavigator.GetByTypeDeclaration(anchor)
                                    ?? CSharpFileNavigator.GetByTypeDeclaration(anchor);

            if (holderDeclaration == null)
            {
                anchor.AddClassMemberDeclaration(declaration);
            }
            else
            {
                holderDeclaration.AddTypeDeclarationAfter(declaration, anchor);
            }
        }
示例#27
0
        private InvariantAvailability(ICSharpContextActionDataProvider provider,
                                      FieldOrPropertyDeclaration selectedElement)
        {
            Contract.Requires(provider != null);

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

            IsAvailable = AnalyzeAvailability();
            if (IsAvailable)
            {
                SelectedMemberName = _selectedElement.Name;
            }
        }
        public static bool Overrides(this IClassLikeDeclaration classLikeDeclaration,
                                     ICSharpFunctionDeclaration baseFunctionDeclaration)
        {
            Contract.Requires(classLikeDeclaration != null);
            Contract.Requires(baseFunctionDeclaration != null);

            Func <IMethodDeclaration, bool> isOverridesCurrentFunction =
                md => md.DeclaredElement.GetAllSuperMembers()
                .Any(overridable => overridable.Member.Equals(baseFunctionDeclaration.DeclaredElement));

            return(classLikeDeclaration
                   .With(x => x.Body)
                   .Return(x => x.Methods.FirstOrDefault(isOverridesCurrentFunction)) != null);
        }
        private void AddScriptUsagesHighlighting([NotNull] IHighlightingConsumer consumer,
                                                 [NotNull] IClassLikeDeclaration declaration,
                                                 [NotNull] IconModel iconModel)
        {
            var count           = 0;
            var estimatedResult = false;

            foreach (var scriptUsagesContainer in myScriptsUsagesElementContainers)
            {
                count          += scriptUsagesContainer.GetScriptUsagesCount(declaration, out var result);
                estimatedResult = estimatedResult || result;
            }
            myUsagesCodeVisionProvider.AddHighlighting(consumer, declaration, declaration.DeclaredElement, count,
                                                       "Click to view usages in assets", "Assets usages", estimatedResult, iconModel);
        }
示例#30
0
        private static IClassLikeDeclaration BuildMethod(ICSharpContextActionDataProvider dataProvider, ICollection <IInterface> interfacesArray, string className, string typeParameters)
        {
            IClassLikeDeclaration builderClass = (IClassLikeDeclaration)dataProvider.ElementFactory.CreateTypeMemberDeclaration("public sealed class Builder {}");
            //List<IInterface> interfaces = theInterface.GetSuperTypes().Select(x => x.GetTypeElement()).OfType<IInterface>().ToList();

            string allNodes = AllNodes(interfacesArray.ToArray());

            allNodes = allNodes.Replace("," + Environment.NewLine + ",", ",");
            builderClass.AddClassMemberDeclaration((IClassMemberDeclaration)dataProvider.ElementFactory.CreateTypeMemberDeclaration(
                                                       $@"public {className}{typeParameters} Build(){{
    return new {className}{typeParameters}{{
            {allNodes}
    }};
}}"));
            return(builderClass);
        }
        private IAttribute CreateContractClassForAttribute(IClassLikeDeclaration contractClassFor)
        {
            var          declaredType = _addContractForAvailability.DeclaredType.GetTypeElement();
            ITypeElement type         = TypeFactory.CreateTypeByCLRName(
                typeof(ContractClassForAttribute).FullName, _provider.PsiModule).GetTypeElement();

            var expression = _factory.CreateExpression("typeof($0)", declaredType);

            var attribute = _factory.CreateAttribute(type);

            attribute.AddArgumentAfter(
                _factory.CreateArgument(ParameterKind.VALUE, expression),
                null);

            return(attribute);
        }
示例#32
0
        public InvariantActionExecutor(InvariantAvailability invariantAvailability,
                                       ICSharpContextActionDataProvider provider)
            : base(provider)
        {
            Contract.Requires(invariantAvailability != null);
            Contract.Requires(provider != null);
            Contract.Requires(invariantAvailability.IsAvailable);

            _invariantAvailability = invariantAvailability;
            _provider = provider;
            // TODO: look at this class CSharpStatementNavigator

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

            Contract.Assert(provider.SelectedElement != null);
        }
        public InvariantActionExecutor(InvariantAvailability invariantAvailability,
            ICSharpContextActionDataProvider provider)
            : base(provider)
        {
            Contract.Requires(invariantAvailability != null);
            Contract.Requires(provider != null);
            Contract.Requires(invariantAvailability.IsAvailable);

            _invariantAvailability = invariantAvailability;
            _provider = provider;
            // TODO: look at this class CSharpStatementNavigator

            _classDeclaration = provider.GetSelectedElement<IClassLikeDeclaration>(true, true);
            
            Contract.Assert(provider.SelectedElement != null);
        }
        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();

        }
 FieldContractInfo([NotNull] IFieldDeclaration declaration, [NotNull] IClassLikeDeclaration classLikeDeclaration, [NotNull] IType type)
     : base(ContractKind.Invariant, type)
 {
     this.declaration = declaration;
     this.classLikeDeclaration = classLikeDeclaration;
 }
        private IAttribute CreateContractClassForAttribute(IClassLikeDeclaration contractClassFor)
        {
            var declaredType = _addContractForAvailability.DeclaredType.GetTypeElement();
            ITypeElement type = TypeFactory.CreateTypeByCLRName(
                typeof(ContractClassForAttribute).FullName,
                _provider.PsiModule, _currentFile.GetResolveContext()).GetTypeElement();

            var expression = _factory.CreateExpression("typeof($0)", declaredType);

            var attribute = _factory.CreateAttribute(type);

            attribute.AddArgumentAfter(
                _factory.CreateArgument(ParameterKind.VALUE, expression),
                null);

            return attribute;
        }
    /// <summary>Gets the modifier.</summary>
    /// <param name="treeNode">The element.</param>
    /// <param name="classDeclaration">The class declaration.</param>
    /// <returns>Returns the modifier.</returns>
    private static string GetModifier(ITreeNode treeNode, IClassLikeDeclaration classDeclaration)
    {
      ITypeMemberDeclaration classMember = null;

      var caret = treeNode.GetTreeStartOffset();

      foreach (var typeMemberDeclaration in classDeclaration.MemberDeclarations)
      {
        if (typeMemberDeclaration.GetTreeStartOffset() > caret)
        {
          break;
        }

        classMember = typeMemberDeclaration;
      }

      var modifier = "public";

      var accessRightsOwner = classMember as IAccessRightsOwner;
      if (accessRightsOwner != null)
      {
        var rights = accessRightsOwner.GetAccessRights();
        switch (rights)
        {
          case AccessRights.PUBLIC:
            modifier = "public";
            break;
          case AccessRights.INTERNAL:
            modifier = "internal";
            break;
          case AccessRights.PROTECTED:
            modifier = "protected";
            break;
          case AccessRights.PROTECTED_OR_INTERNAL:
            modifier = "protected";
            break;
          case AccessRights.PROTECTED_AND_INTERNAL:
            modifier = "protected internal";
            break;
          case AccessRights.PRIVATE:
            modifier = "private";
            break;
          case AccessRights.NONE:
            modifier = string.Empty;
            break;
        }
      }

      var modifiersOwner = classMember as IModifiersOwner;
      if (modifiersOwner != null)
      {
        if (modifiersOwner.IsStatic)
        {
          if (!string.IsNullOrEmpty(modifier))
          {
            modifier += ' ';
          }

          modifier += "static";
        }
      }

      if (!string.IsNullOrEmpty(modifier))
      {
        modifier += ' ';
      }

      return modifier;
    }