Java源码示例:com.sun.tools.javac.code.Lint.LintCategory

示例1
public boolean returnTypeSubstitutable(Type r1,
                                       Type r2, Type r2res,
                                       Warner warner) {
    if (isSameType(r1.getReturnType(), r2res))
        return true;
    if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
        return false;

    if (hasSameArgs(r1, r2))
        return covariantReturnType(r1.getReturnType(), r2res, warner);
    if (!allowCovariantReturns)
        return false;
    if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
        return true;
    if (!isSubtype(r1.getReturnType(), erasure(r2res)))
        return false;
    warner.warn(LintCategory.UNCHECKED);
    return true;
}
 
示例2
protected boolean accepts(AttributeKind kind) {
    if (kinds.contains(kind)) {
        if (majorVersion > version.major || (majorVersion == version.major && minorVersion >= version.minor))
            return true;

        if (lintClassfile && !warnedAttrs.contains(name)) {
            JavaFileObject prev = log.useSource(currentClassFile);
            try {
                log.warning(LintCategory.CLASSFILE, (DiagnosticPosition) null, "future.attr",
                        name, version.major, version.minor, majorVersion, minorVersion);
            } finally {
                log.useSource(prev);
            }
            warnedAttrs.add(name);
        }
    }
    return false;
}
 
示例3
/** Check for redundant casts (i.e. where source type is a subtype of target type)
 * The problem should only be reported for non-292 cast
 */
public void checkRedundantCast(Env<AttrContext> env, final JCTypeCast tree) {
    if (!tree.type.isErroneous()
            && types.isSameType(tree.expr.type, tree.clazz.type)
            && !(ignoreAnnotatedCasts && TreeInfo.containsTypeAnnotation(tree.clazz))
            && !is292targetTypeCast(tree)) {
        deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
            @Override
            public void report() {
                if (lint.isEnabled(Lint.LintCategory.CAST))
                    log.warning(Lint.LintCategory.CAST,
                            tree.pos(), "redundant.cast", tree.expr.type);
            }
        });
    }
}
 
示例4
@Override
public Boolean visitTypeVar(TypeVar t, Type s) {
    switch (s.getTag()) {
    case ERROR:
    case BOT:
        return true;
    case TYPEVAR:
        if (isSubtype(t, s)) {
            return true;
        } else if (isCastable(t.bound, s, noWarnings)) {
            warnStack.head.warn(LintCategory.UNCHECKED);
            return true;
        } else {
            return false;
        }
    default:
        return isCastable(t.bound, s, warnStack.head);
    }
}
 
示例5
boolean accepts(AttributeKind kind) {
    if (kinds.contains(kind)) {
        if (majorVersion > version.major || (majorVersion == version.major && minorVersion >= version.minor))
            return true;

        if (lintClassfile && !warnedAttrs.contains(name)) {
            JavaFileObject prev = log.useSource(currentClassFile);
            try {
                log.warning(LintCategory.CLASSFILE, (DiagnosticPosition) null, "future.attr",
                        name, version.major, version.minor, majorVersion, minorVersion);
            } finally {
                log.useSource(prev);
            }
            warnedAttrs.add(name);
        }
    }
    return false;
}
 
示例6
@Override
public void warn(LintCategory lint) {
    boolean warned = this.warned;
    super.warn(lint);
    if (warned) return; // suppress redundant diagnostics
    switch (lint) {
        case UNCHECKED:
            Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
            break;
        case VARARGS:
            if (method != null &&
                    method.attribute(syms.trustMeType.tsym) != null &&
                    isTrustMeAllowedOnMethod(method) &&
                    !types.isReifiable(method.type.getParameterTypes().last())) {
                Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
            }
            break;
        default:
            throw new AssertionError("Unexpected lint: " + lint);
    }
}
 
示例7
/** Check for redundant casts (i.e. where source type is a subtype of target type)
 * The problem should only be reported for non-292 cast
 */
public void checkRedundantCast(Env<AttrContext> env, final JCTypeCast tree) {
    if (!tree.type.isErroneous()
            && types.isSameType(tree.expr.type, tree.clazz.type)
            && !(ignoreAnnotatedCasts && TreeInfo.containsTypeAnnotation(tree.clazz))
            && !is292targetTypeCast(tree)) {
        deferredLintHandler.report(new DeferredLintHandler.LintLogger() {
            @Override
            public void report() {
                if (lint.isEnabled(Lint.LintCategory.CAST))
                    log.warning(Lint.LintCategory.CAST,
                            tree.pos(), "redundant.cast", tree.expr.type);
            }
        });
    }
}
 
示例8
@Override
public Boolean visitArrayType(ArrayType t, Type s) {
    switch (s.getTag()) {
    case ERROR:
    case BOT:
        return true;
    case TYPEVAR:
        if (isCastable(s, t, noWarnings)) {
            warnStack.head.warn(LintCategory.UNCHECKED);
            return true;
        } else {
            return false;
        }
    case CLASS:
        return isSubtype(t, s);
    case ARRAY:
        if (elemtype(t).isPrimitive() || elemtype(s).isPrimitive()) {
            return elemtype(t).hasTag(elemtype(s).getTag());
        } else {
            return visit(elemtype(t), elemtype(s));
        }
    default:
        return false;
    }
}
 
示例9
@Override
public void warn(LintCategory lint) {
    boolean warned = this.warned;
    super.warn(lint);
    if (warned) return; // suppress redundant diagnostics
    switch (lint) {
        case UNCHECKED:
            Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
            break;
        case VARARGS:
            if (method != null &&
                    method.attribute(syms.trustMeType.tsym) != null &&
                    isTrustMeAllowedOnMethod(method) &&
                    !types.isReifiable(method.type.getParameterTypes().last())) {
                Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
            }
            break;
        default:
            throw new AssertionError("Unexpected lint: " + lint);
    }
}
 
示例10
@Override
public void warn(LintCategory lint) {
    boolean warned = this.warned;
    super.warn(lint);
    if (warned) return; // suppress redundant diagnostics
    switch (lint) {
        case UNCHECKED:
            Check.this.warnUnchecked(pos(), "prob.found.req", diags.fragment(uncheckedKey), found, expected);
            break;
        case VARARGS:
            if (method != null &&
                    method.attribute(syms.trustMeType.tsym) != null &&
                    isTrustMeAllowedOnMethod(method) &&
                    !types.isReifiable(method.type.getParameterTypes().last())) {
                Check.this.warnUnsafeVararg(pos(), "varargs.unsafe.use.varargs.param", method.params.last());
            }
            break;
        default:
            throw new AssertionError("Unexpected lint: " + lint);
    }
}
 
示例11
private void checkClassOverrideEqualsAndHash(DiagnosticPosition pos,
        ClassSymbol someClass) {
    if (lint.isEnabled(LintCategory.OVERRIDES)) {
        MethodSymbol equalsAtObject = (MethodSymbol)syms.objectType
                .tsym.members().findFirst(names.equals);
        MethodSymbol hashCodeAtObject = (MethodSymbol)syms.objectType
                .tsym.members().findFirst(names.hashCode);
        boolean overridesEquals = types.implementation(equalsAtObject,
            someClass, false, equalsHasCodeFilter).owner == someClass;
        boolean overridesHashCode = types.implementation(hashCodeAtObject,
            someClass, false, equalsHasCodeFilter) != hashCodeAtObject;

        if (overridesEquals && !overridesHashCode) {
            log.warning(LintCategory.OVERRIDES, pos,
                    "override.equals.but.not.hashcode", someClass);
        }
    }
}
 
示例12
private void checkClassOverrideEqualsAndHash(DiagnosticPosition pos,
        ClassSymbol someClass) {
    if (lint.isEnabled(LintCategory.OVERRIDES)) {
        MethodSymbol equalsAtObject = (MethodSymbol)syms.objectType
                .tsym.members().lookup(names.equals).sym;
        MethodSymbol hashCodeAtObject = (MethodSymbol)syms.objectType
                .tsym.members().lookup(names.hashCode).sym;
        boolean overridesEquals = types.implementation(equalsAtObject,
            someClass, false, equalsHasCodeFilter).owner == someClass;
        boolean overridesHashCode = types.implementation(hashCodeAtObject,
            someClass, false, equalsHasCodeFilter) != hashCodeAtObject;

        if (overridesEquals && !overridesHashCode) {
            log.warning(LintCategory.OVERRIDES, pos,
                    "override.equals.but.not.hashcode", someClass);
        }
    }
}
 
示例13
@Override
public Boolean visitTypeVar(TypeVar t, Type s) {
    switch (s.getTag()) {
    case ERROR:
    case BOT:
        return true;
    case TYPEVAR:
        if (isSubtype(t, s)) {
            return true;
        } else if (isCastable(t.bound, s, noWarnings)) {
            warnStack.head.warn(LintCategory.UNCHECKED);
            return true;
        } else {
            return false;
        }
    default:
        return isCastable(t.bound, s, warnStack.head);
    }
}
 
示例14
/** Check that an auxiliary class is not accessed from any other file than its own.
 */
void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
    if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) &&
        (c.flags() & AUXILIARY) != 0 &&
        rs.isAccessible(env, c) &&
        !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
    {
        log.warning(pos,
                    Warnings.AuxiliaryClassAccessedFromOutsideOfItsSourceFile(c, c.sourcefile));
    }
}
 
示例15
protected Modules(Context context) {
    context.put(Modules.class, this);
    log = Log.instance(context);
    names = Names.instance(context);
    syms = Symtab.instance(context);
    attr = Attr.instance(context);
    chk = Check.instance(context);
    deferredLintHandler = DeferredLintHandler.instance(context);
    typeEnvs = TypeEnvs.instance(context);
    moduleFinder = ModuleFinder.instance(context);
    types = Types.instance(context);
    fileManager = context.get(JavaFileManager.class);
    source = Source.instance(context);
    allowModules = source.allowModules();
    Options options = Options.instance(context);

    allowAccessIntoSystem = options.isUnset(Option.RELEASE);
    lintOptions = options.isUnset(Option.XLINT_CUSTOM, "-" + LintCategory.OPTIONS.option);

    multiModuleMode = fileManager.hasLocation(StandardLocation.MODULE_SOURCE_PATH);
    ClassWriter classWriter = ClassWriter.instance(context);
    classWriter.multiModuleMode = multiModuleMode;
    JNIWriter jniWriter = JNIWriter.instance(context);
    jniWriter.multiModuleMode = multiModuleMode;

    java_se = names.fromString("java.se");
    java_ = names.fromString("java.");

    addExportsOpt = options.get(Option.ADD_EXPORTS);
    addReadsOpt = options.get(Option.ADD_READS);
    addModsOpt = options.get(Option.ADD_MODULES);
    limitModsOpt = options.get(Option.LIMIT_MODULES);
    moduleVersionOpt = options.get(Option.MODULE_VERSION);
}
 
示例16
private boolean sideCast(Type from, Type to, Warner warn) {
    // We are casting from type $from$ to type $to$, which are
    // non-final unrelated types.  This method
    // tries to reject a cast by transferring type parameters
    // from $to$ to $from$ by common superinterfaces.
    boolean reverse = false;
    Type target = to;
    if ((to.tsym.flags() & INTERFACE) == 0) {
        Assert.check((from.tsym.flags() & INTERFACE) != 0);
        reverse = true;
        to = from;
        from = target;
    }
    List<Type> commonSupers = superClosure(to, erasure(from));
    boolean giveWarning = commonSupers.isEmpty();
    // The arguments to the supers could be unified here to
    // get a more accurate analysis
    while (commonSupers.nonEmpty()) {
        Type t1 = asSuper(from, commonSupers.head.tsym);
        Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
        if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
            return false;
        giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
        commonSupers = commonSupers.tail;
    }
    if (giveWarning && !isReifiable(reverse ? from : to))
        warn.warn(LintCategory.UNCHECKED);
    if (!allowCovariantReturns)
        // reject if there is a common method signature with
        // incompatible return types.
        chk.checkCompatibleAbstracts(warn.pos(), from, to);
    return true;
}
 
示例17
/** Check that an auxiliary class is not accessed from any other file than its own.
 */
void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
    if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) &&
        (c.flags() & AUXILIARY) != 0 &&
        rs.isAccessible(env, c) &&
        !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
    {
        log.warning(pos, "auxiliary.class.accessed.from.outside.of.its.source.file",
                    c, c.sourcefile);
    }
}
 
示例18
/**
 * Construct a new class reader, optionally treated as the
 * definitive classreader for this invocation.
 */
protected ClassReader(Context context, boolean definitive) {
    if (definitive) context.put(classReaderKey, this);

    names = Names.instance(context);
    syms = Symtab.instance(context);
    types = Types.instance(context);
    fileManager = context.get(JavaFileManager.class);
    if (fileManager == null)
        throw new AssertionError("FileManager initialization error");
    diagFactory = JCDiagnostic.Factory.instance(context);

    init(syms, definitive);
    log = Log.instance(context);

    Options options = Options.instance(context);
    annotate = Annotate.instance(context);
    verbose = options.isSet(VERBOSE);
    checkClassFile = options.isSet("-checkclassfile");
    Source source = Source.instance(context);
    allowGenerics = source.allowGenerics();
    allowVarargs = source.allowVarargs();
    allowAnnotations = source.allowAnnotations();
    allowSimplifiedVarargs = source.allowSimplifiedVarargs();
    saveParameterNames = options.isSet("save-parameter-names");
    cacheCompletionFailure = options.isUnset("dev");
    preferSource = "source".equals(options.get("-Xprefer"));

    completionFailureName =
            options.isSet("failcomplete")
                    ? names.fromString(options.get("failcomplete"))
                    : null;

    typevars = new Scope(syms.noSymbol);

    lintClassfile = Lint.instance(context).isEnabled(LintCategory.CLASSFILE);

    initAttributeReaders();
}
 
示例19
/** Check for redundant casts (i.e. where source type is a subtype of target type)
 * The problem should only be reported for non-292 cast
 */
public void checkRedundantCast(Env<AttrContext> env, final JCTypeCast tree) {
    if (!tree.type.isErroneous()
            && types.isSameType(tree.expr.type, tree.clazz.type)
            && !(ignoreAnnotatedCasts && TreeInfo.containsTypeAnnotation(tree.clazz))
            && !is292targetTypeCast(tree)) {
        deferredLintHandler.report(() -> {
            if (lint.isEnabled(LintCategory.CAST))
                log.warning(LintCategory.CAST,
                        tree.pos(), "redundant.cast", tree.clazz.type);
        });
    }
}
 
示例20
/**
 *  Check for division by integer constant zero
 *  @param pos           Position for error reporting.
 *  @param operator      The operator for the expression
 *  @param operand       The right hand operand for the expression
 */
void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
    if (operand.constValue() != null
        && lint.isEnabled(LintCategory.DIVZERO)
        && operand.tag <= LONG
        && ((Number) (operand.constValue())).longValue() == 0) {
        int opc = ((OperatorSymbol)operator).opcode;
        if (opc == ByteCodes.idiv || opc == ByteCodes.imod
            || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
            log.warning(LintCategory.DIVZERO, pos, "div.zero");
        }
    }
}
 
示例21
private boolean sideCastFinal(Type from, Type to, Warner warn) {
    // We are casting from type $from$ to type $to$, which are
    // unrelated types one of which is final and the other of
    // which is an interface.  This method
    // tries to reject a cast by transferring type parameters
    // from the final class to the interface.
    boolean reverse = false;
    Type target = to;
    if ((to.tsym.flags() & INTERFACE) == 0) {
        Assert.check((from.tsym.flags() & INTERFACE) != 0);
        reverse = true;
        to = from;
        from = target;
    }
    Assert.check((from.tsym.flags() & FINAL) != 0);
    Type t1 = asSuper(from, to.tsym);
    if (t1 == null) return false;
    Type t2 = to;
    if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
        return false;
    if (!allowCovariantReturns)
        // reject if there is a common method signature with
        // incompatible return types.
        chk.checkCompatibleAbstracts(warn.pos(), from, to);
    if (!isReifiable(target) &&
        (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
        warn.warn(LintCategory.UNCHECKED);
    return true;
}
 
示例22
Type attribImportType(JCTree tree, Env<AttrContext> env) {
    Assert.check(completionEnabled);
    Lint prevLint = chk.setLint(allowDeprecationOnImport ?
            lint : lint.suppress(LintCategory.DEPRECATION, LintCategory.REMOVAL));
    try {
        // To prevent deep recursion, suppress completion of some
        // types.
        completionEnabled = false;
        return attr.attribType(tree, env);
    } finally {
        completionEnabled = true;
        chk.setLint(prevLint);
    }
}
 
示例23
/** Check that an auxiliary class is not accessed from any other file than its own.
 */
void checkForBadAuxiliaryClassAccess(DiagnosticPosition pos, Env<AttrContext> env, ClassSymbol c) {
    if (lint.isEnabled(Lint.LintCategory.AUXILIARYCLASS) &&
        (c.flags() & AUXILIARY) != 0 &&
        rs.isAccessible(env, c) &&
        !fileManager.isSameFile(c.sourcefile, env.toplevel.sourcefile))
    {
        log.warning(pos, "auxiliary.class.accessed.from.outside.of.its.source.file",
                    c, c.sourcefile);
    }
}
 
示例24
void checkRaw(JCTree tree, Env<AttrContext> env) {
    if (lint.isEnabled(LintCategory.RAW) &&
        tree.type.hasTag(CLASS) &&
        !TreeInfo.isDiamond(tree) &&
        !withinAnonConstr(env) &&
        tree.type.isRaw()) {
        log.warning(LintCategory.RAW,
                tree.pos(), "raw.class.use", tree.type, tree.type.tsym.type);
    }
}
 
示例25
void checkDeprecatedAnnotation(DiagnosticPosition pos, Symbol s) {
    if (allowAnnotations &&
        lint.isEnabled(LintCategory.DEP_ANN) &&
        (s.flags() & DEPRECATED) != 0 &&
        !syms.deprecatedType.isErroneous() &&
        s.attribute(syms.deprecatedType.tsym) == null) {
        log.warning(LintCategory.DEP_ANN,
                pos, "missing.deprecated.annotation");
    }
}
 
示例26
/**
 *  Check for division by integer constant zero
 *  @param pos           Position for error reporting.
 *  @param operator      The operator for the expression
 *  @param operand       The right hand operand for the expression
 */
void checkDivZero(DiagnosticPosition pos, Symbol operator, Type operand) {
    if (operand.constValue() != null
        && lint.isEnabled(LintCategory.DIVZERO)
        && operand.getTag().isSubRangeOf(LONG)
        && ((Number) (operand.constValue())).longValue() == 0) {
        int opc = ((OperatorSymbol)operator).opcode;
        if (opc == ByteCodes.idiv || opc == ByteCodes.imod
            || opc == ByteCodes.ldiv || opc == ByteCodes.lmod) {
            log.warning(LintCategory.DIVZERO, pos, "div.zero");
        }
    }
}
 
示例27
public void checkModuleName (JCModuleDecl tree) {
    Name moduleName = tree.sym.name;
    Assert.checkNonNull(moduleName);
    if (lint.isEnabled(LintCategory.MODULE)) {
        JCExpression qualId = tree.qualId;
        while (qualId != null) {
            Name componentName;
            DiagnosticPosition pos;
            switch (qualId.getTag()) {
                case SELECT:
                    JCFieldAccess selectNode = ((JCFieldAccess) qualId);
                    componentName = selectNode.name;
                    pos = selectNode.pos();
                    qualId = selectNode.selected;
                    break;
                case IDENT:
                    componentName = ((JCIdent) qualId).name;
                    pos = qualId.pos();
                    qualId = null;
                    break;
                default:
                    throw new AssertionError("Unexpected qualified identifier: " + qualId.toString());
            }
            if (componentName != null) {
                String moduleNameComponentString = componentName.toString();
                int nameLength = moduleNameComponentString.length();
                if (nameLength > 0 && Character.isDigit(moduleNameComponentString.charAt(nameLength - 1))) {
                    log.warning(Lint.LintCategory.MODULE, pos, Warnings.PoorChoiceForModuleName(componentName));
                }
            }
        }
    }
}
 
示例28
/**
 * Main method: compile a list of files, return all compiled classes
 *
 * @param sourceFileObjects file objects to be compiled
 * @param classnames class names to process for annotations
 * @param processors user provided annotation processors to bypass
 * discovery, {@code null} means that no processors were provided
 */
public void compile(List<JavaFileObject> sourceFileObjects,
                    List<String> classnames,
                    Iterable<? extends Processor> processors)
{
    if (processors != null && processors.iterator().hasNext())
        explicitAnnotationProcessingRequested = true;
    // as a JavaCompiler can only be used once, throw an exception if
    // it has been used before.
    if (hasBeenUsed)
        throw new AssertionError("attempt to reuse JavaCompiler");
    hasBeenUsed = true;

    // forcibly set the equivalent of -Xlint:-options, so that no further
    // warnings about command line options are generated from this point on
    options.put(XLINT_CUSTOM.text + "-" + LintCategory.OPTIONS.option, "true");
    options.remove(XLINT_CUSTOM.text + LintCategory.OPTIONS.option);

    start_msec = now();

    try {
        initProcessAnnotations(processors);

        // These method calls must be chained to avoid memory leaks
        delegateCompiler =
            processAnnotations(
                enterTrees(stopIfError(CompileState.PARSE, parseFiles(sourceFileObjects))),
                classnames);

        delegateCompiler.compile2();
        delegateCompiler.close();
        elapsed_msec = delegateCompiler.elapsed_msec;
    } catch (Abort ex) {
        if (devVerbose)
            ex.printStackTrace(System.err);
    } finally {
        if (procEnvImpl != null)
            procEnvImpl.close();
    }
}
 
示例29
boolean visitIntersectionType(IntersectionClassType ict, Type s, boolean reverse) {
    Warner warn = noWarnings;
    for (Type c : ict.getComponents()) {
        warn.clear();
        if (reverse ? !isCastable(s, c, warn) : !isCastable(c, s, warn))
            return false;
    }
    if (warn.hasLint(LintCategory.UNCHECKED))
        warnStack.head.warn(LintCategory.UNCHECKED);
    return true;
}
 
示例30
/** Construct a new class reader. */
protected ClassReader(Context context) {
    context.put(classReaderKey, this);
    annotate = Annotate.instance(context);
    names = Names.instance(context);
    syms = Symtab.instance(context);
    types = Types.instance(context);
    fileManager = context.get(JavaFileManager.class);
    if (fileManager == null)
        throw new AssertionError("FileManager initialization error");
    diagFactory = JCDiagnostic.Factory.instance(context);

    log = Log.instance(context);

    Options options = Options.instance(context);
    verbose         = options.isSet(Option.VERBOSE);

    Source source = Source.instance(context);
    allowSimplifiedVarargs = source.allowSimplifiedVarargs();
    allowModules     = source.allowModules();

    saveParameterNames = options.isSet(PARAMETERS);

    profile = Profile.instance(context);

    typevars = WriteableScope.create(syms.noSymbol);

    lintClassfile = Lint.instance(context).isEnabled(LintCategory.CLASSFILE);

    initAttributeReaders();
}