Search in sources :

Example 6 with CheckReturnValue

use of com.google.errorprone.annotations.CheckReturnValue in project error-prone by google.

the class ScannerSupplier method plus.

/**
 * Composes this {@link ScannerSupplier} with the {@code other} {@link ScannerSupplier}. The set
 * of checks that are turned on is the intersection of the checks on in {@code this} and {@code
 * other}.
 */
@CheckReturnValue
public ScannerSupplier plus(ScannerSupplier other) {
    HashBiMap<String, BugCheckerInfo> combinedAllChecks = HashBiMap.create(this.getAllChecks());
    other.getAllChecks().forEach((k, v) -> {
        BugCheckerInfo existing = combinedAllChecks.putIfAbsent(k, v);
        if (existing != null && !existing.checkerClass().getName().contentEquals(v.checkerClass().getName())) {
            throw new IllegalArgumentException(String.format("Cannot combine scanner suppliers with different implementations of" + " '%s': %s, %s", k, v.checkerClass().getName(), existing.checkerClass().getName()));
        }
    });
    HashMap<String, SeverityLevel> combinedSeverities = new LinkedHashMap<>(this.severities());
    other.severities().forEach((k, v) -> {
        SeverityLevel existing = combinedSeverities.putIfAbsent(k, v);
        if (existing != null && !existing.equals(v)) {
            throw new IllegalArgumentException(String.format("Cannot combine scanner suppliers with different severities for" + " '%s': %s, %s", k, v, existing));
        }
    });
    ImmutableSet<String> disabled = ImmutableSet.copyOf(Sets.union(disabled(), other.disabled()));
    ErrorProneFlags combinedFlags = this.getFlags().plus(other.getFlags());
    return new ScannerSupplierImpl(ImmutableBiMap.copyOf(combinedAllChecks), ImmutableMap.copyOf(combinedSeverities), disabled, combinedFlags);
}
Also used : SeverityLevel(com.google.errorprone.BugPattern.SeverityLevel) BugCheckerInfo(com.google.errorprone.BugCheckerInfo) ErrorProneFlags(com.google.errorprone.ErrorProneFlags) LinkedHashMap(java.util.LinkedHashMap) CheckReturnValue(com.google.errorprone.annotations.CheckReturnValue)

Example 7 with CheckReturnValue

use of com.google.errorprone.annotations.CheckReturnValue in project error-prone by google.

the class ScannerSupplier method applyOverrides.

/**
 * Applies options to this {@link ScannerSupplier}.
 *
 * <p>Command-line options to override check severities may do any of the following:
 *
 * <ul>
 *   <li>Enable a check that is currently off
 *   <li>Disable a check that is currently on
 *   <li>Change the severity of a check that is on, promoting a warning to an error or demoting an
 *       error to a warning
 * </ul>
 *
 * @param errorProneOptions an {@link ErrorProneOptions} object that encapsulates the overrides
 *     for this compilation
 * @throws InvalidCommandLineOptionException if the override map attempts to disable a check that
 *     may not be disabled
 */
@CheckReturnValue
public ScannerSupplier applyOverrides(ErrorProneOptions errorProneOptions) throws InvalidCommandLineOptionException {
    Map<String, Severity> severityOverrides = errorProneOptions.getSeverityMap();
    if (severityOverrides.isEmpty() && errorProneOptions.getFlags().isEmpty() && !errorProneOptions.isEnableAllChecksAsWarnings() && !errorProneOptions.isDropErrorsToWarnings() && !errorProneOptions.isDisableAllChecks()) {
        return this;
    }
    // Initialize result allChecks map and enabledChecks set with current state of this Supplier.
    ImmutableBiMap<String, BugCheckerInfo> checks = getAllChecks();
    Map<String, SeverityLevel> severities = new LinkedHashMap<>(severities());
    Set<String> disabled = new HashSet<>(disabled());
    if (errorProneOptions.isEnableAllChecksAsWarnings()) {
        disabled.forEach(c -> severities.put(c, SeverityLevel.WARNING));
        disabled.clear();
    }
    if (errorProneOptions.isDropErrorsToWarnings()) {
        getAllChecks().values().stream().filter(c -> c.defaultSeverity() == SeverityLevel.ERROR && c.disableable()).forEach(c -> severities.put(c.canonicalName(), SeverityLevel.WARNING));
    }
    if (errorProneOptions.isDisableAllChecks()) {
        getAllChecks().values().stream().filter(c -> c.disableable()).forEach(c -> disabled.add(c.canonicalName()));
    }
    // Process overrides
    severityOverrides.forEach((checkName, newSeverity) -> {
        BugCheckerInfo check = getAllChecks().get(checkName);
        if (check == null) {
            if (errorProneOptions.ignoreUnknownChecks()) {
                return;
            }
            throw new InvalidCommandLineOptionException(checkName + " is not a valid checker name");
        }
        switch(newSeverity) {
            case OFF:
                if (!check.disableable()) {
                    throw new InvalidCommandLineOptionException(check.canonicalName() + " may not be disabled");
                }
                severities.remove(check.canonicalName());
                disabled.add(check.canonicalName());
                break;
            case DEFAULT:
                severities.put(check.canonicalName(), check.defaultSeverity());
                disabled.remove(check.canonicalName());
                break;
            case WARN:
                // Demoting an enabled check from an error to a warning is a form of disabling
                if (!disabled().contains(check.canonicalName()) && !check.disableable() && check.defaultSeverity() == SeverityLevel.ERROR) {
                    throw new InvalidCommandLineOptionException(check.canonicalName() + " is not disableable and may not be demoted to a warning");
                }
                severities.put(check.canonicalName(), SeverityLevel.WARNING);
                disabled.remove(check.canonicalName());
                break;
            case ERROR:
                severities.put(check.canonicalName(), SeverityLevel.ERROR);
                disabled.remove(check.canonicalName());
                break;
            default:
                throw new IllegalStateException("Unexpected severity level: " + newSeverity);
        }
    });
    return new ScannerSupplierImpl(checks, ImmutableMap.copyOf(severities), ImmutableSet.copyOf(disabled), errorProneOptions.getFlags());
}
Also used : Arrays(java.util.Arrays) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) CheckReturnValue(com.google.errorprone.annotations.CheckReturnValue) Supplier(com.google.common.base.Supplier) BugChecker(com.google.errorprone.bugpatterns.BugChecker) Set(java.util.Set) HashMap(java.util.HashMap) Severity(com.google.errorprone.ErrorProneOptions.Severity) Sets(com.google.common.collect.Sets) ImmutableBiMap(com.google.common.collect.ImmutableBiMap) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) HashBiMap(com.google.common.collect.HashBiMap) ImmutableList(com.google.common.collect.ImmutableList) ErrorProneFlags(com.google.errorprone.ErrorProneFlags) Predicate(com.google.common.base.Predicate) BugCheckerInfo(com.google.errorprone.BugCheckerInfo) ErrorProneOptions(com.google.errorprone.ErrorProneOptions) Map(java.util.Map) VisibleForTesting(com.google.common.annotations.VisibleForTesting) InvalidCommandLineOptionException(com.google.errorprone.InvalidCommandLineOptionException) SeverityLevel(com.google.errorprone.BugPattern.SeverityLevel) BugCheckerInfo(com.google.errorprone.BugCheckerInfo) InvalidCommandLineOptionException(com.google.errorprone.InvalidCommandLineOptionException) Severity(com.google.errorprone.ErrorProneOptions.Severity) LinkedHashMap(java.util.LinkedHashMap) SeverityLevel(com.google.errorprone.BugPattern.SeverityLevel) HashSet(java.util.HashSet) CheckReturnValue(com.google.errorprone.annotations.CheckReturnValue)

Example 8 with CheckReturnValue

use of com.google.errorprone.annotations.CheckReturnValue in project error-prone by google.

the class IncompatibleArgumentType method populateTypesToEnforce.

// Return whether this method contains any @CompatibleWith annotations. If there are none, the
// caller should explore super-methods.
@CheckReturnValue
private boolean populateTypesToEnforce(MethodSymbol declaredMethod, Type calledMethodType, Type calledReceiverType, List<RequiredType> argumentTypeRequirements, VisitorState state) {
    boolean foundAnyTypeToEnforce = false;
    List<VarSymbol> params = declaredMethod.params();
    for (int i = 0; i < params.size(); i++) {
        VarSymbol varSymbol = params.get(i);
        CompatibleWith anno = ASTHelpers.getAnnotation(varSymbol, CompatibleWith.class);
        if (anno != null) {
            foundAnyTypeToEnforce = true;
            // Now we try and resolve the generic type argument in the annotation against the current
            // method call's projection of this generic type.
            RequiredType requiredType = resolveRequiredTypeForThisCall(state, calledMethodType, calledReceiverType, declaredMethod, anno.value());
            // @CW is on the varags parameter
            if (declaredMethod.isVarArgs() && i == params.size() - 1) {
                if (i >= argumentTypeRequirements.size()) {
                    // void foo(String...); foo();
                    break;
                } else {
                    // Set this required type for all of the arguments in the varargs position.
                    for (int j = i; j < argumentTypeRequirements.size(); j++) {
                        argumentTypeRequirements.set(j, requiredType);
                    }
                }
            } else {
                argumentTypeRequirements.set(i, requiredType);
            }
        }
    }
    return foundAnyTypeToEnforce;
}
Also used : VarSymbol(com.sun.tools.javac.code.Symbol.VarSymbol) CompatibleWith(com.google.errorprone.annotations.CompatibleWith) CheckReturnValue(com.google.errorprone.annotations.CheckReturnValue)

Example 9 with CheckReturnValue

use of com.google.errorprone.annotations.CheckReturnValue in project closure-compiler by google.

the class TypeInference method updateScopeForAssignment.

/**
 * Updates the scope according to the result of an assignment.
 */
@CheckReturnValue
private FlowScope updateScopeForAssignment(FlowScope scope, Node target, JSType resultType, Node updateNode, AssignmentType type) {
    checkNotNull(resultType);
    checkState(updateNode == null || updateNode == target);
    // may be null
    JSType targetType = target.getJSType();
    Node right = NodeUtil.getRValueOfLValue(target);
    if (isPossibleMixinApplication(target, right)) {
        addMissingInterfaceProperties(targetType);
    }
    switch(target.getToken()) {
        case NAME:
            String varName = target.getString();
            TypedVar var = getDeclaredVar(scope, varName);
            JSType varType = var == null ? null : var.getType();
            boolean isVarDeclaration = type == AssignmentType.DECLARATION && !var.isTypeInferred() && // implicit vars (like arguments) have no nameNode
            var.getNameNode() != null;
            // Whether this variable is declared not because it has JSDoc with a declaration, but
            // because it is const and the right-hand-side is easily inferrable.
            // e.g. these are 'typeless const declarations':
            // const x = 0;
            // /** @const */
            // a.b.c = SomeOtherConstructor;
            // but these are not:
            // let x = 0;
            // /** @const @constructor */
            // a.b.c = someMixin();
            // This is messy, since the definition of 'typeless const' is duplicated in
            // TypedScopeCreator and this code.
            boolean isTypelessConstDecl = isVarDeclaration && // ignore redeclarations of implicit globals
            var.getNameNode().isName() && NodeUtil.isConstantDeclaration(var.getJSDocInfo(), var.getNameNode()) && !(var.getJSDocInfo() != null && var.getJSDocInfo().containsDeclarationExcludingTypelessConst());
            // When looking at VAR initializers for declared VARs, we tend
            // to use the declared type over the type it's being
            // initialized to in the global scope.
            // 
            // For example,
            // /** @param {number} */ var f = goog.abstractMethod;
            // it's obvious that the programmer wants you to use
            // the declared function signature, not the inferred signature.
            // 
            // Or,
            // /** @type {Object.<string>} */ var x = {};
            // the one-time anonymous object on the right side
            // is as narrow as it can possibly be, but we need to make
            // sure we back-infer the <string> element constraint on
            // the left hand side, so we use the left hand side.
            boolean isVarTypeBetter = isVarDeclaration && // Makes it easier to check for NPEs.
            !resultType.isNullType() && !resultType.isVoidType() && // because this type was computed from the RHS
            !isTypelessConstDecl;
            if (isVarTypeBetter) {
                scope = redeclareSimpleVar(scope, target, varType);
            } else {
                scope = redeclareSimpleVar(scope, target, resultType);
            }
            if (updateNode != null) {
                updateNode.setJSType(resultType);
            }
            if (var != null && var.isTypeInferred() && // TODO(sdh): remove this condition after cleaning up code depending on it.
            !(target.getParent().isLet() && !target.hasChildren())) {
                JSType oldType = var.getType();
                var.setType(oldType == null ? resultType : oldType.getLeastSupertype(resultType));
            } else if (isTypelessConstDecl) {
                // /** @const */ var x = y;
                // should be redeclared, so that the type of y
                // gets propagated to inner scopes.
                var.setType(resultType);
            }
            break;
        case GETPROP:
            if (target.isQualifiedName()) {
                String qualifiedName = target.getQualifiedName();
                boolean declaredSlotType = false;
                JSType rawObjType = target.getFirstChild().getJSType();
                if (rawObjType != null) {
                    ObjectType objType = ObjectType.cast(rawObjType.restrictByNotNullOrUndefined());
                    if (objType != null) {
                        String propName = target.getString();
                        declaredSlotType = objType.isPropertyTypeDeclared(propName);
                    }
                }
                JSType safeLeftType = targetType == null ? unknownType : targetType;
                scope = scope.inferQualifiedSlot(target, qualifiedName, safeLeftType, resultType, declaredSlotType);
            }
            if (updateNode != null) {
                updateNode.setJSType(resultType);
            }
            ensurePropertyDefined(target, resultType, scope);
            break;
        default:
            break;
    }
    return scope;
}
Also used : ObjectType(com.google.javascript.rhino.jstype.ObjectType) JSType(com.google.javascript.rhino.jstype.JSType) Node(com.google.javascript.rhino.Node) CheckReturnValue(com.google.errorprone.annotations.CheckReturnValue)

Example 10 with CheckReturnValue

use of com.google.errorprone.annotations.CheckReturnValue in project closure-compiler by google.

the class TypeInference method traverseReturn.

/**
 * Traverse a return value.
 */
@CheckReturnValue
private FlowScope traverseReturn(Node n, FlowScope scope) {
    scope = traverseChildren(n, scope);
    Node retValue = n.getFirstChild();
    if (retValue != null) {
        JSType type = containerScope.getRootNode().getJSType();
        if (type != null) {
            FunctionType fnType = type.toMaybeFunctionType();
            if (fnType != null) {
                inferPropertyTypesToMatchConstraint(retValue.getJSType(), fnType.getReturnType());
            }
        }
    }
    return scope;
}
Also used : JSType(com.google.javascript.rhino.jstype.JSType) Node(com.google.javascript.rhino.Node) FunctionType(com.google.javascript.rhino.jstype.FunctionType) CheckReturnValue(com.google.errorprone.annotations.CheckReturnValue)

Aggregations

CheckReturnValue (com.google.errorprone.annotations.CheckReturnValue)16 JSType (com.google.javascript.rhino.jstype.JSType)11 Node (com.google.javascript.rhino.Node)7 ObjectType (com.google.javascript.rhino.jstype.ObjectType)3 BugCheckerInfo (com.google.errorprone.BugCheckerInfo)2 SeverityLevel (com.google.errorprone.BugPattern.SeverityLevel)2 ErrorProneFlags (com.google.errorprone.ErrorProneFlags)2 HashSet (java.util.HashSet)2 LinkedHashMap (java.util.LinkedHashMap)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 Predicate (com.google.common.base.Predicate)1 Supplier (com.google.common.base.Supplier)1 HashBiMap (com.google.common.collect.HashBiMap)1 ImmutableBiMap (com.google.common.collect.ImmutableBiMap)1 ImmutableList (com.google.common.collect.ImmutableList)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 ImmutableSet (com.google.common.collect.ImmutableSet)1 Sets (com.google.common.collect.Sets)1 ErrorProneOptions (com.google.errorprone.ErrorProneOptions)1 Severity (com.google.errorprone.ErrorProneOptions.Severity)1