no_unsafe_enum_comparison

package
v0.1.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 11, 2025 License: MIT Imports: 5 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var NoUnsafeEnumComparisonRule = rule.CreateRule(rule.Rule{
	Name: "no-unsafe-enum-comparison",
	Run: func(ctx rule.RuleContext, options any) rule.RuleListeners {
		isMismatchedComparison := func(
			leftType *checker.Type,
			rightType *checker.Type,
		) bool {

			leftEnumTypes := utils.GetEnumTypes(ctx.TypeChecker, leftType)
			rightEnumTypes := utils.NewSetFromItems(utils.GetEnumTypes(ctx.TypeChecker, rightType)...)
			if len(leftEnumTypes) == 0 && rightEnumTypes.Len() == 0 {
				return false
			}

			for _, leftEnumType := range leftEnumTypes {
				if rightEnumTypes.Has(leftEnumType) {
					return false
				}
			}

			leftTypeParts := utils.UnionTypeParts(leftType)
			rightTypeParts := utils.UnionTypeParts(rightType)

			for _, leftTypePart := range leftTypeParts {
				if slices.Contains(rightTypeParts, leftTypePart) {
					return false
				}
			}

			l := typeViolates(leftTypeParts, rightType)

			return (l || typeViolates(rightTypeParts, leftType))
		}

		return rule.RuleListeners{
			ast.KindBinaryExpression: func(node *ast.Node) {
				expr := node.AsBinaryExpression()
				opKind := expr.OperatorToken.Kind
				if opKind != ast.KindLessThanToken && opKind != ast.KindLessThanEqualsToken && opKind != ast.KindGreaterThanToken && opKind != ast.KindGreaterThanEqualsToken && opKind != ast.KindEqualsEqualsToken && opKind != ast.KindEqualsEqualsEqualsToken && opKind != ast.KindExclamationEqualsToken && opKind != ast.KindExclamationEqualsEqualsToken {
					return
				}

				leftType := ctx.TypeChecker.GetTypeAtLocation(expr.Left)
				rightType := ctx.TypeChecker.GetTypeAtLocation(expr.Right)

				if isMismatchedComparison(leftType, rightType) {

					ctx.ReportNode(node, buildMismatchedConditionMessage())
				}
			},

			ast.KindCaseClause: func(node *ast.Node) {
				leftType := ctx.TypeChecker.GetTypeAtLocation(node.Parent.Parent.Expression())
				rightType := ctx.TypeChecker.GetTypeAtLocation(node.Expression())

				if isMismatchedComparison(leftType, rightType) {
					ctx.ReportNode(node, buildMismatchedCaseMessage())
				}
			},
		}
	},
})

Functions

This section is empty.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL