Search in sources :

Example 6 with PsiNewExpression

use of com.intellij.psi.PsiNewExpression in project intellij-community by JetBrains.

the class JNDIResourceInspection method isResourceCreation.

protected boolean isResourceCreation(PsiExpression expression) {
    if (expression instanceof PsiMethodCallExpression) {
        final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) expression;
        final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression();
        @NonNls final String methodName = methodExpression.getReferenceName();
        if ("list".equals(methodName) || "listBindings".equals(methodName)) {
            final PsiExpression qualifier = methodExpression.getQualifierExpression();
            if (qualifier == null) {
                return false;
            }
            return TypeUtils.expressionHasTypeOrSubtype(qualifier, "javax.naming.Context");
        } else if ("getAll".equals(methodName)) {
            final PsiExpression qualifier = methodExpression.getQualifierExpression();
            if (qualifier == null) {
                return false;
            }
            return TypeUtils.expressionHasTypeOrSubtype(qualifier, "javax.naming.directory.Attribute", "javax.naming.directory.Attributes") != null;
        } else {
            return false;
        }
    } else if (expression instanceof PsiNewExpression) {
        return TypeUtils.expressionHasTypeOrSubtype(expression, "javax.naming.InitialContext");
    }
    return false;
}
Also used : NonNls(org.jetbrains.annotations.NonNls) PsiExpression(com.intellij.psi.PsiExpression) PsiReferenceExpression(com.intellij.psi.PsiReferenceExpression) PsiNewExpression(com.intellij.psi.PsiNewExpression) PsiMethodCallExpression(com.intellij.psi.PsiMethodCallExpression)

Example 7 with PsiNewExpression

use of com.intellij.psi.PsiNewExpression in project intellij-community by JetBrains.

the class SocketResourceInspection method isResourceCreation.

@Override
protected boolean isResourceCreation(PsiExpression expression) {
    if (expression instanceof PsiMethodCallExpression) {
        final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression) expression;
        final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression();
        @NonNls final String methodName = methodExpression.getReferenceName();
        if (!"accept".equals(methodName)) {
            return false;
        }
        final PsiExpression qualifier = methodExpression.getQualifierExpression();
        if (qualifier == null || !TypeUtils.expressionHasTypeOrSubtype(qualifier, "java.net.ServerSocket")) {
            return false;
        }
        return TypeUtils.expressionHasTypeOrSubtype(methodCallExpression, "java.net.Socket");
    } else if (expression instanceof PsiNewExpression) {
        return TypeUtils.expressionHasTypeOrSubtype(expression, "java.net.Socket", "java.net.DatagramSocket", "java.net.ServerSocket") != null;
    }
    return false;
}
Also used : NonNls(org.jetbrains.annotations.NonNls) PsiExpression(com.intellij.psi.PsiExpression) PsiReferenceExpression(com.intellij.psi.PsiReferenceExpression) PsiNewExpression(com.intellij.psi.PsiNewExpression) PsiMethodCallExpression(com.intellij.psi.PsiMethodCallExpression)

Example 8 with PsiNewExpression

use of com.intellij.psi.PsiNewExpression in project kotlin by JetBrains.

the class ConstantEvaluator method evaluate.

/**
     * Evaluates the given node and returns the constant value it resolves to, if any
     *
     * @param node the node to compute the constant value for
     * @return the corresponding constant value - a String, an Integer, a Float, and so on
     */
@Nullable
public Object evaluate(@Nullable PsiElement node) {
    if (node == null) {
        return null;
    }
    if (node instanceof PsiLiteral) {
        return ((PsiLiteral) node).getValue();
    } else if (node instanceof PsiPrefixExpression) {
        IElementType operator = ((PsiPrefixExpression) node).getOperationTokenType();
        Object operand = evaluate(((PsiPrefixExpression) node).getOperand());
        if (operand == null) {
            return null;
        }
        if (operator == JavaTokenType.EXCL) {
            if (operand instanceof Boolean) {
                return !(Boolean) operand;
            }
        } else if (operator == JavaTokenType.PLUS) {
            return operand;
        } else if (operator == JavaTokenType.TILDE) {
            if (operand instanceof Integer) {
                return ~(Integer) operand;
            } else if (operand instanceof Long) {
                return ~(Long) operand;
            } else if (operand instanceof Short) {
                return ~(Short) operand;
            } else if (operand instanceof Character) {
                return ~(Character) operand;
            } else if (operand instanceof Byte) {
                return ~(Byte) operand;
            }
        } else if (operator == JavaTokenType.MINUS) {
            if (operand instanceof Integer) {
                return -(Integer) operand;
            } else if (operand instanceof Long) {
                return -(Long) operand;
            } else if (operand instanceof Double) {
                return -(Double) operand;
            } else if (operand instanceof Float) {
                return -(Float) operand;
            } else if (operand instanceof Short) {
                return -(Short) operand;
            } else if (operand instanceof Character) {
                return -(Character) operand;
            } else if (operand instanceof Byte) {
                return -(Byte) operand;
            }
        }
    } else if (node instanceof PsiConditionalExpression) {
        PsiConditionalExpression expression = (PsiConditionalExpression) node;
        Object known = evaluate(expression.getCondition());
        if (known == Boolean.TRUE && expression.getThenExpression() != null) {
            return evaluate(expression.getThenExpression());
        } else if (known == Boolean.FALSE && expression.getElseExpression() != null) {
            return evaluate(expression.getElseExpression());
        }
    } else if (node instanceof PsiParenthesizedExpression) {
        PsiParenthesizedExpression parenthesizedExpression = (PsiParenthesizedExpression) node;
        PsiExpression expression = parenthesizedExpression.getExpression();
        if (expression != null) {
            return evaluate(expression);
        }
    } else if (node instanceof PsiBinaryExpression) {
        IElementType operator = ((PsiBinaryExpression) node).getOperationTokenType();
        Object operandLeft = evaluate(((PsiBinaryExpression) node).getLOperand());
        Object operandRight = evaluate(((PsiBinaryExpression) node).getROperand());
        if (operandLeft == null || operandRight == null) {
            if (mAllowUnknown) {
                if (operandLeft == null) {
                    return operandRight;
                } else {
                    return operandLeft;
                }
            }
            return null;
        }
        if (operandLeft instanceof String && operandRight instanceof String) {
            if (operator == JavaTokenType.PLUS) {
                return operandLeft.toString() + operandRight.toString();
            }
            return null;
        } else if (operandLeft instanceof Boolean && operandRight instanceof Boolean) {
            boolean left = (Boolean) operandLeft;
            boolean right = (Boolean) operandRight;
            if (operator == JavaTokenType.OROR) {
                return left || right;
            } else if (operator == JavaTokenType.ANDAND) {
                return left && right;
            } else if (operator == JavaTokenType.OR) {
                return left | right;
            } else if (operator == JavaTokenType.XOR) {
                return left ^ right;
            } else if (operator == JavaTokenType.AND) {
                return left & right;
            } else if (operator == JavaTokenType.EQEQ) {
                return left == right;
            } else if (operator == JavaTokenType.NE) {
                return left != right;
            }
        } else if (operandLeft instanceof Number && operandRight instanceof Number) {
            Number left = (Number) operandLeft;
            Number right = (Number) operandRight;
            boolean isInteger = !(left instanceof Float || left instanceof Double || right instanceof Float || right instanceof Double);
            boolean isWide = isInteger ? (left instanceof Long || right instanceof Long) : (left instanceof Double || right instanceof Double);
            if (operator == JavaTokenType.OR) {
                if (isWide) {
                    return left.longValue() | right.longValue();
                } else {
                    return left.intValue() | right.intValue();
                }
            } else if (operator == JavaTokenType.XOR) {
                if (isWide) {
                    return left.longValue() ^ right.longValue();
                } else {
                    return left.intValue() ^ right.intValue();
                }
            } else if (operator == JavaTokenType.AND) {
                if (isWide) {
                    return left.longValue() & right.longValue();
                } else {
                    return left.intValue() & right.intValue();
                }
            } else if (operator == JavaTokenType.EQEQ) {
                if (isInteger) {
                    return left.longValue() == right.longValue();
                } else {
                    return left.doubleValue() == right.doubleValue();
                }
            } else if (operator == JavaTokenType.NE) {
                if (isInteger) {
                    return left.longValue() != right.longValue();
                } else {
                    return left.doubleValue() != right.doubleValue();
                }
            } else if (operator == JavaTokenType.GT) {
                if (isInteger) {
                    return left.longValue() > right.longValue();
                } else {
                    return left.doubleValue() > right.doubleValue();
                }
            } else if (operator == JavaTokenType.GE) {
                if (isInteger) {
                    return left.longValue() >= right.longValue();
                } else {
                    return left.doubleValue() >= right.doubleValue();
                }
            } else if (operator == JavaTokenType.LT) {
                if (isInteger) {
                    return left.longValue() < right.longValue();
                } else {
                    return left.doubleValue() < right.doubleValue();
                }
            } else if (operator == JavaTokenType.LE) {
                if (isInteger) {
                    return left.longValue() <= right.longValue();
                } else {
                    return left.doubleValue() <= right.doubleValue();
                }
            } else if (operator == JavaTokenType.LTLT) {
                if (isWide) {
                    return left.longValue() << right.intValue();
                } else {
                    return left.intValue() << right.intValue();
                }
            } else if (operator == JavaTokenType.GTGT) {
                if (isWide) {
                    return left.longValue() >> right.intValue();
                } else {
                    return left.intValue() >> right.intValue();
                }
            } else if (operator == JavaTokenType.GTGTGT) {
                if (isWide) {
                    return left.longValue() >>> right.intValue();
                } else {
                    return left.intValue() >>> right.intValue();
                }
            } else if (operator == JavaTokenType.PLUS) {
                if (isInteger) {
                    if (isWide) {
                        return left.longValue() + right.longValue();
                    } else {
                        return left.intValue() + right.intValue();
                    }
                } else {
                    if (isWide) {
                        return left.doubleValue() + right.doubleValue();
                    } else {
                        return left.floatValue() + right.floatValue();
                    }
                }
            } else if (operator == JavaTokenType.MINUS) {
                if (isInteger) {
                    if (isWide) {
                        return left.longValue() - right.longValue();
                    } else {
                        return left.intValue() - right.intValue();
                    }
                } else {
                    if (isWide) {
                        return left.doubleValue() - right.doubleValue();
                    } else {
                        return left.floatValue() - right.floatValue();
                    }
                }
            } else if (operator == JavaTokenType.ASTERISK) {
                if (isInteger) {
                    if (isWide) {
                        return left.longValue() * right.longValue();
                    } else {
                        return left.intValue() * right.intValue();
                    }
                } else {
                    if (isWide) {
                        return left.doubleValue() * right.doubleValue();
                    } else {
                        return left.floatValue() * right.floatValue();
                    }
                }
            } else if (operator == JavaTokenType.DIV) {
                if (isInteger) {
                    if (isWide) {
                        return left.longValue() / right.longValue();
                    } else {
                        return left.intValue() / right.intValue();
                    }
                } else {
                    if (isWide) {
                        return left.doubleValue() / right.doubleValue();
                    } else {
                        return left.floatValue() / right.floatValue();
                    }
                }
            } else if (operator == JavaTokenType.PERC) {
                if (isInteger) {
                    if (isWide) {
                        return left.longValue() % right.longValue();
                    } else {
                        return left.intValue() % right.intValue();
                    }
                } else {
                    if (isWide) {
                        return left.doubleValue() % right.doubleValue();
                    } else {
                        return left.floatValue() % right.floatValue();
                    }
                }
            } else {
                return null;
            }
        }
    } else if (node instanceof PsiTypeCastExpression) {
        PsiTypeCastExpression cast = (PsiTypeCastExpression) node;
        Object operandValue = evaluate(cast.getOperand());
        if (operandValue instanceof Number) {
            Number number = (Number) operandValue;
            PsiTypeElement typeElement = cast.getCastType();
            if (typeElement != null) {
                PsiType type = typeElement.getType();
                if (PsiType.FLOAT.equals(type)) {
                    return number.floatValue();
                } else if (PsiType.DOUBLE.equals(type)) {
                    return number.doubleValue();
                } else if (PsiType.INT.equals(type)) {
                    return number.intValue();
                } else if (PsiType.LONG.equals(type)) {
                    return number.longValue();
                } else if (PsiType.SHORT.equals(type)) {
                    return number.shortValue();
                } else if (PsiType.BYTE.equals(type)) {
                    return number.byteValue();
                }
            }
        }
        return operandValue;
    } else if (node instanceof PsiReference) {
        PsiElement resolved = ((PsiReference) node).resolve();
        if (resolved instanceof PsiField) {
            PsiField field = (PsiField) resolved;
            Object value = field.computeConstantValue();
            if (value != null) {
                return value;
            }
            if (field.getInitializer() != null) {
                return evaluate(field.getInitializer());
            }
            return null;
        } else if (resolved instanceof PsiLocalVariable) {
            PsiLocalVariable variable = (PsiLocalVariable) resolved;
            PsiStatement statement = PsiTreeUtil.getParentOfType(node, PsiStatement.class, false);
            if (statement != null) {
                PsiStatement prev = PsiTreeUtil.getPrevSiblingOfType(statement, PsiStatement.class);
                String targetName = variable.getName();
                if (targetName == null) {
                    return null;
                }
                while (prev != null) {
                    if (prev instanceof PsiDeclarationStatement) {
                        for (PsiElement element : ((PsiDeclarationStatement) prev).getDeclaredElements()) {
                            if (variable.equals(element)) {
                                return evaluate(variable.getInitializer());
                            }
                        }
                    } else if (prev instanceof PsiExpressionStatement) {
                        PsiExpression expression = ((PsiExpressionStatement) prev).getExpression();
                        if (expression instanceof PsiAssignmentExpression) {
                            PsiAssignmentExpression assign = (PsiAssignmentExpression) expression;
                            PsiExpression lhs = assign.getLExpression();
                            if (lhs instanceof PsiReferenceExpression) {
                                PsiReferenceExpression reference = (PsiReferenceExpression) lhs;
                                if (targetName.equals(reference.getReferenceName()) && reference.getQualifier() == null) {
                                    return evaluate(assign.getRExpression());
                                }
                            }
                        }
                    }
                    prev = PsiTreeUtil.getPrevSiblingOfType(prev, PsiStatement.class);
                }
            }
        }
    } else if (node instanceof PsiNewExpression) {
        PsiNewExpression creation = (PsiNewExpression) node;
        PsiArrayInitializerExpression initializer = creation.getArrayInitializer();
        PsiType type = creation.getType();
        if (type instanceof PsiArrayType) {
            if (initializer != null) {
                PsiExpression[] initializers = initializer.getInitializers();
                Class<?> commonType = null;
                List<Object> values = Lists.newArrayListWithExpectedSize(initializers.length);
                int count = 0;
                for (PsiExpression expression : initializers) {
                    Object value = evaluate(expression);
                    if (value != null) {
                        values.add(value);
                        if (commonType == null) {
                            commonType = value.getClass();
                        } else {
                            while (!commonType.isAssignableFrom(value.getClass())) {
                                commonType = commonType.getSuperclass();
                            }
                        }
                    } else if (!mAllowUnknown) {
                        // Inconclusive
                        return null;
                    }
                    count++;
                    if (count == 20) {
                        // avoid large initializers
                        break;
                    }
                }
                type = type.getDeepComponentType();
                if (type == PsiType.INT) {
                    if (!values.isEmpty()) {
                        int[] array = new int[values.size()];
                        for (int i = 0; i < values.size(); i++) {
                            Object o = values.get(i);
                            if (o instanceof Integer) {
                                array[i] = (Integer) o;
                            }
                        }
                        return array;
                    }
                    return new int[0];
                } else if (type == PsiType.BOOLEAN) {
                    if (!values.isEmpty()) {
                        boolean[] array = new boolean[values.size()];
                        for (int i = 0; i < values.size(); i++) {
                            Object o = values.get(i);
                            if (o instanceof Boolean) {
                                array[i] = (Boolean) o;
                            }
                        }
                        return array;
                    }
                    return new boolean[0];
                } else if (type == PsiType.DOUBLE) {
                    if (!values.isEmpty()) {
                        double[] array = new double[values.size()];
                        for (int i = 0; i < values.size(); i++) {
                            Object o = values.get(i);
                            if (o instanceof Double) {
                                array[i] = (Double) o;
                            }
                        }
                        return array;
                    }
                    return new double[0];
                } else if (type == PsiType.LONG) {
                    if (!values.isEmpty()) {
                        long[] array = new long[values.size()];
                        for (int i = 0; i < values.size(); i++) {
                            Object o = values.get(i);
                            if (o instanceof Long) {
                                array[i] = (Long) o;
                            }
                        }
                        return array;
                    }
                    return new long[0];
                } else if (type == PsiType.FLOAT) {
                    if (!values.isEmpty()) {
                        float[] array = new float[values.size()];
                        for (int i = 0; i < values.size(); i++) {
                            Object o = values.get(i);
                            if (o instanceof Float) {
                                array[i] = (Float) o;
                            }
                        }
                        return array;
                    }
                    return new float[0];
                } else if (type == PsiType.CHAR) {
                    if (!values.isEmpty()) {
                        char[] array = new char[values.size()];
                        for (int i = 0; i < values.size(); i++) {
                            Object o = values.get(i);
                            if (o instanceof Character) {
                                array[i] = (Character) o;
                            }
                        }
                        return array;
                    }
                    return new char[0];
                } else if (type == PsiType.BYTE) {
                    if (!values.isEmpty()) {
                        byte[] array = new byte[values.size()];
                        for (int i = 0; i < values.size(); i++) {
                            Object o = values.get(i);
                            if (o instanceof Byte) {
                                array[i] = (Byte) o;
                            }
                        }
                        return array;
                    }
                    return new byte[0];
                } else if (type == PsiType.SHORT) {
                    if (!values.isEmpty()) {
                        short[] array = new short[values.size()];
                        for (int i = 0; i < values.size(); i++) {
                            Object o = values.get(i);
                            if (o instanceof Short) {
                                array[i] = (Short) o;
                            }
                        }
                        return array;
                    }
                    return new short[0];
                } else {
                    if (!values.isEmpty()) {
                        Object o = Array.newInstance(commonType, values.size());
                        return values.toArray((Object[]) o);
                    }
                    return null;
                }
            } else {
                // something like "new byte[3]" but with no initializer.
                // Look up the size and only if small, use it. E.g. if it was byte[3]
                // we return a byte[3] array, but if it's say byte[1024*1024] we don't
                // want to do that.
                PsiExpression[] arrayDimensions = creation.getArrayDimensions();
                int size = 0;
                if (arrayDimensions.length == 1) {
                    Object fixedSize = evaluate(arrayDimensions[0]);
                    if (fixedSize instanceof Number) {
                        size = ((Number) fixedSize).intValue();
                        if (size > 30) {
                            size = 30;
                        }
                    }
                }
                type = type.getDeepComponentType();
                if (type instanceof PsiPrimitiveType) {
                    if (PsiType.BYTE.equals(type)) {
                        return new byte[size];
                    }
                    if (PsiType.BOOLEAN.equals(type)) {
                        return new boolean[size];
                    }
                    if (PsiType.INT.equals(type)) {
                        return new int[size];
                    }
                    if (PsiType.LONG.equals(type)) {
                        return new long[size];
                    }
                    if (PsiType.CHAR.equals(type)) {
                        return new char[size];
                    }
                    if (PsiType.FLOAT.equals(type)) {
                        return new float[size];
                    }
                    if (PsiType.DOUBLE.equals(type)) {
                        return new double[size];
                    }
                    if (PsiType.SHORT.equals(type)) {
                        return new short[size];
                    }
                } else if (type instanceof PsiClassType) {
                    String className = type.getCanonicalText();
                    if (TYPE_STRING.equals(className)) {
                        //noinspection SSBasedInspection
                        return new String[size];
                    }
                    if (TYPE_OBJECT.equals(className)) {
                        //noinspection SSBasedInspection
                        return new Object[size];
                    }
                }
            }
        }
    }
    return null;
}
Also used : PsiPrefixExpression(com.intellij.psi.PsiPrefixExpression) PsiExpression(com.intellij.psi.PsiExpression) PsiReferenceExpression(com.intellij.psi.PsiReferenceExpression) PsiAssignmentExpression(com.intellij.psi.PsiAssignmentExpression) PsiLiteral(com.intellij.psi.PsiLiteral) PsiLocalVariable(com.intellij.psi.PsiLocalVariable) PsiArrayInitializerExpression(com.intellij.psi.PsiArrayInitializerExpression) PsiTypeCastExpression(com.intellij.psi.PsiTypeCastExpression) PsiArrayType(com.intellij.psi.PsiArrayType) PsiParenthesizedExpression(com.intellij.psi.PsiParenthesizedExpression) List(java.util.List) ArrayList(java.util.ArrayList) PsiElement(com.intellij.psi.PsiElement) PsiType(com.intellij.psi.PsiType) PsiStatement(com.intellij.psi.PsiStatement) PsiDeclarationStatement(com.intellij.psi.PsiDeclarationStatement) PsiPrimitiveType(com.intellij.psi.PsiPrimitiveType) PsiReference(com.intellij.psi.PsiReference) PsiNewExpression(com.intellij.psi.PsiNewExpression) PsiConditionalExpression(com.intellij.psi.PsiConditionalExpression) IElementType(com.intellij.psi.tree.IElementType) PsiClassType(com.intellij.psi.PsiClassType) PsiExpressionStatement(com.intellij.psi.PsiExpressionStatement) PsiTypeElement(com.intellij.psi.PsiTypeElement) PsiField(com.intellij.psi.PsiField) PsiClass(com.intellij.psi.PsiClass) PsiBinaryExpression(com.intellij.psi.PsiBinaryExpression) Nullable(com.android.annotations.Nullable)

Example 9 with PsiNewExpression

use of com.intellij.psi.PsiNewExpression in project oxy-template-support-plugin by mutant-industries.

the class GlobalVariableTypeProvider method compute.

@Nullable
@Override
public Result<JSType> compute() {
    List<PsiElement> cacheDependencies = new LinkedList<>();
    cacheDependencies.add(expression);
    // controllers
    if (CONTROLLERS_GLOBAL_VARIABLE_NAME.equals(name)) {
        Project project = expression.getProject();
        GlobalSearchScope allScope = ProjectScope.getAllScope(project);
        GlobalSearchScope projectScope = ProjectScope.getProjectScope(project);
        List<JSRecordTypeImpl.TypeMember> members = new LinkedList<>();
        JSTypeSource typeSource = JSTypeSourceFactory.createTypeSource(expression, true);
        PsiClass controller;
        PsiClass controllerAnnotation = JavaPsiFacade.getInstance(project).findClass(CONTROLLER_FQN, allScope);
        if (controllerAnnotation != null && controllerAnnotation.isAnnotationType()) {
            for (PsiReference controllerAnnotationReference : ReferencesSearch.search(controllerAnnotation, projectScope).findAll()) {
                PsiElement reference = controllerAnnotationReference.getElement();
                if ((controller = PsiTreeUtil.getParentOfType(reference, PsiClass.class)) != null && controller.getQualifiedName() != null) {
                    JSTypeSource source = JSTypeSourceFactory.createTypeSource(controller, true);
                    JSType jsType = JSTypeUtils.createType(controller.getQualifiedName(), source);
                    JSRecordTypeImpl.PropertySignature signature = new JSRecordTypeImpl.PropertySignatureImpl(controller.getName(), jsType, false);
                    members.add(signature);
                    cacheDependencies.add(controller);
                }
            }
        }
        Collections.addAll(cacheDependencies, FilenameIndex.getFilesByName(project, CONTROLLERS_BEANS_FILE_NAME, ProjectScope.getProjectScope(project)));
        return Result.create(new JSRecordTypeImpl(typeSource, ImmutableList.copyOf(members)), cacheDependencies);
    }
    PsiReturnStatement returnStatement;
    PsiClass aClass;
    PsiElement elementAt;
    // global model provider
    if ((returnStatement = PsiTreeUtil.getParentOfType(expression, PsiReturnStatement.class)) != null && (aClass = PsiTreeUtil.getParentOfType(returnStatement, PsiClass.class)) != null && InheritanceUtil.isInheritor(aClass, GLOBAL_MODEL_PROVIDER_FQN)) {
        return Result.create(getTypeFromProvider(aClass), cacheDependencies);
    } else // model provider registry
    {
        elementAt = expression;
        while (elementAt != null && !((elementAt = elementAt.getNextSibling()) instanceof PsiExpression)) ;
        if (elementAt instanceof PsiNewExpression) {
            PsiJavaCodeReferenceElement providerClassReference = PsiTreeUtil.getNextSiblingOfType(elementAt.getFirstChild(), PsiJavaCodeReferenceElement.class);
            PsiElement providerClass;
            if (providerClassReference != null && (providerClass = providerClassReference.resolve()) instanceof PsiClass) {
                aClass = (PsiClass) providerClass;
            } else if ((aClass = PsiTreeUtil.getNextSiblingOfType(elementAt.getFirstChild(), PsiAnonymousClass.class)) == null) {
                return Result.create(null, expression);
            }
            cacheDependencies.add(aClass);
            return Result.create(getTypeFromProvider(aClass), cacheDependencies);
        } else if (elementAt != null) {
            PsiType type = ((PsiExpression) elementAt).getType();
            if (type != null && (aClass = JavaPsiFacade.getInstance(expression.getProject()).findClass(type.getCanonicalText(), ProjectScope.getAllScope(expression.getProject()))) != null) {
                return Result.create(getTypeFromProvider(aClass), cacheDependencies);
            }
        }
    }
    return Result.create(null, cacheDependencies);
}
Also used : JSTypeSource(com.intellij.lang.javascript.psi.types.JSTypeSource) JSType(com.intellij.lang.javascript.psi.JSType) PsiExpression(com.intellij.psi.PsiExpression) PsiJavaCodeReferenceElement(com.intellij.psi.PsiJavaCodeReferenceElement) PsiClass(com.intellij.psi.PsiClass) PsiReference(com.intellij.psi.PsiReference) LinkedList(java.util.LinkedList) PsiNewExpression(com.intellij.psi.PsiNewExpression) JSRecordTypeImpl(com.intellij.lang.javascript.psi.types.JSRecordTypeImpl) Project(com.intellij.openapi.project.Project) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) PsiReturnStatement(com.intellij.psi.PsiReturnStatement) PsiElement(com.intellij.psi.PsiElement) PsiType(com.intellij.psi.PsiType) Nullable(org.jetbrains.annotations.Nullable)

Example 10 with PsiNewExpression

use of com.intellij.psi.PsiNewExpression in project google-cloud-intellij by GoogleCloudPlatform.

the class AppEngineForbiddenCodeInspection method checkFile.

@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull final InspectionManager manager, final boolean isOnTheFly) {
    final Project project = manager.getProject();
    Module module = ModuleUtilCore.findModuleForPsiElement(file);
    final AppEngineStandardFacet appEngineStandardFacet = AppEngineStandardFacet.getAppEngineFacetByModule(module);
    if (appEngineStandardFacet == null) {
        return null;
    }
    if (appEngineStandardFacet.getRuntimeJavaVersion().atLeast(JavaVersion.JAVA_1_8)) {
        return null;
    }
    final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
    final List<ProblemDescriptor> problems = new ArrayList<ProblemDescriptor>();
    file.accept(new JavaRecursiveElementWalkingVisitor() {

        CloudSdkInternals sdkInternals = CloudSdkInternals.getInstance();

        @Override
        public void visitDocComment(PsiDocComment comment) {
        }

        @Override
        public void visitMethod(PsiMethod method) {
            final PsiModifierList modifierList = method.getModifierList();
            if (modifierList.hasModifierProperty(PsiModifier.NATIVE)) {
                if (!isNativeMethodAllowed(method)) {
                    problems.add(manager.createProblemDescriptor(modifierList, "Native methods aren't allowed in App Engine application", isOnTheFly, LocalQuickFix.EMPTY_ARRAY, ProblemHighlightType.GENERIC_ERROR_OR_WARNING));
                }
            }
            super.visitMethod(method);
        }

        @Override
        public void visitNewExpression(PsiNewExpression expression) {
            final PsiJavaCodeReferenceElement classReference = expression.getClassReference();
            if (classReference != null) {
                final PsiElement resolved = classReference.resolve();
                if (resolved instanceof PsiClass) {
                    final String qualifiedName = ((PsiClass) resolved).getQualifiedName();
                    if (qualifiedName != null && sdkInternals.isMethodInBlacklist(qualifiedName, "new")) {
                        final String message = "App Engine application should not create new instances of '" + qualifiedName + "' class";
                        problems.add(manager.createProblemDescriptor(classReference, message, isOnTheFly, LocalQuickFix.EMPTY_ARRAY, ProblemHighlightType.GENERIC_ERROR_OR_WARNING));
                    }
                }
            }
            super.visitNewExpression(expression);
        }

        @Override
        public void visitMethodCallExpression(PsiMethodCallExpression expression) {
            final PsiReferenceExpression methodExpression = expression.getMethodExpression();
            final PsiElement element = methodExpression.resolve();
            if (element instanceof PsiMethod) {
                final PsiMethod method = (PsiMethod) element;
                final PsiClass psiClass = method.getContainingClass();
                if (psiClass != null) {
                    final String qualifiedName = psiClass.getQualifiedName();
                    final String methodName = method.getName();
                    if (qualifiedName != null && sdkInternals.isMethodInBlacklist(qualifiedName, methodName)) {
                        final String message = "AppEngine application should not call '" + StringUtil.getShortName(qualifiedName) + "" + methodName + "' method";
                        problems.add(manager.createProblemDescriptor(methodExpression, message, isOnTheFly, LocalQuickFix.EMPTY_ARRAY, ProblemHighlightType.GENERIC_ERROR_OR_WARNING));
                    }
                }
            }
            super.visitMethodCallExpression(expression);
        }

        @Override
        public void visitReferenceElement(PsiJavaCodeReferenceElement reference) {
            final PsiElement resolved = reference.resolve();
            if (resolved instanceof PsiClass) {
                final PsiFile psiFile = resolved.getContainingFile();
                if (psiFile != null) {
                    final VirtualFile virtualFile = psiFile.getVirtualFile();
                    if (virtualFile != null && !fileIndex.isInSource(virtualFile)) {
                        final List<OrderEntry> list = fileIndex.getOrderEntriesForFile(virtualFile);
                        for (OrderEntry entry : list) {
                            if (entry instanceof JdkOrderEntry) {
                                final String className = ClassUtil.getJVMClassName((PsiClass) resolved);
                                if (className != null && !sdkInternals.isClassInWhiteList(className)) {
                                    problems.add(manager.createProblemDescriptor(reference, "Class '" + className + "' is not included in App Engine JRE White List", isOnTheFly, LocalQuickFix.EMPTY_ARRAY, ProblemHighlightType.GENERIC_ERROR_OR_WARNING));
                                }
                            }
                        }
                    }
                }
            }
            super.visitReferenceElement(reference);
        }
    });
    return problems.toArray(new ProblemDescriptor[problems.size()]);
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiMethod(com.intellij.psi.PsiMethod) ProblemDescriptor(com.intellij.codeInspection.ProblemDescriptor) PsiJavaCodeReferenceElement(com.intellij.psi.PsiJavaCodeReferenceElement) PsiReferenceExpression(com.intellij.psi.PsiReferenceExpression) ArrayList(java.util.ArrayList) CloudSdkInternals(com.google.cloud.tools.intellij.appengine.sdk.CloudSdkInternals) JdkOrderEntry(com.intellij.openapi.roots.JdkOrderEntry) OrderEntry(com.intellij.openapi.roots.OrderEntry) PsiFile(com.intellij.psi.PsiFile) ArrayList(java.util.ArrayList) PsiModifierList(com.intellij.psi.PsiModifierList) List(java.util.List) PsiElement(com.intellij.psi.PsiElement) JavaRecursiveElementWalkingVisitor(com.intellij.psi.JavaRecursiveElementWalkingVisitor) PsiDocComment(com.intellij.psi.javadoc.PsiDocComment) JdkOrderEntry(com.intellij.openapi.roots.JdkOrderEntry) PsiClass(com.intellij.psi.PsiClass) PsiNewExpression(com.intellij.psi.PsiNewExpression) PsiModifierList(com.intellij.psi.PsiModifierList) PsiMethodCallExpression(com.intellij.psi.PsiMethodCallExpression) Project(com.intellij.openapi.project.Project) ProjectFileIndex(com.intellij.openapi.roots.ProjectFileIndex) AppEngineStandardFacet(com.google.cloud.tools.intellij.appengine.facet.standard.AppEngineStandardFacet) Module(com.intellij.openapi.module.Module)

Aggregations

PsiNewExpression (com.intellij.psi.PsiNewExpression)10 PsiElement (com.intellij.psi.PsiElement)8 PsiExpression (com.intellij.psi.PsiExpression)6 PsiReferenceExpression (com.intellij.psi.PsiReferenceExpression)6 PsiClass (com.intellij.psi.PsiClass)4 PsiMethodCallExpression (com.intellij.psi.PsiMethodCallExpression)4 PsiJavaCodeReferenceElement (com.intellij.psi.PsiJavaCodeReferenceElement)3 PsiReference (com.intellij.psi.PsiReference)3 PsiType (com.intellij.psi.PsiType)3 Project (com.intellij.openapi.project.Project)2 PsiAnonymousClass (com.intellij.psi.PsiAnonymousClass)2 PsiArrayType (com.intellij.psi.PsiArrayType)2 PsiAssignmentExpression (com.intellij.psi.PsiAssignmentExpression)2 PsiDeclarationStatement (com.intellij.psi.PsiDeclarationStatement)2 PsiExpressionStatement (com.intellij.psi.PsiExpressionStatement)2 PsiField (com.intellij.psi.PsiField)2 PsiLocalVariable (com.intellij.psi.PsiLocalVariable)2 PsiMethod (com.intellij.psi.PsiMethod)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2