Java Code Examples for com.strobel.assembler.metadata.TypeReference

The following examples show how to use com.strobel.assembler.metadata.TypeReference. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: huntbugs   Author: amaembo   File: Types.java    License: Apache License 2.0 6 votes vote down vote up
public static TypeReference mergeTypes(TypeReference t1, TypeReference t2) {
    if (t1 == null || t2 == null)
        return null;
    if (t1 == BuiltinTypes.Null)
        return t2;
    if (t2 == BuiltinTypes.Null)
        return t1;
    if (t1.isEquivalentTo(t2))
        return t1;
    if(t1.isArray() ^ t2.isArray())
        return null;
    if(t1.isArray()) {
        TypeReference merged = mergeTypes(t1.getElementType(), t2.getElementType());
        return merged == null ? null : merged.makeArrayType();
    }
    List<TypeReference> chain1 = getBaseTypes(t1);
    List<TypeReference> chain2 = getBaseTypes(t2);
    for (int i = Math.min(chain1.size(), chain2.size()) - 1; i >= 0; i--) {
        if (chain1.get(i).equals(chain2.get(i)))
            return chain1.get(i);
    }
    return null;
}
 
Example #2
Source Project: huntbugs   Author: amaembo   File: CovariantArrays.java    License: Apache License 2.0 6 votes vote down vote up
private boolean allImplementationsDerivedFromSubclass(Hierarchy h, TypeReference superClass,
        TypeReference subClass) {
    TypeDefinition td = superClass.resolve();
    if(td == null || (!td.isInterface() && !Flags.testAny(td.getFlags(), Flags.ABSTRACT)) )
        return false;
    for(TypeHierarchy th : h.get(td).getSubClasses()) {
        if(subClass.getInternalName().equals(th.getInternalName()))
            continue;
        if(th.hasFlag(Flags.INTERFACE) || th.hasFlag(Flags.ABSTRACT))
            continue;
        TypeReference subType = td.getResolver().lookupType(th.getInternalName());
        if(subType == null || Types.isInstance(subType, subClass))
            continue;
        return false;
    }
    return true;
}
 
Example #3
Source Project: huntbugs   Author: amaembo   File: LockProblems.java    License: Apache License 2.0 6 votes vote down vote up
@AstVisitor(nodes = AstNodes.EXPRESSIONS)
public void visit(Expression expr, MethodContext mc) {
    if (expr.getCode() != AstCode.InvokeVirtual)
        return;
    MethodReference mr = (MethodReference) expr.getOperand();
    String name = mr.getName();
    if (!Types.isObject(mr.getDeclaringType()) || (!name.equals("wait") && !name.startsWith("notify")))
        return;
    TypeReference type = ValuesFlow.reduceType(expr.getArguments().get(0));
    if (type == null || !type.getInternalName().startsWith("java/util/concurrent/"))
        return;
    TypeDefinition target = type.resolve();
    if (target == null || !target.isPublic())
        return;
    MethodDefinition replacement = findReplacement(name, target);
    if(replacement != null) {
        mc.report("IncorrectConcurrentMethod", 0, expr, TARGET.create(target), Roles.REPLACEMENT_METHOD.create(replacement));
    }
}
 
Example #4
Source Project: huntbugs   Author: amaembo   File: SerializationIdiom.java    License: Apache License 2.0 6 votes vote down vote up
@ClassVisitor
public void visitClass(TypeDefinition td, ClassContext cc) {
    isSerializable = Types.isInstance(td, "java/io/Serializable");
    if(Types.isInstance(td, "java/util/Comparator") && !td.isAnonymous() && !td.isLocalClass()
            && !isSerializable) {
        int priority = 0;
        for(FieldDefinition fd : td.getDeclaredFields()) {
            TypeReference fieldType = fd.getFieldType();
            while(fieldType.isArray())
                fieldType = fieldType.getElementType();
            if(fieldType.isPrimitive())
                continue;
            if(Types.isInstance(fieldType, "java/io/Serializable")) {
                priority+=10;
                if(priority > 20)
                    break;
            }
        }
        cc.report("ComparatorIsNotSerializable", priority, SHOULD_IMPLEMENT.create("java/io/Serializable"));
    }
}
 
Example #5
Source Project: huntbugs   Author: amaembo   File: Naming.java    License: Apache License 2.0 6 votes vote down vote up
@ClassVisitor
public void visitClass(TypeDefinition td, ClassContext cc) {
    if (td.isAnonymous() || td.isSynthetic())
        return;
    String name = td.getSimpleName();
    if (Character.isLetter(name.charAt(0)) && !Character.isUpperCase(name.charAt(0)) && name.indexOf('_') == -1) {
        cc.report("BadNameOfClass", td.isPublic() ? 0 : 15);
    }
    if (name.endsWith("Exception") && !Types.isInstance(td, "java/lang/Throwable")) {
        cc.report("BadNameOfClassException", td.isPublic() ? 0 : 15);
    }
    TypeReference superClass = td.getBaseType();
    if (superClass != null && superClass.getSimpleName().equals(name)) {
        cc.report("BadNameOfClassSameAsSuperclass", td.isPublic() ? 0 : 15, Roles.SUPERCLASS.create(superClass));
    }
    for (TypeReference iface : td.getExplicitInterfaces()) {
        if (iface.getSimpleName().equals(name)) {
            cc.report("BadNameOfClassSameAsInterface", td.isPublic() ? 0 : 15, Roles.INTERFACE.create(iface));
        }
    }
}
 
Example #6
Source Project: huntbugs   Author: amaembo   File: NoRuntimeRetention.java    License: Apache License 2.0 6 votes vote down vote up
@AstVisitor(nodes = AstNodes.EXPRESSIONS)
public void visit(Expression expr, MethodContext mc, DeclaredAnnotations da) {
    if (expr.getCode() == AstCode.InvokeVirtual && expr.getArguments().size() == 2) {
        MethodReference mr = (MethodReference) expr.getOperand();
        if ((mr.getDeclaringType().getInternalName().startsWith("java/lang/reflect/") || mr.getDeclaringType()
                .getInternalName().equals("java/lang/Class")) && mr.getName().contains("Annotation")) {
            Object constant = Nodes.getConstant(expr.getArguments().get(1));
            if (constant instanceof TypeReference) {
                TypeReference tr = (TypeReference) constant;
                DeclaredAnnotation annot = da.get(tr);
                if (annot != null && annot.getPolicy() != RetentionPolicy.RUNTIME) {
                    mc.report("AnnotationNoRuntimeRetention", 0, expr, ANNOTATION.create(tr));
                }
            }
        }
    }
}
 
Example #7
Source Project: huntbugs   Author: amaembo   File: ToArrayDowncast.java    License: Apache License 2.0 6 votes vote down vote up
@AstVisitor(nodes = AstNodes.EXPRESSIONS)
public void visit(Expression expr, MethodContext mc) {
    if (expr.getCode() != AstCode.CheckCast)
        return;
    TypeReference targetType = (TypeReference) expr.getOperand();
    if (!targetType.isArray() || Types.isObject(targetType.getElementType()))
        return;
    Expression arg = Exprs.getChild(expr, 0);
    if (arg.getCode() != AstCode.InvokeVirtual && arg.getCode() != AstCode.InvokeInterface)
        return;
    MethodReference mr = (MethodReference) arg.getOperand();
    if (!mr.getName().equals("toArray") || !mr.getSignature().equals("()[Ljava/lang/Object;"))
        return;
    Expression target = Exprs.getChild(arg, 0);
    if (!Types.isInstance(target.getInferredType(), "java/util/Collection"))
        return;
    mc.report("ImpossibleToArrayDowncast", 0, target, Roles.TARGET_TYPE.create(targetType),
        TARGET_ELEMENT_TYPE.create(targetType.getElementType()));
}
 
Example #8
Source Project: huntbugs   Author: amaembo   File: NumericComparison.java    License: Apache License 2.0 6 votes vote down vote up
private JvmType getIntegralType(Expression expression) {
    TypeReference type = expression.getInferredType();
    if (type == null)
        return null;
    JvmType jvmType = type.getSimpleType();
    if (!jvmType.isIntegral())
        return null;
    if (jvmType == JvmType.Integer || jvmType == JvmType.Long)
        return jvmType;
    // Fix procyon type inference
    switch (expression.getCode()) {
    case Add:
    case Sub:
    case Div:
    case Rem:
    case Mul:
    case Shr:
    case Shl:
    case UShr:
    case Neg:
        return JvmType.Integer;
    default:
        return jvmType;
    }
}
 
Example #9
Source Project: huntbugs   Author: amaembo   File: InitializerRefersSubclass.java    License: Apache License 2.0 6 votes vote down vote up
@AstVisitor(nodes=AstNodes.EXPRESSIONS, methodName="<clinit>")
public void visit(Expression expr, NodeChain nc, MethodContext mc, TypeDefinition td) {
    if(expr.getOperand() instanceof MemberReference) {
        MemberReference mr = (MemberReference) expr.getOperand();
        TypeReference tr = mr.getDeclaringType();
        TypeDefinition subType = tr == null ? null : tr.resolve();
        if (subType != null && (subType.isAnonymous() || subType.isLocalClass())) {
            subType = subType.getBaseType().resolve();
        }
        if (subType != null && !td.isEquivalentTo(subType) && Types.isInstance(subType, td) && nc
                .getLambdaMethod() == null) {
            mc.report("InitializerRefersSubclass", td.isNonPublic() || subType.isNonPublic() ? 5 : 0, expr,
                Roles.SUBCLASS.create(subType));
        }
    }
}
 
Example #10
Source Project: huntbugs   Author: amaembo   File: UnnecessaryInstanceOf.java    License: Apache License 2.0 6 votes vote down vote up
private void report(MethodContext mc, TypeReference typeRef, Expression expr, Expression cond, EdgeType deadEdge,
        EType eType, String wType) {
    int priority = 0;
    List<WarningAnnotation<?>> anno = new ArrayList<>(Arrays.asList(Roles.TARGET_TYPE.create(typeRef), ETYPE.create(
        eType.toString()), Roles.EXPRESSION.create(expr)));
    if (deadEdge != null) {
        CodeBlock deadCode = mc.findDeadCode(cond, deadEdge);
        if (deadCode != null) {
            priority = deadCode.isExceptional ? 40 : 0;
            anno.add(Roles.DEAD_CODE_LOCATION.create(mc, deadCode.startExpr));
        } else {
            priority = 20;
        }
    }
    mc.report(wType, priority, expr, anno);
}
 
Example #11
Source Project: huntbugs   Author: amaembo   File: CFG.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void addExceptional(BasicBlock block, TypeReference exception) {
    for (Entry<CatchBlock, BasicBlock> entry : catches.entrySet()) {
        for (TypeReference tr : types(entry.getKey())) {
            if (Types.isInstance(exception, tr)) {
                // Exact match: catch and return
                block.addTarget(EdgeType.FAIL, entry.getValue());
                return;
            } else if (Types.isInstance(tr, exception) || !Types.hasCompleteHierarchy(tr.resolve())) {
                // Inexact match: probably caught here or by another catch block
                block.addTarget(EdgeType.FAIL, entry.getValue());
            }
        }
    }
    super.addExceptional(block, exception);
}
 
Example #12
Source Project: huntbugs   Author: amaembo   File: SingleType.java    License: Apache License 2.0 6 votes vote down vote up
static EType of(TypeReference tr, What what) {
    if (tr == null || tr.isPrimitive() || (what == What.SUBTYPE && Types.isObject(tr)))
        return UNKNOWN;
    TypeDefinition td = tr.resolve();
    if (td == null)
        return UNKNOWN;
    if (td.isFinal() || td.isPrimitive()) {
        if (what == What.SUBTYPE)
            what = What.EXACT;
        if (what == What.NOT)
            what = What.NOT_SUBTYPE;
    }
    TypeReference newTr = td;
    while (tr.isArray()) {
        tr = tr.getElementType();
        newTr = newTr.makeArrayType();
    }
    boolean complete = Types.hasCompleteHierarchy(td);
    return new SingleType(newTr, what, complete);
}
 
Example #13
Source Project: huntbugs   Author: amaembo   File: AndType.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public YesNoMaybe is(TypeReference tr, boolean exact) {
    boolean hasYes = false, hasNo = false;
    for (EType type : types) {
        switch (type.is(tr, exact)) {
        case YES:
            hasYes = true;
            break;
        case NO:
            hasNo = true;
            break;
        default:
        }
    }
    if (hasYes && hasNo)
        return YesNoMaybe.MAYBE;
    if (hasYes)
        return YesNoMaybe.YES;
    if (hasNo)
        return YesNoMaybe.NO;
    return YesNoMaybe.MAYBE;
}
 
Example #14
Source Project: huntbugs   Author: amaembo   File: AndType.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public EType shrinkConstraint(TypeReference tr, boolean exact) {
    Set<SingleType> yes = new HashSet<>(), no = new HashSet<>();
    for (SingleType type : types) {
        switch (type.is(tr, exact)) {
        case YES:
            yes.add(type);
            break;
        case NO:
            no.add(type);
            break;
        default:
        }
    }
    if (!yes.isEmpty() && !no.isEmpty())
        return this;
    if (!yes.isEmpty())
        return of(yes);
    if (!no.isEmpty())
        return of(no);
    return this;
}
 
Example #15
Source Project: huntbugs   Author: amaembo   File: Nodes.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean isUnboxing(Node node) {
    if (!isOp(node, AstCode.InvokeVirtual))
        return false;
    MethodReference ref = (MethodReference) ((Expression) node).getOperand();
    TypeReference type = ref.getDeclaringType();
    if (type.getInternalName().equals("java/lang/Double") && ref.getName().equals("doubleValue"))
        return true;
    if (type.getInternalName().equals("java/lang/Integer") && ref.getName().equals("intValue"))
        return true;
    if (type.getInternalName().equals("java/lang/Long") && ref.getName().equals("longValue"))
        return true;
    if (type.getInternalName().equals("java/lang/Boolean") && ref.getName().equals("booleanValue"))
        return true;
    if (type.getInternalName().equals("java/lang/Short") && ref.getName().equals("shortValue"))
        return true;
    if (type.getInternalName().equals("java/lang/Character") && ref.getName().equals("charValue"))
        return true;
    if (type.getInternalName().equals("java/lang/Float") && ref.getName().equals("floatValue"))
        return true;
    if (type.getInternalName().equals("java/lang/Byte") && ref.getName().equals("byteValue"))
        return true;
    return false;
}
 
Example #16
Source Project: huntbugs   Author: amaembo   File: Types.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean isInstance(TypeReference type, String wantedType) {
    if (type == null || type.isPrimitive())
        return false;
    if (wantedType.equals("java/lang/Object"))
        return true;
    if (type.getInternalName().equals(wantedType))
        return true;
    if (type.isArray()) {
        if(!wantedType.startsWith("["))
            return false;
        return isInstance(type.getElementType(), wantedType.substring(1));
    }
    TypeDefinition td = type.resolve();
    if (td == null)
        return false;
    for (TypeReference iface : td.getExplicitInterfaces()) {
        if (isInstance(iface, wantedType))
            return true;
    }
    TypeReference bt = td.getBaseType();
    if (bt == null)
        return false;
    return isInstance(bt, wantedType);
}
 
Example #17
Source Project: Luyten   Author: deathmarine   File: DecompilerLinkProvider.java    License: Apache License 2.0 5 votes vote down vote up
private String getPathAndTypeStr(TypeReference typeRef) {
	String name = typeRef.getName();
	String packageStr = typeRef.getPackageName();
	TypeReference mostOuterTypeRef = getMostOuterTypeRef(typeRef);
	String mostOuterTypeName = mostOuterTypeRef.getName();
	if (name != null && packageStr != null && mostOuterTypeName != null && name.trim().length() > 0
			&& mostOuterTypeName.trim().length() > 0) {
		String pathStr = packageStr.replaceAll("\\.", "/") + "/" + mostOuterTypeName;
		String typeStr = packageStr + "." + name.replace(".", "$");
		return pathStr + "|" + typeStr;
	}
	return null;
}
 
Example #18
Source Project: huntbugs   Author: amaembo   File: CovariantArrays.java    License: Apache License 2.0 5 votes vote down vote up
private TypeReference toRawType(TypeReference type) {
    if(type.hasExtendsBound())
        return toRawType(type.getExtendsBound());
    if(type.hasSuperBound())
        return BuiltinTypes.Object;
    if(type instanceof GenericParameter)
        return toRawType(type.getUnderlyingType());
    if(!type.isGenericType())
        return type;
    try {
        return type.getRawType();
    } catch (UnsupportedOperationException e) {
        return BuiltinTypes.Object;
    }
}
 
Example #19
Source Project: huntbugs   Author: amaembo   File: FloatingPointComparison.java    License: Apache License 2.0 5 votes vote down vote up
@AstVisitor(nodes=AstNodes.EXPRESSIONS)
public void visit(Expression node, MethodContext ctx, MethodDefinition md) {
    if (node.getCode() != AstCode.CmpEq && node.getCode() != AstCode.CmpNe)
        return;
    List<Expression> args = node.getArguments();
    TypeReference inferredType = args.get(0).getInferredType();
    if(inferredType == null)
        return;
    JvmType type = inferredType.getSimpleType();
    if (type != JvmType.Double && type != JvmType.Float)
        return;
    Expression leftArg = Exprs.getChild(node, 0);
    Expression rightArg = Exprs.getChild(node, 1);
    Object left = Nodes.getConstant(leftArg);
    Object right = Nodes.getConstant(rightArg);
    int priority = tweakPriority(args.get(0)) + tweakPriority(args.get(1));
    if(ValuesFlow.anyMatch(leftArg, rightArg::equals) || ValuesFlow.anyMatch(rightArg, leftArg::equals))
        priority += 20;
    String lcName = md.getName().toLowerCase(Locale.ENGLISH);
    if (lcName.contains("equal") || lcName.contains("compare"))
        priority += 20;
    Number n = left instanceof Number ? (Number) left : right instanceof Number ? (Number) right : null;
    if(n != null)
        ctx.report("FloatComparison", priority, node, Roles.NUMBER.create(n));
    else
        ctx.report("FloatComparison", priority, node);
}
 
Example #20
Source Project: huntbugs   Author: amaembo   File: DubiousCatch.java    License: Apache License 2.0 5 votes vote down vote up
@AstVisitor
public void visit(Node node, MethodContext mc) {
    if(node instanceof CatchBlock) {
        CatchBlock block = (CatchBlock)node;
        List<TypeReference> exceptions = block.getCaughtTypes();
        if(exceptions.isEmpty() && block.getExceptionType() != null)
            exceptions = Collections.singletonList(block.getExceptionType());
        for(TypeReference type : exceptions) {
            String warningType = EXCEPTION_TO_WARNING.get(type.getInternalName());
            if(warningType != null) {
                mc.report(warningType, 0, node, Roles.EXCEPTION.create(type));
            }
        }
    }
}
 
Example #21
Source Project: huntbugs   Author: amaembo   File: UnnecessaryBoxing.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isBoxedToString(Expression expr) {
    if (expr.getCode() == AstCode.InvokeVirtual) {
        MethodReference mr = (MethodReference) expr.getOperand();
        if (mr.getName().equals("toString") && mr.getSignature().equals("()Ljava/lang/String;")) {
            TypeReference type = mr.getDeclaringType();
            if (Types.isBoxed(type)) {
                return true;
            }
        }
    }
    return false;
}
 
Example #22
Source Project: huntbugs   Author: amaembo   File: WrongMapIterator.java    License: Apache License 2.0 5 votes vote down vote up
@AstVisitor(nodes = AstNodes.EXPRESSIONS)
public void visit(Expression expr, NodeChain nc, MethodContext mc) {
    MethodReference getMr = getCalledMethod(expr);
    if (getMr == null || !getMr.getName().equals("get"))
        return;
    Expression mapArg = Exprs.getChildNoSpecial(expr, 0);
    TypeReference type = ValuesFlow.reduceType(Exprs.getChild(expr, 0));
    if (!Types.isInstance(type, "java/util/Map") || Types.isInstance(type, "java/util/EnumMap"))
        return;
    Expression key = Exprs.getChild(expr, 1);
    while (key.getCode() == AstCode.CheckCast || Nodes.isBoxing(key) || Nodes.isUnboxing(key))
        key = Exprs.getChild(key, 0);
    MethodReference nextMr = getCalledMethod(key);
    if (nextMr == null || !nextMr.getName().equals("next") || !Types.is(nextMr.getDeclaringType(), Iterator.class))
        return;
    Expression iter = Exprs.getChild(key, 0);
    MethodReference iterMr = getCalledMethod(iter);
    if (iterMr == null || !iterMr.getName().equals("iterator"))
        return;
    Expression keySet = Exprs.getChild(iter, 0);
    MethodReference keySetMr = getCalledMethod(keySet);
    if (keySetMr == null || !keySetMr.getName().equals("keySet"))
        return;
    if (!Nodes.isEquivalent(mapArg, Exprs.getChildNoSpecial(keySet, 0)))
        return;
    int priority = nc.isInLoop() ? 0 : 15;
    if(mc.isAnnotated() && usedForGetOnly(key, mapArg)) {
        mc.report("WrongMapIteratorValues", priority, expr, Roles.REPLACEMENT_METHOD.create("java/util/Map", "values", "()Ljava/util/Collection;"));
    } else {
        mc.report("WrongMapIterator", priority, expr, Roles.REPLACEMENT_METHOD.create("java/util/Map", "entrySet", "()Ljava/util/Set;"));
    }
}
 
Example #23
Source Project: huntbugs   Author: amaembo   File: BadMethodReferences.java    License: Apache License 2.0 5 votes vote down vote up
private void check(MethodHandle handle, TypeReference functionalInterface, MethodContext mc, Expression expr) {
    if(functionalInterface.getInternalName().equals("java/util/Comparator") && handle.getHandleType() == MethodHandleType.InvokeStatic) {
        MethodReference mr = handle.getMethod();
        if((mr.getName().equals("min") || mr.getName().equals("max")) && mr.getDeclaringType().getPackageName().equals("java.lang")) {
            mc.report("MaxMinMethodReferenceForComparator", 0, expr, Roles.METHOD_REFERENCE.create(mr));
        }
    }
}
 
Example #24
Source Project: huntbugs   Author: amaembo   File: StaticFieldNonThreadSafe.java    License: Apache License 2.0 5 votes vote down vote up
@FieldVisitor
public void visitField(FieldDefinition fd, FieldContext fc, TypeDefinition td) {
    if((fd.isPublic() || fd.isProtected()) && (td.isPublic() || td.isProtected()) &&
            fd.isStatic() && !fd.isEnumConstant()) {
        TypeReference fieldType = fd.getFieldType();
        if(!isNotThreadSafe(fieldType))
            return;
        fc.report("StaticNotThreadSafeField", AccessLevel.of(fd).select(0, 20, 100, 100),
            Roles.FIELD_TYPE.create(fieldType));
    }
}
 
Example #25
Source Project: huntbugs   Author: amaembo   File: RedundantInterfaces.java    License: Apache License 2.0 5 votes vote down vote up
@ClassVisitor
public void visit(TypeDefinition td, ClassContext cc) {
    TypeDefinition baseType = td.getBaseType().resolve();
    if(baseType == null || Types.isObject(baseType))
        return;
    for(TypeReference tr : td.getExplicitInterfaces()) {
        if(tr.getInternalName().equals("java/io/Serializable")) {
            continue;
        }
        if(Types.isInstance(baseType, tr)) {
            cc.report("RedundantInterface", td.isPublic() ? 0 : 10, Roles.INTERFACE.create(tr));
        }
    }
}
 
Example #26
Source Project: huntbugs   Author: amaembo   File: RandomUsage.java    License: Apache License 2.0 5 votes vote down vote up
void checkOnlyOnce(Expression node, MethodContext ctx) {
    if (node.getCode() != AstCode.InvokeVirtual || node.getArguments().get(0).getCode() != AstCode.InitObject)
        return;
    MethodReference ctor = (MethodReference) node.getArguments().get(0).getOperand();
    TypeReference type = ctor.getDeclaringType();
    if (!Types.isRandomClass(type) || type.getInternalName().equals("java/security/SecureRandom"))
        return;
    MethodReference mr = (MethodReference) node.getOperand();
    if(mr.getReturnType().getPackageName().equals("java.util.stream"))
        return;
    if(Inf.BACKLINK.findTransitiveUsages(node, true).allMatch(this::isRandomInit))
        return;
    ctx.report("RandomUsedOnlyOnce", 0, node, RANDOM_TYPE.create(type));
}
 
Example #27
Source Project: huntbugs   Author: amaembo   File: IgnoredException.java    License: Apache License 2.0 5 votes vote down vote up
@AstVisitor
public void visit(Node node, MethodContext mc) {
    if(node instanceof CatchBlock) {
        CatchBlock cb = (CatchBlock)node;
        TypeReference tr = cb.getExceptionType();
        if(tr != null && isTrivial(cb.getBody(), cb.getExceptionVariable())) {
            int priority = getExceptionPriority(tr);
            if(priority >= 0) {
                mc.report("IgnoredException", priority, node, Roles.EXCEPTION.create(tr));
            }
        }
    }
}
 
Example #28
Source Project: huntbugs   Author: amaembo   File: IgnoredException.java    License: Apache License 2.0 5 votes vote down vote up
private static int getExceptionPriority(TypeReference tr) {
    switch(tr.getInternalName()) {
    case "java/lang/Throwable":
        return 0;
    case "java/lang/Error":
        return 1;
    case "java/lang/Exception":
        return 5;
    case "java/lang/RuntimeException":
        return 7;
    default:
        return -1;
    }
}
 
Example #29
Source Project: Luyten   Author: deathmarine   File: Model.java    License: Apache License 2.0 5 votes vote down vote up
public void navigateTo(final String uniqueStr) {
	new Thread(new Runnable() {
		@Override
		public void run() {
			if (uniqueStr == null)
				return;
			String[] linkParts = uniqueStr.split("\\|");
			if (linkParts.length <= 1)
				return;
			String destinationTypeStr = linkParts[1];
			try {
				bar.setVisible(true);
				getLabel().setText("Navigating: " + destinationTypeStr.replaceAll("/", "."));

				TypeReference type = metadataSystem.lookupType(destinationTypeStr);
				if (type == null)
					throw new RuntimeException("Cannot lookup type: " + destinationTypeStr);
				TypeDefinition typeDef = type.resolve();
				if (typeDef == null)
					throw new RuntimeException("Cannot resolve type: " + destinationTypeStr);

				String tabTitle = typeDef.getName() + ".class";
				extractClassToTextPane(typeDef, tabTitle, destinationTypeStr, uniqueStr);

				getLabel().setText("Complete");
			} catch (Exception e) {
				getLabel().setText("Cannot navigate: " + destinationTypeStr.replaceAll("/", "."));
				Luyten.showExceptionDialog("Cannot Navigate!", e);
			} finally {
				bar.setVisible(false);
			}
		}
	}).start();
}
 
Example #30
Source Project: huntbugs   Author: amaembo   File: RedundantStreamCalls.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isStreamFilter(MethodReference mr) {
    if(!mr.getName().equals("filter") || mr.getParameters().size() != 1)
        return false;
    TypeReference type = mr.getParameters().get(0).getParameterType();
    return type.getSimpleName().endsWith("Predicate") && type.getPackageName().equals("java.util.function")
            && Types.isBaseStream(mr.getDeclaringType());
}