Search in sources :

Example 41 with GrVariable

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

the class GrReferenceExpressionImpl method getNominalTypeInner.

@Nullable
private PsiType getNominalTypeInner(@Nullable PsiElement resolved) {
    if (resolved == null && !"class".equals(getReferenceName())) {
        resolved = resolve();
    }
    if (resolved instanceof PsiClass) {
        final PsiElementFactory factory = JavaPsiFacade.getInstance(getProject()).getElementFactory();
        if (PsiUtil.isInstanceThisRef(this)) {
            final PsiClassType categoryType = GdkMethodUtil.getCategoryType((PsiClass) resolved);
            if (categoryType != null) {
                return categoryType;
            } else {
                return factory.createType((PsiClass) resolved);
            }
        } else if (PsiUtil.isSuperReference(this)) {
            PsiClass contextClass = PsiUtil.getContextClass(this);
            if (GrTraitUtil.isTrait(contextClass)) {
                PsiClassType[] extendsTypes = contextClass.getExtendsListTypes();
                PsiClassType[] implementsTypes = contextClass.getImplementsListTypes();
                PsiClassType[] superTypes = ArrayUtil.mergeArrays(implementsTypes, extendsTypes, PsiClassType.ARRAY_FACTORY);
                if (superTypes.length > 0) {
                    return PsiIntersectionType.createIntersection(ArrayUtil.reverseArray(superTypes));
                }
            }
            return factory.createType((PsiClass) resolved);
        }
        return TypesUtil.createJavaLangClassType(factory.createType((PsiClass) resolved), getProject(), getResolveScope());
    }
    if (resolved instanceof GrVariable) {
        return ((GrVariable) resolved).getDeclaredType();
    }
    if (resolved instanceof PsiVariable) {
        return ((PsiVariable) resolved).getType();
    }
    if (resolved instanceof PsiMethod) {
        PsiMethod method = (PsiMethod) resolved;
        if (PropertyUtil.isSimplePropertySetter(method) && !method.getName().equals(getReferenceName())) {
            return method.getParameterList().getParameters()[0].getType();
        }
        //'class' property with explicit generic
        PsiClass containingClass = method.getContainingClass();
        if (containingClass != null && CommonClassNames.JAVA_LANG_OBJECT.equals(containingClass.getQualifiedName()) && "getClass".equals(method.getName())) {
            return TypesUtil.createJavaLangClassType(PsiImplUtil.getQualifierType(this), getProject(), getResolveScope());
        }
        return PsiUtil.getSmartReturnType(method);
    }
    if (resolved == null) {
        final PsiType fromClassRef = getTypeFromClassRef(this);
        if (fromClassRef != null) {
            return fromClassRef;
        }
        final PsiType fromMapAccess = getTypeFromMapAccess(this);
        if (fromMapAccess != null) {
            return fromMapAccess;
        }
        final PsiType fromSpreadOperator = getTypeFromSpreadOperator(this);
        if (fromSpreadOperator != null) {
            return fromSpreadOperator;
        }
    }
    return null;
}
Also used : GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) Nullable(org.jetbrains.annotations.Nullable)

Example 42 with GrVariable

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

the class GrVariableDeclarationImpl method setType.

@Override
public void setType(@Nullable PsiType type) {
    final GrTypeElement typeElement = getTypeElementGroovy();
    if (type == null) {
        if (typeElement == null)
            return;
        if (getModifierList().getModifiers().length == 0) {
            getModifierList().setModifierProperty(GrModifier.DEF, true);
        }
        typeElement.delete();
        return;
    }
    type = TypesUtil.unboxPrimitiveTypeWrapper(type);
    GrTypeElement newTypeElement;
    try {
        newTypeElement = GroovyPsiElementFactory.getInstance(getProject()).createTypeElement(type);
    } catch (IncorrectOperationException e) {
        LOG.error(e);
        return;
    }
    if (typeElement == null) {
        getModifierList().setModifierProperty(GrModifier.DEF, false);
        final GrVariable[] variables = getVariables();
        if (variables.length == 0)
            return;
        newTypeElement = (GrTypeElement) addBefore(newTypeElement, variables[0]);
    } else {
        newTypeElement = (GrTypeElement) typeElement.replace(newTypeElement);
    }
    JavaCodeStyleManager.getInstance(getProject()).shortenClassReferences(newTypeElement);
}
Also used : GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) GrTypeElement(org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 43 with GrVariable

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

the class GrTypeDefinitionImpl method add.

@Override
public PsiElement add(@NotNull PsiElement psiElement) throws IncorrectOperationException {
    final GrTypeDefinitionBody body = getBody();
    if (body == null)
        throw new IncorrectOperationException("Class must have body");
    final PsiElement lBrace = body.getLBrace();
    if (lBrace == null)
        throw new IncorrectOperationException("No left brace");
    PsiMember member = getAnyMember(psiElement);
    PsiElement anchor = member != null ? getDefaultAnchor(body, member) : null;
    if (anchor == null) {
        anchor = lBrace.getNextSibling();
    }
    if (anchor != null) {
        ASTNode node = anchor.getNode();
        assert node != null;
        if (GroovyTokenTypes.mSEMI.equals(node.getElementType())) {
            anchor = anchor.getNextSibling();
        }
        if (psiElement instanceof GrField) {
            //add field with modifiers which are in its parent
            int i = ArrayUtilRt.find(((GrVariableDeclaration) psiElement.getParent()).getVariables(), psiElement);
            psiElement = body.addBefore(psiElement.getParent(), anchor);
            GrVariable[] vars = ((GrVariableDeclaration) psiElement).getVariables();
            for (int j = 0; j < vars.length; j++) {
                if (i != j)
                    vars[i].delete();
            }
            psiElement = vars[i];
        } else {
            psiElement = body.addBefore(psiElement, anchor);
        }
    } else {
        psiElement = body.add(psiElement);
    }
    return psiElement;
}
Also used : GrTypeDefinitionBody(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinitionBody) GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) GrField(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField) GrVariableDeclaration(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration) ASTNode(com.intellij.lang.ASTNode) IncorrectOperationException(com.intellij.util.IncorrectOperationException) LeafPsiElement(com.intellij.psi.impl.source.tree.LeafPsiElement)

Example 44 with GrVariable

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

the class GrForStatementImpl method processDeclarations.

@Override
public boolean processDeclarations(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, @Nullable PsiElement lastParent, @NotNull PsiElement place) {
    if (!ResolveUtil.shouldProcessProperties(processor.getHint(ElementClassHint.KEY)))
        return true;
    GrForClause forClause = getClause();
    final GrVariable varScope = PsiTreeUtil.getParentOfType(place, GrVariable.class);
    if (forClause == null)
        return true;
    if (lastParent == null || lastParent instanceof GrForInClause)
        return true;
    GrVariable var = forClause.getDeclaredVariable();
    if (var == null || var.equals(varScope))
        return true;
    if (!ResolveUtil.processElement(processor, var, state))
        return false;
    return true;
}
Also used : GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) GrForInClause(org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForInClause) GrForClause(org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForClause)

Example 45 with GrVariable

use of org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable in project android by JetBrains.

the class GradleEditorModelParserFacade method fillContext.

/**
   * Processes given PSI file and fills given context
   * by {@link GradleEditorModelParseContext#getAssignments(Variable) corresponding assignments}.
   *
   * @param context  context to fill
   * @param psiFile  psi file to parse
   */
private static void fillContext(@NotNull final GradleEditorModelParseContext context, @NotNull PsiFile psiFile) {
    psiFile.acceptChildren(new GroovyPsiElementVisitor(new GroovyRecursiveElementVisitor() {

        @Override
        public void visitMethodCallExpression(GrMethodCallExpression methodCallExpression) {
            Pair<String, TextRange> pair = GradleEditorValueExtractor.extractMethodName(methodCallExpression);
            GrClosableBlock[] closureArguments = methodCallExpression.getClosureArguments();
            if (pair == null || closureArguments.length > 1) {
                super.visitMethodCallExpression(methodCallExpression);
                return;
            }
            if (closureArguments.length == 0) {
                if (methodCallExpression.getArgumentList().getAllArguments().length == 0) {
                    // This is a no-args method, so, we just register it for cases like 'mavenCentral()' or 'jcenter()'.
                    context.addCachedValue(NO_ARGS_METHOD_ASSIGNMENT_VALUE, TextRange.create(pair.second.getEndOffset(), methodCallExpression.getTextRange().getEndOffset()));
                    context.registerAssignmentFromCachedData(pair.first, pair.second, methodCallExpression);
                }
                return;
            }
            context.onMethodEnter(pair.getFirst());
            try {
                super.visitClosure(closureArguments[0]);
            } finally {
                context.onMethodExit();
            }
        }

        @Override
        public void visitApplicationStatement(GrApplicationStatement applicationStatement) {
            Pair<String, TextRange> methodName = GradleEditorValueExtractor.extractMethodName(applicationStatement);
            if (methodName == null) {
                return;
            }
            GroovyPsiElement[] allArguments = applicationStatement.getArgumentList().getAllArguments();
            if (allArguments.length == 1) {
                context.resetCaches();
                extractValueOrVariable(allArguments[0], context);
                context.registerAssignmentFromCachedData(methodName.getFirst(), methodName.getSecond(), applicationStatement.getArgumentList());
            }
        }

        @Override
        public void visitAssignmentExpression(GrAssignmentExpression expression) {
            // General idea is to try to extract variable from the given expression and, in case of success, try to extract rvalue and
            // register corresponding assignment with them.
            context.resetCaches();
            extractValueOrVariable(expression.getLValue(), context);
            Multimap<Variable, Location> vars = context.getCachedVariables();
            if (vars.size() != 1) {
                context.resetCaches();
                return;
            }
            Map.Entry<Variable, Location> entry = vars.entries().iterator().next();
            Variable lVariable = entry.getKey();
            Location lVariableLocation = entry.getValue();
            context.resetCaches();
            GrExpression rValue = expression.getRValue();
            if (rValue == null) {
                return;
            }
            extractValueOrVariable(rValue, context);
            if (context.getCachedValues().size() > 1) {
                Value value = new Value("", new Location(context.getCurrentFile(), GradleEditorModelUtil.interestedRange(rValue)));
                context.setCachedValues(Collections.singletonList(value));
            }
            context.registerAssignmentFromCachedData(lVariable, lVariableLocation, rValue);
            context.resetCaches();
        }

        @Override
        public void visitVariable(GrVariable variable) {
            TextRange nameRange = null;
            boolean lookForInitializer = false;
            ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.findSingle(GroovyLanguage.INSTANCE);
            for (PsiElement e = variable.getFirstChild(); e != null; e = e.getNextSibling()) {
                ASTNode node = e.getNode();
                if (node == null) {
                    continue;
                }
                if (!lookForInitializer) {
                    if (node.getElementType() == GroovyTokenTypes.mIDENT) {
                        nameRange = e.getTextRange();
                    } else if (node.getElementType() == GroovyTokenTypes.mASSIGN) {
                        if (nameRange == null) {
                            return;
                        }
                        lookForInitializer = true;
                    }
                    continue;
                }
                if (node.getElementType() == GroovyTokenTypes.mNLS || node.getElementType() == GroovyTokenTypes.mSEMI) {
                    break;
                }
                if (parserDefinition.getWhitespaceTokens().contains(node.getElementType())) {
                    continue;
                }
                extractValueOrVariable(e, context);
                if (context.getCachedValues().size() > 1) {
                    Value value = new Value("", new Location(context.getCurrentFile(), GradleEditorModelUtil.interestedRange(e)));
                    context.setCachedValues(Collections.singletonList(value));
                }
                if (context.registerAssignmentFromCachedData(variable.getName(), nameRange, e)) {
                    return;
                }
            }
        }
    }));
}
Also used : GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement) GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) GroovyRecursiveElementVisitor(org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor) TextRange(com.intellij.openapi.util.TextRange) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) GrApplicationStatement(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrApplicationStatement) GrVariable(org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable) ParserDefinition(com.intellij.lang.ParserDefinition) GrMethodCallExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression) GrAssignmentExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression) GroovyPsiElementVisitor(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementVisitor) ASTNode(com.intellij.lang.ASTNode) Map(java.util.Map) PsiElement(com.intellij.psi.PsiElement) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)

Aggregations

GrVariable (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable)88 GrExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression)34 PsiElement (com.intellij.psi.PsiElement)24 Nullable (org.jetbrains.annotations.Nullable)20 GrVariableDeclaration (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration)19 GroovyPsiElement (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement)16 NotNull (org.jetbrains.annotations.NotNull)14 GrReferenceExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)14 GrField (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField)12 StringPartInfo (org.jetbrains.plugins.groovy.refactoring.introduce.StringPartInfo)11 GrStatement (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement)10 GrParameter (org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter)10 GrClosableBlock (org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock)8 GrMethod (org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod)8 PsiType (com.intellij.psi.PsiType)7 GroovyResolveResult (org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult)7 GrAssignmentExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression)7 TextRange (com.intellij.openapi.util.TextRange)6 GroovyRecursiveElementVisitor (org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor)6 ASTNode (com.intellij.lang.ASTNode)5