"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const experimental_utils_1 = require("@typescript-eslint/experimental-utils");
const typescript_1 = __importStar(require("typescript"));
const tsutils_1 = require("tsutils");
const util_1 = require("../util");
// Truthiness utilities
// #region
const isTruthyLiteral = (type) => tsutils_1.isBooleanLiteralType(type, true) || (tsutils_1.isLiteralType(type) && !!type.value);
const isPossiblyFalsy = (type) => tsutils_1.unionTypeParts(type)
    // PossiblyFalsy flag includes literal values, so exclude ones that
    // are definitely truthy
    .filter(t => !isTruthyLiteral(t))
    .some(type => tsutils_1.isTypeFlagSet(type, typescript_1.default.TypeFlags.PossiblyFalsy));
const isPossiblyTruthy = (type) => tsutils_1.unionTypeParts(type).some(type => !tsutils_1.isFalsyType(type));
// isLiteralType only covers numbers and strings, this is a more exhaustive check.
const isLiteral = (type) => tsutils_1.isBooleanLiteralType(type, true) ||
    tsutils_1.isBooleanLiteralType(type, false) ||
    type.flags === typescript_1.default.TypeFlags.Undefined ||
    type.flags === typescript_1.default.TypeFlags.Null ||
    type.flags === typescript_1.default.TypeFlags.Void ||
    tsutils_1.isLiteralType(type);
exports.default = util_1.createRule({
    name: 'no-unnecessary-conditionals',
    meta: {
        type: 'suggestion',
        docs: {
            description: 'Prevents conditionals where the type is always truthy or always falsy',
            category: 'Best Practices',
            recommended: false,
            requiresTypeChecking: true,
        },
        schema: [
            {
                type: 'object',
                properties: {
                    ignoreRhs: {
                        type: 'boolean',
                    },
                },
                additionalProperties: false,
            },
        ],
        messages: {
            alwaysTruthy: 'Unnecessary conditional, value is always truthy.',
            alwaysFalsy: 'Unnecessary conditional, value is always falsy.',
            literalBooleanExpression: 'Unnecessary conditional, both sides of the expression are literal values',
            never: 'Unnecessary conditional, value is `never`',
        },
    },
    defaultOptions: [
        {
            ignoreRhs: false,
        },
    ],
    create(context, [{ ignoreRhs }]) {
        const service = util_1.getParserServices(context);
        const checker = service.program.getTypeChecker();
        function getNodeType(node) {
            const tsNode = service.esTreeNodeToTSNodeMap.get(node);
            return util_1.getConstrainedTypeAtLocation(checker, tsNode);
        }
        /**
         * Checks if a conditional node is necessary:
         * if the type of the node is always true or always false, it's not necessary.
         */
        function checkNode(node) {
            const type = getNodeType(node);
            // Conditional is always necessary if it involves `any` or `unknown`
            if (tsutils_1.isTypeFlagSet(type, typescript_1.TypeFlags.Any | typescript_1.TypeFlags.Unknown)) {
                return;
            }
            if (tsutils_1.isTypeFlagSet(type, typescript_1.TypeFlags.Never)) {
                context.report({ node, messageId: 'never' });
            }
            else if (!isPossiblyTruthy(type)) {
                context.report({ node, messageId: 'alwaysFalsy' });
            }
            else if (!isPossiblyFalsy(type)) {
                context.report({ node, messageId: 'alwaysTruthy' });
            }
        }
        /**
         * Checks that a binary expression is necessarily conditional, reports otherwise.
         * If both sides of the binary expression are literal values, it's not a necessary condition.
         *
         * NOTE: It's also unnecessary if the types that don't overlap at all
         *    but that case is handled by the Typescript compiler itself.
         */
        const BOOL_OPERATORS = new Set([
            '<',
            '>',
            '<=',
            '>=',
            '==',
            '===',
            '!=',
            '!==',
        ]);
        function checkIfBinaryExpressionIsNecessaryConditional(node) {
            if (BOOL_OPERATORS.has(node.operator) &&
                isLiteral(getNodeType(node.left)) &&
                isLiteral(getNodeType(node.right))) {
                context.report({ node, messageId: 'literalBooleanExpression' });
            }
        }
        /**
         * Checks that a testable expression is necessarily conditional, reports otherwise.
         * Filters all LogicalExpressions to prevent some duplicate reports.
         */
        function checkIfTestExpressionIsNecessaryConditional(node) {
            if (node.test !== null &&
                node.test.type !== experimental_utils_1.AST_NODE_TYPES.LogicalExpression) {
                checkNode(node.test);
            }
        }
        /**
         * Checks that a logical expression contains a boolean, reports otherwise.
         */
        function checkLogicalExpressionForUnnecessaryConditionals(node) {
            checkNode(node.left);
            if (!ignoreRhs) {
                checkNode(node.right);
            }
        }
        return {
            BinaryExpression: checkIfBinaryExpressionIsNecessaryConditional,
            ConditionalExpression: checkIfTestExpressionIsNecessaryConditional,
            DoWhileStatement: checkIfTestExpressionIsNecessaryConditional,
            ForStatement: checkIfTestExpressionIsNecessaryConditional,
            IfStatement: checkIfTestExpressionIsNecessaryConditional,
            WhileStatement: checkIfTestExpressionIsNecessaryConditional,
            LogicalExpression: checkLogicalExpressionForUnnecessaryConditionals,
        };
    },
});
//# sourceMappingURL=no-unnecessary-condition.js.map