Search in sources :

Example 81 with PsiType

use of com.intellij.psi.PsiType in project intellij-plugins by JetBrains.

the class LiteralExpressionPsiTest method runBigDecimalLiteral.

private void runBigDecimalLiteral(@Language(value = OgnlLanguage.ID, prefix = OgnlLanguage.EXPRESSION_PREFIX, suffix = OgnlLanguage.EXPRESSION_SUFFIX) final String bigDecimalExpression) {
    final OgnlLiteralExpression expression = parse(bigDecimalExpression);
    final PsiType type = expression.getType();
    assertNotNull(type);
    assertEquals("java.math.BigDecimal", type.getCanonicalText());
    assertEquals(new BigDecimal(bigDecimalExpression.substring(0, bigDecimalExpression.length() - 1)), expression.getConstantValue());
}
Also used : BigDecimal(java.math.BigDecimal) PsiType(com.intellij.psi.PsiType)

Example 82 with PsiType

use of com.intellij.psi.PsiType in project intellij-plugins by JetBrains.

the class CfmlStringLiteralExpression method getReferences.

@NotNull
@Override
public PsiReference[] getReferences() {
    CfmlFunctionCallExpression functionCallEl = PsiTreeUtil.getParentOfType(this, CfmlFunctionCallExpression.class);
    if (functionCallEl != null && functionCallEl.isCreateObject()) {
        final String[] args = functionCallEl.getArgumentsAsStrings();
        final CfmlExpression[] expressions = functionCallEl.getArguments();
        final PsiElement referenceElement = findChildByType(CfmlTokenTypes.STRING_TEXT);
        if (referenceElement == null) {
            return super.getReferences();
        }
        if (args.length == 2 && "java".equals(args[0]) && expressions.length == 2 && expressions[1] == this) {
            final JavaClassReferenceProvider provider = new JavaClassReferenceProvider();
            return provider.getReferencesByString(args[1], referenceElement, 0);
        } else if ((args.length == 2 && "component".equals(args[0]) && expressions.length == 2 && expressions[1] == this) || (args.length == 1 && expressions.length == 1 && expressions[0] == this)) {
            final ASTNode referenceNode = referenceElement.getNode();
            if (referenceNode != null) {
                return new PsiReference[] { new CfmlComponentReference(referenceNode) };
            }
        }
    } else if (functionCallEl != null && functionCallEl.isExpandPath()) {
        final PsiElement referenceElement = findChildByType(CfmlTokenTypes.STRING_TEXT);
        if (referenceElement == null) {
            return super.getReferences();
        }
        final ASTNode referenceNode = referenceElement.getNode();
        if (referenceNode != null) {
            return (new CfmlFileReferenceSet(this, 1)).getAllReferences();
        }
    } else if (functionCallEl != null && functionCallEl.isCreateFromJavaLoader()) {
        CfmlExpression[] expressions = functionCallEl.getArguments();
        if (expressions.length > 0 && expressions[0] == this) {
            PsiElement stringTextElement = findChildByType(CfmlTokenTypes.STRING_TEXT);
            if (stringTextElement != null) {
                // getting javaloader type
                PsiElement secondChild = functionCallEl.getFirstChild().getFirstChild();
                if (!(secondChild instanceof CfmlReferenceExpression)) {
                    return super.getReferences();
                }
                PsiType type = ((CfmlReferenceExpression) secondChild).getPsiType();
                if (!(type instanceof CfmlJavaLoaderClassType)) {
                    return super.getReferences();
                }
                final GlobalSearchScope ss = ((CfmlJavaLoaderClassType) type).getSearchScope();
                String possibleJavaClassName = stringTextElement.getText();
                final JavaClassReferenceProvider provider = new JavaClassReferenceProvider() {

                    @Override
                    public GlobalSearchScope getScope(Project project) {
                        return ss;
                    }
                };
                return provider.getReferencesByString(possibleJavaClassName, stringTextElement, 0);
            }
        }
    } else if (getParent() instanceof CfmlComponentConstructorCall || getParent() instanceof CfmlImport) {
        PsiElement stringTextElement = findChildByType(CfmlTokenTypes.STRING_TEXT);
        if (stringTextElement != null) {
            return new PsiReference[] { new CfmlComponentReference(stringTextElement.getNode(), this) };
        }
    }
    return super.getReferences();
}
Also used : JavaClassReferenceProvider(com.intellij.psi.impl.source.resolve.reference.impl.providers.JavaClassReferenceProvider) Project(com.intellij.openapi.project.Project) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) ASTNode(com.intellij.lang.ASTNode) PsiElement(com.intellij.psi.PsiElement) PsiType(com.intellij.psi.PsiType) NotNull(org.jetbrains.annotations.NotNull)

Example 83 with PsiType

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

the class StringFormatDetector method checkStringFormatCall.

/**
     * Check the given String.format call (with the given arguments) to see if the string format is
     * being used correctly
     *  @param context           the context to report errors to
     * @param calledMethod      the method being called
     * @param call              the AST node for the {@link String#format}
     * @param specifiesLocale   whether the first parameter is a locale string, shifting the
     */
private void checkStringFormatCall(JavaContext context, PsiMethod calledMethod, UCallExpression call, boolean specifiesLocale) {
    int argIndex = specifiesLocale ? 1 : 0;
    List<UExpression> args = call.getValueArguments();
    if (args.size() <= argIndex) {
        return;
    }
    UExpression argument = args.get(argIndex);
    ResourceUrl resource = ResourceEvaluator.getResource(context, argument);
    if (resource == null || resource.framework || resource.type != ResourceType.STRING) {
        return;
    }
    String name = resource.name;
    if (mIgnoreStrings != null && mIgnoreStrings.contains(name)) {
        return;
    }
    boolean passingVarArgsArray = false;
    int callCount = args.size() - 1 - argIndex;
    if (callCount == 1) {
        // If instead of a varargs call like
        //    getString(R.string.foo, arg1, arg2, arg3)
        // the code is calling the varargs method with a packed Object array, as in
        //    getString(R.string.foo, new Object[] { arg1, arg2, arg3 })
        // we'll need to handle that such that we don't think this is a single
        // argument
        UExpression lastArg = args.get(args.size() - 1);
        PsiParameterList parameterList = calledMethod.getParameterList();
        int parameterCount = parameterList.getParametersCount();
        if (parameterCount > 0 && parameterList.getParameters()[parameterCount - 1].isVarArgs()) {
            boolean knownArity = false;
            boolean argWasReference = false;
            if (lastArg instanceof UReferenceExpression) {
                PsiElement resolved = ((UReferenceExpression) lastArg).resolve();
                if (resolved instanceof PsiVariable) {
                    UExpression initializer = context.getUastContext().getInitializerBody((PsiVariable) resolved);
                    if (initializer != null && (UastExpressionUtils.isNewArray(initializer) || UastExpressionUtils.isArrayInitializer(initializer))) {
                        argWasReference = true;
                        // Now handled by check below
                        lastArg = initializer;
                    }
                }
            }
            if (UastExpressionUtils.isNewArray(lastArg) || UastExpressionUtils.isArrayInitializer(lastArg)) {
                UCallExpression arrayInitializer = (UCallExpression) lastArg;
                if (UastExpressionUtils.isNewArrayWithInitializer(lastArg) || UastExpressionUtils.isArrayInitializer(lastArg)) {
                    callCount = arrayInitializer.getValueArgumentCount();
                    knownArity = true;
                } else if (UastExpressionUtils.isNewArrayWithDimensions(lastArg)) {
                    List<UExpression> arrayDimensions = arrayInitializer.getValueArguments();
                    if (arrayDimensions.size() == 1) {
                        UExpression first = arrayDimensions.get(0);
                        if (first instanceof ULiteralExpression) {
                            Object o = ((ULiteralExpression) first).getValue();
                            if (o instanceof Integer) {
                                callCount = (Integer) o;
                                knownArity = true;
                            }
                        }
                    }
                }
                if (!knownArity) {
                    if (!argWasReference) {
                        return;
                    }
                } else {
                    passingVarArgsArray = true;
                }
            }
        }
    }
    if (callCount > 0 && mNotFormatStrings.containsKey(name)) {
        checkNotFormattedHandle(context, call, name, mNotFormatStrings.get(name));
        return;
    }
    List<Pair<Handle, String>> list = mFormatStrings != null ? mFormatStrings.get(name) : null;
    if (list == null) {
        LintClient client = context.getClient();
        if (client.supportsProjectResources() && !context.getScope().contains(Scope.RESOURCE_FILE)) {
            AbstractResourceRepository resources = client.getProjectResources(context.getMainProject(), true);
            List<ResourceItem> items;
            if (resources != null) {
                items = resources.getResourceItem(ResourceType.STRING, name);
            } else {
                // Must be a non-Android module
                items = null;
            }
            if (items != null) {
                for (final ResourceItem item : items) {
                    ResourceValue v = item.getResourceValue(false);
                    if (v != null) {
                        String value = v.getRawXmlValue();
                        if (value != null) {
                            // Make sure it's really a formatting string,
                            // not for example "Battery remaining: 90%"
                            boolean isFormattingString = value.indexOf('%') != -1;
                            for (int j = 0, m = value.length(); j < m && isFormattingString; j++) {
                                char c = value.charAt(j);
                                if (c == '\\') {
                                    j++;
                                } else if (c == '%') {
                                    Matcher matcher = FORMAT.matcher(value);
                                    if (!matcher.find(j)) {
                                        isFormattingString = false;
                                    } else {
                                        String conversion = matcher.group(6);
                                        int conversionClass = getConversionClass(conversion.charAt(0));
                                        if (conversionClass == CONVERSION_CLASS_UNKNOWN || matcher.group(5) != null) {
                                            // Some date format etc - don't process
                                            return;
                                        }
                                    }
                                    // Don't process second % in a %%
                                    j++;
                                }
                            // If the user marked the string with
                            }
                            Handle handle = client.createResourceItemHandle(item);
                            if (isFormattingString) {
                                if (list == null) {
                                    list = Lists.newArrayList();
                                    if (mFormatStrings == null) {
                                        mFormatStrings = Maps.newHashMap();
                                    }
                                    mFormatStrings.put(name, list);
                                }
                                list.add(Pair.of(handle, value));
                            } else if (callCount > 0) {
                                checkNotFormattedHandle(context, call, name, handle);
                            }
                        }
                    }
                }
            }
        } else {
            return;
        }
    }
    if (list != null) {
        Set<String> reported = null;
        for (Pair<Handle, String> pair : list) {
            String s = pair.getSecond();
            if (reported != null && reported.contains(s)) {
                continue;
            }
            int count = getFormatArgumentCount(s, null);
            Handle handle = pair.getFirst();
            if (count != callCount) {
                Location location = context.getUastLocation(call);
                Location secondary = handle.resolve();
                secondary.setMessage(String.format("This definition requires %1$d arguments", count));
                location.setSecondary(secondary);
                String message = String.format("Wrong argument count, format string `%1$s` requires `%2$d` but format " + "call supplies `%3$d`", name, count, callCount);
                context.report(ARG_TYPES, call, location, message);
                if (reported == null) {
                    reported = Sets.newHashSet();
                }
                reported.add(s);
            } else {
                if (passingVarArgsArray) {
                    // flag parameters on the Object[] instead of the wrapped parameters
                    return;
                }
                for (int i = 1; i <= count; i++) {
                    int argumentIndex = i + argIndex;
                    PsiType type = args.get(argumentIndex).getExpressionType();
                    if (type != null) {
                        boolean valid = true;
                        String formatType = getFormatArgumentType(s, i);
                        if (formatType == null) {
                            continue;
                        }
                        char last = formatType.charAt(formatType.length() - 1);
                        if (formatType.length() >= 2 && Character.toLowerCase(formatType.charAt(formatType.length() - 2)) == 't') {
                            // TODO
                            continue;
                        }
                        switch(last) {
                            // unusual and probably not intended.
                            case 'b':
                            case 'B':
                                valid = isBooleanType(type);
                                break;
                            // Numeric: integer and floats in various formats
                            case 'x':
                            case 'X':
                            case 'd':
                            case 'o':
                            case 'e':
                            case 'E':
                            case 'f':
                            case 'g':
                            case 'G':
                            case 'a':
                            case 'A':
                                valid = isNumericType(type, true);
                                break;
                            case 'c':
                            case 'C':
                                // Unicode character
                                valid = isCharacterType(type);
                                break;
                            case 'h':
                            // Hex print of hash code of objects
                            case 'H':
                            case 's':
                            case 'S':
                                // String. Can pass anything, but warn about
                                // numbers since you may have meant more
                                // specific formatting. Use special issue
                                // explanation for this?
                                valid = !isBooleanType(type) && !isNumericType(type, false);
                                break;
                        }
                        if (!valid) {
                            Location location = context.getUastLocation(args.get(argumentIndex));
                            Location secondary = handle.resolve();
                            secondary.setMessage("Conflicting argument declaration here");
                            location.setSecondary(secondary);
                            String suggestion = null;
                            if (isBooleanType(type)) {
                                suggestion = "`b`";
                            } else if (isCharacterType(type)) {
                                suggestion = "'c'";
                            } else if (PsiType.INT.equals(type) || PsiType.LONG.equals(type) || PsiType.BYTE.equals(type) || PsiType.SHORT.equals(type)) {
                                suggestion = "`d`, 'o' or `x`";
                            } else if (PsiType.FLOAT.equals(type) || PsiType.DOUBLE.equals(type)) {
                                suggestion = "`e`, 'f', 'g' or `a`";
                            } else if (type instanceof PsiClassType) {
                                String fqn = type.getCanonicalText();
                                if (TYPE_INTEGER_WRAPPER.equals(fqn) || TYPE_LONG_WRAPPER.equals(fqn) || TYPE_BYTE_WRAPPER.equals(fqn) || TYPE_SHORT_WRAPPER.equals(fqn)) {
                                    suggestion = "`d`, 'o' or `x`";
                                } else if (TYPE_FLOAT_WRAPPER.equals(fqn) || TYPE_DOUBLE_WRAPPER.equals(fqn)) {
                                    suggestion = "`d`, 'o' or `x`";
                                } else if (TYPE_OBJECT.equals(fqn)) {
                                    suggestion = "'s' or 'h'";
                                }
                            }
                            if (suggestion != null) {
                                suggestion = " (Did you mean formatting character " + suggestion + "?)";
                            } else {
                                suggestion = "";
                            }
                            String canonicalText = type.getCanonicalText();
                            canonicalText = canonicalText.substring(canonicalText.lastIndexOf('.') + 1);
                            String message = String.format("Wrong argument type for formatting argument '#%1$d' " + "in `%2$s`: conversion is '`%3$s`', received `%4$s` " + "(argument #%5$d in method call)%6$s", i, name, formatType, canonicalText, argumentIndex + 1, suggestion);
                            context.report(ARG_TYPES, call, location, message);
                            if (reported == null) {
                                reported = Sets.newHashSet();
                            }
                            reported.add(s);
                        }
                    }
                }
            }
        }
    }
}
Also used : ULiteralExpression(org.jetbrains.uast.ULiteralExpression) Matcher(java.util.regex.Matcher) UCallExpression(org.jetbrains.uast.UCallExpression) AbstractResourceRepository(com.android.ide.common.res2.AbstractResourceRepository) ResourceValue(com.android.ide.common.rendering.api.ResourceValue) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) NodeList(org.w3c.dom.NodeList) PsiParameterList(com.intellij.psi.PsiParameterList) ResourceUrl(com.android.ide.common.resources.ResourceUrl) PsiElement(com.intellij.psi.PsiElement) Pair(com.android.utils.Pair) PsiType(com.intellij.psi.PsiType) PsiVariable(com.intellij.psi.PsiVariable) LintClient(com.android.tools.klint.client.api.LintClient) Handle(com.android.tools.klint.detector.api.Location.Handle) UExpression(org.jetbrains.uast.UExpression) PsiClassType(com.intellij.psi.PsiClassType) UReferenceExpression(org.jetbrains.uast.UReferenceExpression) PsiParameterList(com.intellij.psi.PsiParameterList) ResourceItem(com.android.ide.common.res2.ResourceItem) Location(com.android.tools.klint.detector.api.Location)

Example 84 with PsiType

use of com.intellij.psi.PsiType in project android by JetBrains.

the class PsiCFGPartialMethodSignature method hashCode.

@Override
public int hashCode() {
    int retHash = 0;
    retHash += methodName.hashCode();
    if (parameterTypes != null) {
        //Calculate the hash
        for (PsiType curType : parameterTypes) {
            retHash = retHash % BIG_PRIME;
            retHash *= 3;
            retHash += curType.hashCode();
        }
    }
    //Calculate the hash
    if (isVarArgs) {
        retHash >>= 1;
        retHash = retHash % BIG_PRIME;
        retHash *= 3;
    }
    return retHash;
}
Also used : PsiType(com.intellij.psi.PsiType)

Example 85 with PsiType

use of com.intellij.psi.PsiType in project android-parcelable-intellij-plugin by mcharmas.

the class MapSerializer method writeValue.

@Override
public String writeValue(SerializableValue field, String parcel, String flags) {
    final List<PsiType> resolvedGenerics = PsiUtils.getResolvedGenerics(field.getType());
    PsiType keyType = resolvedGenerics.get(1);
    PsiType valueType = resolvedGenerics.get(0);
    final String fieldName = field.getName();
    return new StringBuilder().append(parcel).append(".writeInt(").append(fieldName).append(".size());").append(String.format("for(Map.Entry<%s,%s> entry : %s.entrySet()) {", keyType.getCanonicalText(), valueType.getCanonicalText(), field.getName())).append(typeSerializerFactory.getSerializer(keyType).writeValue(SerializableValue.statement("entry.getKey()", keyType), parcel, flags)).append(typeSerializerFactory.getSerializer(valueType).writeValue(SerializableValue.statement("entry.getValue()", valueType), parcel, flags)).append("}").toString();
}
Also used : PsiType(com.intellij.psi.PsiType)

Aggregations

PsiType (com.intellij.psi.PsiType)157 PsiElement (com.intellij.psi.PsiElement)34 Nullable (org.jetbrains.annotations.Nullable)24 GrExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression)24 NotNull (org.jetbrains.annotations.NotNull)21 PsiClassType (com.intellij.psi.PsiClassType)20 PsiClass (com.intellij.psi.PsiClass)14 GrReferenceExpression (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)13 PsiPrimitiveType (com.intellij.psi.PsiPrimitiveType)12 ArrayList (java.util.ArrayList)9 GrTypeElement (org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement)9 PsiArrayType (com.intellij.psi.PsiArrayType)7 PsiExpression (com.intellij.psi.PsiExpression)7 PsiField (com.intellij.psi.PsiField)7 NonNls (org.jetbrains.annotations.NonNls)7 GrVariable (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable)7 PsiLiteralExpression (com.intellij.psi.PsiLiteralExpression)6 PsiMethod (com.intellij.psi.PsiMethod)6 GrStatement (org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement)6 GrLiteral (org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral)6