Search in sources :

Example 16 with GrReferenceElement

use of org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement in project intellij-community by JetBrains.

the class GroovyReferenceCopyPasteProcessor method restoreReferences.

@Override
protected void restoreReferences(ReferenceData[] referenceData, GrReferenceElement[] refs) {
    for (int i = 0; i < refs.length; i++) {
        GrReferenceElement reference = refs[i];
        if (reference == null)
            continue;
        try {
            PsiManager manager = reference.getManager();
            ReferenceData refData = referenceData[i];
            PsiClass refClass = JavaPsiFacade.getInstance(manager.getProject()).findClass(refData.qClassName, reference.getResolveScope());
            if (refClass != null) {
                if (refData.staticMemberName == null) {
                    reference.bindToElement(refClass);
                } else {
                    LOG.assertTrue(reference instanceof GrReferenceExpression);
                    PsiMember member = findMember(refData, refClass);
                    if (member != null) {
                        ((GrReferenceExpression) reference).bindToElementViaStaticImport(member);
                    }
                }
            }
        } catch (IncorrectOperationException e) {
            LOG.error(e);
        }
    }
}
Also used : ReferenceData(com.intellij.codeInsight.editorActions.ReferenceData) IncorrectOperationException(com.intellij.util.IncorrectOperationException) GrReferenceElement(org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)

Example 17 with GrReferenceElement

use of org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement in project intellij-community by JetBrains.

the class GroovyReferenceCopyPasteProcessor method addReferenceData.

@Override
protected void addReferenceData(PsiFile file, int startOffset, PsiElement element, ArrayList<ReferenceData> to) {
    if (element instanceof GrReferenceElement) {
        if (((GrReferenceElement) element).getQualifier() == null) {
            final GroovyResolveResult resolveResult = ((GrReferenceElement) element).advancedResolve();
            final PsiElement refElement = resolveResult.getElement();
            if (refElement != null) {
                if (refElement instanceof PsiClass) {
                    if (refElement.getContainingFile() != element.getContainingFile()) {
                        final String qName = ((PsiClass) refElement).getQualifiedName();
                        if (qName != null) {
                            addReferenceData(element, to, startOffset, qName, null);
                        }
                    }
                } else if (resolveResult.getCurrentFileResolveContext() instanceof GrImportStatement && ((GrImportStatement) resolveResult.getCurrentFileResolveContext()).isStatic()) {
                    final String classQName = ((PsiMember) refElement).getContainingClass().getQualifiedName();
                    final String name = ((PsiNamedElement) refElement).getName();
                    if (classQName != null && name != null) {
                        addReferenceData(element, to, startOffset, classQName, name);
                    }
                }
            }
        }
    }
}
Also used : GroovyResolveResult(org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult) GrImportStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement) GrReferenceElement(org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement)

Example 18 with GrReferenceElement

use of org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement in project intellij-community by JetBrains.

the class CreateClassFix method createClassFixAction.

public static IntentionAction createClassFixAction(final GrReferenceElement refElement, GrCreateClassKind type) {
    return new CreateClassActionBase(type, refElement) {

        @Override
        protected void processIntention(@NotNull PsiElement element, @NotNull Project project, Editor editor) throws IncorrectOperationException {
            final PsiFile file = element.getContainingFile();
            if (!(file instanceof GroovyFileBase))
                return;
            GroovyFileBase groovyFile = (GroovyFileBase) file;
            PsiElement qualifier = myRefElement.getQualifier();
            if (qualifier == null || qualifier instanceof GrReferenceElement && ((GrReferenceElement) qualifier).resolve() instanceof PsiPackage) {
                createTopLevelClass(project, groovyFile);
            } else {
                createInnerClass(project, editor, qualifier);
            }
        }

        private void createInnerClass(Project project, final Editor editor, PsiElement qualifier) {
            PsiElement resolved = resolveQualifier(qualifier);
            if (!(resolved instanceof PsiClass))
                return;
            JVMElementFactory factory = JVMElementFactories.getFactory(resolved.getLanguage(), project);
            if (factory == null)
                return;
            String name = myRefElement.getReferenceName();
            PsiClass template = createTemplate(factory, name);
            if (template == null) {
                ApplicationManager.getApplication().invokeLater(() -> {
                    if (editor != null && editor.getComponent().isDisplayable()) {
                        HintManager.getInstance().showErrorHint(editor, GroovyIntentionsBundle.message("cannot.create.class"));
                    }
                });
                return;
            }
            if (!FileModificationService.getInstance().preparePsiElementForWrite(resolved))
                return;
            WriteAction.run(() -> {
                PsiClass added = (PsiClass) resolved.add(template);
                PsiModifierList modifierList = added.getModifierList();
                if (modifierList != null) {
                    modifierList.setModifierProperty(PsiModifier.STATIC, true);
                }
                IntentionUtils.positionCursor(project, added.getContainingFile(), added);
            });
        }

        @Nullable
        private PsiElement resolveQualifier(@NotNull PsiElement qualifier) {
            if (qualifier instanceof GrCodeReferenceElement) {
                return ((GrCodeReferenceElement) qualifier).resolve();
            } else if (qualifier instanceof GrExpression) {
                PsiType type = ((GrExpression) qualifier).getType();
                if (type instanceof PsiClassType) {
                    return ((PsiClassType) type).resolve();
                } else if (qualifier instanceof GrReferenceExpression) {
                    final PsiElement resolved = ((GrReferenceExpression) qualifier).resolve();
                    if (resolved instanceof PsiClass || resolved instanceof PsiPackage) {
                        return resolved;
                    }
                }
            }
            return null;
        }

        @Nullable
        private PsiClass createTemplate(JVMElementFactory factory, String name) {
            switch(getType()) {
                case ENUM:
                    return factory.createEnum(name);
                case TRAIT:
                    if (factory instanceof GroovyPsiElementFactory) {
                        return ((GroovyPsiElementFactory) factory).createTrait(name);
                    } else {
                        return null;
                    }
                case CLASS:
                    return factory.createClass(name);
                case INTERFACE:
                    return factory.createInterface(name);
                case ANNOTATION:
                    return factory.createAnnotationType(name);
                default:
                    return null;
            }
        }

        private void createTopLevelClass(@NotNull Project project, @NotNull GroovyFileBase file) {
            final String pack = getPackage(file);
            final PsiManager manager = PsiManager.getInstance(project);
            final String name = myRefElement.getReferenceName();
            assert name != null;
            final Module module = ModuleUtilCore.findModuleForPsiElement(file);
            PsiDirectory targetDirectory = getTargetDirectory(project, pack, name, module, getText());
            if (targetDirectory == null)
                return;
            String templateName = getTemplateName(getType());
            final PsiClass targetClass = createClassByType(targetDirectory, name, manager, myRefElement, templateName, true);
            if (targetClass == null)
                return;
            bindRef(targetClass, myRefElement);
            IntentionUtils.positionCursor(project, targetClass.getContainingFile(), targetClass);
        }

        @NotNull
        private String getPackage(@NotNull PsiClassOwner file) {
            final PsiElement qualifier = myRefElement.getQualifier();
            if (qualifier instanceof GrReferenceElement) {
                final PsiElement resolved = ((GrReferenceElement) qualifier).resolve();
                if (resolved instanceof PsiPackage) {
                    return ((PsiPackage) resolved).getQualifiedName();
                }
            }
            return file instanceof GroovyFile ? file.getPackageName() : "";
        }

        @Override
        public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
            if (!super.isAvailable(project, editor, file))
                return false;
            final PsiElement qualifier = myRefElement.getQualifier();
            if (qualifier != null && resolveQualifier(qualifier) == null) {
                return false;
            }
            return true;
        }
    };
}
Also used : GroovyFileBase(org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) NotNull(org.jetbrains.annotations.NotNull) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression) GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) Project(com.intellij.openapi.project.Project) GrCodeReferenceElement(org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement) Editor(com.intellij.openapi.editor.Editor) Module(com.intellij.openapi.module.Module) GrReferenceElement(org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement) GroovyFile(org.jetbrains.plugins.groovy.lang.psi.GroovyFile)

Example 19 with GrReferenceElement

use of org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement in project intellij-community by JetBrains.

the class GrChangeSignatureUsageProcessor method processMethodUsage.

private static void processMethodUsage(PsiElement element, JavaChangeInfo changeInfo, boolean toChangeArguments, boolean toCatchExceptions, GrClosureSignatureUtil.ArgInfo<PsiElement>[] map, PsiSubstitutor substitutor) {
    if (map == null)
        return;
    if (changeInfo.isNameChanged()) {
        if (element instanceof GrReferenceElement) {
            element = ((GrReferenceElement) element).handleElementRename(changeInfo.getNewName());
        }
    }
    if (toChangeArguments) {
        JavaParameterInfo[] parameters = changeInfo.getNewParameters();
        GrArgumentList argumentList = PsiUtil.getArgumentsList(element);
        GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(element.getProject());
        if (argumentList == null) {
            if (element instanceof GrEnumConstant) {
                argumentList = factory.createArgumentList();
                argumentList = (GrArgumentList) element.add(argumentList);
            } else {
                return;
            }
        }
        Set<PsiElement> argsToDelete = new HashSet<>(map.length * 2);
        for (GrClosureSignatureUtil.ArgInfo<PsiElement> argInfo : map) {
            argsToDelete.addAll(argInfo.args);
        }
        GrExpression[] values = new GrExpression[parameters.length];
        for (int i = 0; i < parameters.length; i++) {
            JavaParameterInfo parameter = parameters[i];
            int index = parameter.getOldIndex();
            if (index >= 0) {
                argsToDelete.removeAll(map[index].args);
            } else {
                values[i] = createDefaultValue(factory, changeInfo, parameter, argumentList, substitutor);
            }
        }
        for (PsiElement arg : argsToDelete) {
            arg.delete();
        }
        boolean skipOptionals = false;
        //PsiTreeUtil.getChildOfAnyType(argumentList, GrExpression.class, GrNamedArgument.class);
        PsiElement anchor = null;
        for (int i = 0; i < parameters.length; i++) {
            JavaParameterInfo parameter = parameters[i];
            int index = parameter.getOldIndex();
            if (index >= 0) {
                GrClosureSignatureUtil.ArgInfo<PsiElement> argInfo = map[index];
                List<PsiElement> arguments = argInfo.args;
                if (argInfo.isMultiArg) {
                    //arguments for Map and varArg
                    if ((i != 0 || !(!arguments.isEmpty() && arguments.iterator().next() instanceof GrNamedArgument)) && (i != parameters.length - 1 || !parameter.isVarargType())) {
                        final PsiType type = parameter.createType(changeInfo.getMethod().getParameterList(), argumentList.getManager());
                        final GrExpression arg = GroovyRefactoringUtil.generateArgFromMultiArg(substitutor, arguments, type, element.getProject());
                        for (PsiElement argument : arguments) {
                            argument.delete();
                        }
                        anchor = argumentList.addAfter(arg, anchor);
                        JavaCodeStyleManager.getInstance(anchor.getProject()).shortenClassReferences(anchor);
                    }
                } else {
                    //arguments for simple parameters
                    if (arguments.size() == 1) {
                        //arg exists
                        PsiElement arg = arguments.iterator().next();
                        if (i == parameters.length - 1 && parameter.isVarargType()) {
                            if (arg instanceof GrSafeCastExpression) {
                                PsiElement expr = ((GrSafeCastExpression) arg).getOperand();
                                if (expr instanceof GrListOrMap && !((GrListOrMap) expr).isMap()) {
                                    final PsiElement copy = expr.copy();
                                    PsiElement[] newVarargs = ((GrListOrMap) copy).getInitializers();
                                    for (PsiElement vararg : newVarargs) {
                                        anchor = argumentList.addAfter(vararg, anchor);
                                    }
                                    arg.delete();
                                    continue;
                                }
                            }
                        }
                        PsiElement curArg = getNextOfType(argumentList, anchor, GrExpression.class);
                        if (curArg == arg) {
                            anchor = arg;
                        } else {
                            final PsiElement copy = arg.copy();
                            anchor = argumentList.addAfter(copy, anchor);
                            arg.delete();
                        }
                    } else {
                        //arg is skipped. Parameter is optional
                        skipOptionals = true;
                    }
                }
            } else {
                if (skipOptionals && isParameterOptional(parameter))
                    continue;
                if (forceOptional(parameter)) {
                    skipOptionals = true;
                    continue;
                }
                try {
                    final GrExpression value = values[i];
                    if (i > 0 && (value == null || anchor == null)) {
                        PsiElement comma = Factory.createSingleLeafElement(GroovyTokenTypes.mCOMMA, ",", 0, 1, SharedImplUtil.findCharTableByTree(argumentList.getNode()), argumentList.getManager()).getPsi();
                        if (anchor == null)
                            anchor = argumentList.getLeftParen();
                        anchor = argumentList.addAfter(comma, anchor);
                    }
                    if (value != null) {
                        anchor = argumentList.addAfter(value, anchor);
                    }
                } catch (IncorrectOperationException e) {
                    LOG.error(e.getMessage());
                }
            }
        }
        for (PsiElement arg : argsToDelete) {
            arg.delete();
        }
        GrCall call = GroovyRefactoringUtil.getCallExpressionByMethodReference(element);
        if (argumentList.getText().trim().isEmpty() && (call == null || !PsiImplUtil.hasClosureArguments(call))) {
            argumentList = argumentList.replaceWithArgumentList(factory.createArgumentList());
        }
        CodeStyleManager.getInstance(argumentList.getProject()).reformat(argumentList);
    }
    if (toCatchExceptions) {
        final ThrownExceptionInfo[] exceptionInfos = changeInfo.getNewExceptions();
        PsiClassType[] exceptions = getExceptions(exceptionInfos, element, element.getManager());
        fixExceptions(element, exceptions);
    }
}
Also used : GrNamedArgument(org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument) GrCall(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall) GrEnumConstant(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrEnumConstant) GrSafeCastExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrSafeCastExpression) GrListOrMap(org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap) GrReferenceElement(org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement) HashSet(com.intellij.util.containers.HashSet) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) GrClosureSignatureUtil(org.jetbrains.plugins.groovy.lang.psi.impl.signatures.GrClosureSignatureUtil) GrArgumentList(org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 20 with GrReferenceElement

use of org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement in project intellij-community by JetBrains.

the class GrPullUpHelper method fixReferencesToStatic.

private void fixReferencesToStatic(GroovyPsiElement classMember) throws IncorrectOperationException {
    final StaticReferencesCollector collector = new StaticReferencesCollector(myMembersToMove);
    classMember.accept(collector);
    ArrayList<GrReferenceElement> refs = collector.getReferences();
    ArrayList<PsiElement> members = collector.getReferees();
    ArrayList<PsiClass> classes = collector.getRefereeClasses();
    GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(myProject);
    for (int i = 0; i < refs.size(); i++) {
        GrReferenceElement ref = refs.get(i);
        PsiElement namedElement = members.get(i);
        PsiClass aClass = classes.get(i);
        if (namedElement instanceof PsiNamedElement) {
            GrReferenceExpression newRef = (GrReferenceExpression) factory.createExpressionFromText("a." + ((PsiNamedElement) namedElement).getName(), null);
            GrExpression qualifier = newRef.getQualifierExpression();
            assert qualifier != null;
            qualifier = (GrExpression) qualifier.replace(factory.createReferenceExpressionFromText(aClass.getQualifiedName()));
            qualifier.putCopyableUserData(PRESERVE_QUALIFIER, ref.isQualified());
            PsiElement replaced = ref.replace(newRef);
            JavaCodeStyleManager.getInstance(myProject).shortenClassReferences(replaced);
        }
    }
}
Also used : GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) GrReferenceElement(org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)

Aggregations

GrReferenceElement (org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement)25 GrImportStatement (org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement)10 GroovyFile (org.jetbrains.plugins.groovy.lang.psi.GroovyFile)6 GroovyResolveResult (org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult)6 GrReferenceExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)6 GroovyPsiElement (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)5 GroovyPsiElementFactory (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory)5 PsiElement (com.intellij.psi.PsiElement)4 IncorrectOperationException (com.intellij.util.IncorrectOperationException)4 NotNull (org.jetbrains.annotations.NotNull)4 GrCodeReferenceElement (org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement)4 Nullable (org.jetbrains.annotations.Nullable)3 GroovyFileBase (org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase)3 GrExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression)3 GrPackageDefinition (org.jetbrains.plugins.groovy.lang.psi.api.toplevel.packaging.GrPackageDefinition)3 ReferenceData (com.intellij.codeInsight.editorActions.ReferenceData)2 ASTNode (com.intellij.lang.ASTNode)2 Document (com.intellij.openapi.editor.Document)2 Project (com.intellij.openapi.project.Project)2 TextRange (com.intellij.openapi.util.TextRange)2