public override void Rename(IRenameRefactoring executer, IProgressIndicator pi, bool hasConflictsWithDeclarations,
                                    IRefactoringDriver driver)
        {
            if (!myModel.ShouldAddFormerlySerializedAs)
            {
                return;
            }

            var fieldDeclaration = GetFieldDeclaration(myPointer.FindDeclaredElement() as IField);

            if (fieldDeclaration == null)
            {
                return;
            }

            RemoveExistingAttributesWithNewName(fieldDeclaration);

            if (HasExistingFormerlySerializedAsAttribute(fieldDeclaration))
            {
                // Make sure textual occurrence rename doesn't rename the existing attribute parameter
                RemoveFromTextualOccurrences(executer, fieldDeclaration);
                return;
            }

            var attribute = CreateFormerlySerializedAsAttribute(fieldDeclaration.GetPsiModule());

            if (attribute != null)
            {
                fieldDeclaration.AddAttributeAfter(attribute, null);
            }
        }
        public override bool Navigate(ISolution solution, IDeclaredElementPointer <IDeclaredElement> pointer, LocalReference location)
        {
            if (!solution.GetComponent <BackendUnityHost>().IsConnectionEstablished())
            {
                var textControl = solution.GetComponent <TextControlManager>().LastFocusedTextControl.Value;
                if (textControl == null)
                {
                    return(true);
                }

                var tooltipManager = solution.GetComponent <ITooltipManager>();
                tooltipManager.Show("Start the Unity Editor to view results",
                                    new PopupWindowContextSource(lifetime =>
                                                                 textControl.PopupWindowContextFactory.CreatePopupWindowContext(lifetime)));
                return(true);
            }

            var findRequestCreator = solution.GetComponent <UnityEditorFindUsageResultCreator>();
            var declaredElement    = pointer.FindDeclaredElement();

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

            findRequestCreator.CreateRequestToUnity(declaredElement, location, true);
            return(false);
        }
        public override void Rename(IRenameRefactoring executer, IProgressIndicator pi, bool hasConflictsWithDeclarations,
                                    IRefactoringDriver driver)
        {
            // Rename the "declaration"
            var declaredElement  = myPointer.FindDeclaredElement();
            var originalTreeNode = declaredElement?.GetTreeNode();

            if (originalTreeNode == null)
            {
                return;
            }

            var originalRange     = originalTreeNode.GetDocumentRange();
            var factory           = JavaScriptElementFactory.GetInstance(originalTreeNode);
            var literalExpression = factory.CreateExpression("\"$0\"", NewName);
            var newExpression     = originalTreeNode.ReplaceBy(literalExpression);

            RemoveFromTextualOccurrences(executer, originalRange);

            var references = executer.Workflow.GetElementReferences(declaredElement);

            if (!Enumerable.Any(references))
            {
                return;
            }

            pi.Start(references.Count);

            // Create a new declared element (other implementations don't appear to cache this, either)
            var element = new AsmDefNameDeclaredElement(declaredElement.GetJsServices(), NewName,
                                                        declaredElement.SourceFile, newExpression.GetTreeStartOffset().Offset);

            // Rename/bind the references
            foreach (var pair in LanguageUtil.SortReferences(references.Where(r => r.IsValid())))
            {
                foreach (var sortedReference in LanguageUtil.GetSortedReferences(pair.Value))
                {
                    InterruptableActivityCookie.CheckAndThrow(pi);

                    var referenceRange = sortedReference.GetDocumentRange();

                    if (sortedReference.IsValid())
                    {
                        sortedReference.BindTo(element);
                    }

                    RemoveFromTextualOccurrences(executer, referenceRange);

                    pi.Advance();
                }
            }

            element.GetPsiServices().Caches.Update();
            myNewPointer = element.CreateElementPointer();
        }
Exemple #4
0
        public UnityAnimatorScriptOccurence([NotNull] IPsiSourceFile sourceFile,
                                            [NotNull] IDeclaredElementPointer <IDeclaredElement> declaredElement,
                                            [NotNull] IAnimatorScriptUsage usage)
            : base(sourceFile, declaredElement, usage.Location, false)
        {
            Usage = usage;
            var container = GetSolution()
                            .NotNull("occurrence.GetSolution() != null")
                            .GetComponent <AnimatorScriptUsagesElementContainer>();

            Container = container;
            var element = declaredElement.FindDeclaredElement();

            if (element is null)
            {
                return;
            }
            var location = Usage.Location;

            container.GetElementsNames(location, element, out _, out var isStateMachine);
            IconId = isStateMachine
                ? UnityObjectTypeThemedIcons.UsageAnimatorStateMachine.Id
                : UnityObjectTypeThemedIcons.UsageAnimatorState.Id;
        }
        public override void Rename(IRenameRefactoring executer, IProgressIndicator pi, bool hasConflictsWithDeclarations, IRefactoringDriver driver)
        {
            BuildDeclarations();

            //Logger.Assert(myDeclarations.Count > 0, "myDeclarations.Count > 0");

            IDeclaredElement declaredElement = myOriginalElementPointer.FindDeclaredElement();

            if (declaredElement == null)
            {
                return;
            }

            IPsiServices psiServices = declaredElement.GetPsiServices();

            IList <IReference> primaryReferences = executer.Workflow.GetElementReferences(PrimaryDeclaredElement);
            List <Pair <IDeclaredElement, IList <IReference> > > secondaryElementWithReferences = SecondaryDeclaredElements.Select(x => Pair.Of(x, executer.Workflow.GetElementReferences(x))).ToList();

            pi.Start(myDeclarations.Count + primaryReferences.Count);

            foreach (IDeclaration declaration in myDeclarations)
            {
                InterruptableActivityCookie.CheckAndThrow(pi);
                declaration.SetName(myNewName);
                pi.Advance();
            }

            psiServices.Caches.Update();

            IDeclaredElement newDeclaredElement;

            if (myDeclarations.Count > 0)
            {
                newDeclaredElement = myDeclarations[0].DeclaredElement;
            }
            else
            {
                if (myElement is RoleDeclaredElement)
                {
                    newDeclaredElement = myElement;
                    ((RoleDeclaredElement)myElement).ChangeName = true;
                    ((RoleDeclaredElement)myElement).NewName    = NewName;
                    ((RoleDeclaredElement)newDeclaredElement).SetName(NewName);
                }
                else
                {
                    newDeclaredElement = null;
                }
            }
            Assertion.Assert(newDeclaredElement != null, "The condition (newDeclaredElement != null) is false.");

            myNewElementPointer = newDeclaredElement.CreateElementPointer();
            Assertion.Assert(newDeclaredElement.IsValid(), "myNewDeclaredElement.IsValid()");


            myNewReferences.Clear();
            OneToSetMap <PsiLanguageType, IReference> references = LanguageUtil.SortReferences(primaryReferences.Where(x => x.IsValid()));
            IList <IReference> referencesToRename = new List <IReference>();

            foreach (var pair in references)
            {
                List <IReference> sortedReferences = pair.Value.ToList();//LanguageUtil.GetSortedReferences(pair.Value);
                foreach (IReference reference in sortedReferences)
                {
                    IReference oldReferenceForConflict = reference;
                    InterruptableActivityCookie.CheckAndThrow(pi);
                    if (reference.IsValid()) // reference may invalidate during additional reference processing
                    {
                        RenameHelperBase        rename     = executer.Workflow.LanguageSpecific[reference.GetTreeNode().Language];
                        IReference              reference1 = rename.TransformProjectedInitializer(reference);
                        DeclaredElementInstance subst      = GetSubst(newDeclaredElement, executer);
                        IReference              newReference;
                        if (subst != null)
                        {
                            if (subst.Substitution.Domain.IsEmpty())
                            {
                                newReference = reference1.BindTo(subst.Element);
                            }
                            else
                            {
                                newReference = reference1.BindTo(subst.Element, subst.Substitution);
                            }
                        }
                        else
                        {
                            newReference = reference1.BindTo(newDeclaredElement);
                        }
                        if (!(newReference is IImplicitReference))
                        {
                            IDeclaredElement element = newReference.Resolve().DeclaredElement;
                            if (!hasConflictsWithDeclarations && !myDoNotShowBindingConflicts && (element == null || !element.Equals(newDeclaredElement)) && !rename.IsAlias(newDeclaredElement))
                            {
                                driver.AddLateConflict(() => new Conflict(newReference.GetTreeNode().GetSolution(), "Usage {0} can not be updated correctly.", ConflictSeverity.Error, oldReferenceForConflict), "not bound");
                            }
                            referencesToRename.Add(newReference);
                        }
                        myNewReferences.Insert(0, newReference);
                        rename.AdditionalReferenceProcessing(newDeclaredElement, newReference, myNewReferences);
                    }

                    pi.Advance();
                }
            }

            foreach (var pair in secondaryElementWithReferences)
            {
                IDeclaredElement   element             = pair.First;
                IList <IReference> secondaryReferences = pair.Second;
                foreach (IReference reference in secondaryReferences)
                {
                    InterruptableActivityCookie.CheckAndThrow(pi);
                    if (reference.IsValid())
                    {
                        reference.BindTo(element);
                    }
                }
            }

            if (myElement is RoleDeclaredElement)
            {
                ((RoleDeclaredElement)myElement).ChangeName = false;
                ((RoleDeclaredElement)myElement).SetName(NewName);
                foreach (IReference reference in referencesToRename)
                {
                    ((PsiRoleReference)reference).SetName(NewName);
                    reference.CurrentResolveResult = null;
                    ((PsiFile)((RoleDeclaredElement)myElement).File).ClearTables();
                }
            }
        }
Exemple #6
0
        public override bool Execute(IProgressIndicator progressIndicator)
        {
            var languageService = CSharpLanguage.Instance.LanguageService();

            if (languageService == null)
            {
                return(false);
            }
            var ctor = _ctor.FindDeclaredElement();

            if (ctor == null)
            {
                return(false);
            }
            var definingClass = _class.FindDeclaredElement();

            if (definingClass == null)
            {
                return(false);
            }
            var factory  = CSharpElementFactory.GetInstance(ctor.Module);
            var ctorDecl = ctor.GetDeclarations().FirstOrDefault();

            if (ctorDecl == null)
            {
                var typeDecl = definingClass.GetDeclarations().FirstOrDefault() as IClassLikeDeclaration;
                if (typeDecl == null)
                {
                    return(false);
                }
                var typeBody = typeDecl.Body;
                ctorDecl = factory.CreateTypeMemberDeclaration("public $0() {}", typeDecl.DeclaredName);
                if (typeBody.FirstChild == null)
                {
                    return(false);
                }

                ctorDecl = ModificationUtil.AddChildBefore(
                    typeBody,
                    typeBody.FirstChild.NextSibling,
                    ctorDecl).GetContainingNode <IConstructorDeclaration>(true);
            }
            if (ctorDecl == null)
            {
                return(false);
            }
            var type = CSharpTypeFactory.CreateType(_parameterType, ctorDecl);

            if (!type.IsResolved)
            {
                type = CSharpTypeFactory.CreateType(_parameterType, ctorDecl.GetPsiModule());
            }
            string recommendedName = null;

            if (!type.IsResolved)
            {
                var presentableName = type.GetPresentableName(CSharpLanguage.Instance);
                var indexOfGeneric  = presentableName.IndexOf('<');
                if (indexOfGeneric != -1)
                {
                    var interfaceName   = presentableName.Substring(1, indexOfGeneric - 1);
                    var genericArgument = presentableName.Substring(indexOfGeneric).Trim('<', '>');
                    recommendedName = type.GetPsiServices().Naming.Suggestion.GetDerivedName(
                        genericArgument + interfaceName,
                        NamedElementKinds.Parameters,
                        ScopeKind.Common,
                        CSharpLanguage.Instance,
                        new SuggestionOptions(),
                        ctorDecl.GetSourceFile());
                }
                var interfaceDecl = factory.CreateTypeMemberDeclaration("public interface IFoo {}");
                interfaceDecl.SetName(presentableName);
                languageService.CodeFormatter.Format(interfaceDecl, CodeFormatProfile.GENERATOR);
                var containingType = ctor.GetContainingType();
                if (containingType == null)
                {
                    return(false);
                }
                var containingTypeDecl = containingType.GetDeclarations().First();
                ModificationUtil.AddChildBefore(containingTypeDecl, interfaceDecl);
            }
            type = CSharpTypeFactory.CreateType(_parameterType, ctorDecl);
            if (recommendedName == null)
            {
                var suggestionOptions = new SuggestionOptions();
                recommendedName = type.GetPsiServices().Naming.Suggestion.GetDerivedName(
                    type.GetPresentableName(CSharpLanguage.Instance),
                    NamedElementKinds.Parameters,
                    ScopeKind.Common,
                    CSharpLanguage.Instance,
                    suggestionOptions,
                    ctorDecl.GetSourceFile());
            }
            var parametersOwner = ctorDecl as ICSharpParametersOwnerDeclaration;
            var references      = FindReferences(parametersOwner, progressIndicator);

            if (parametersOwner == null)
            {
                return(false);
            }
            parametersOwner.AddParameterDeclarationAfter(
                ParameterKind.VALUE, type, recommendedName,
                parametersOwner.ParameterDeclarations.LastOrDefault());

            foreach (var reference in references)
            {
                ChangeReference(reference, recommendedName, type);
            }

            return(true);
        }