no_cond_assign

package
v0.1.14 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2025 License: MIT Imports: 2 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var NoCondAssignRule = rule.CreateRule(rule.Rule{
	Name: "no-cond-assign",
	Run: func(ctx rule.RuleContext, options any) rule.RuleListeners {

		mode := "except-parens"
		if options != nil {
			if optMap, ok := options.(map[string]interface{}); ok {
				if modeStr, ok := optMap["mode"].(string); ok {
					mode = modeStr
				}
			} else if optStr, ok := options.(string); ok {
				mode = optStr
			}
		}

		return rule.RuleListeners{
			ast.KindBinaryExpression: func(node *ast.Node) {

				if !isAssignmentExpression(node) {
					return
				}

				// Walk up to find if we're directly in a conditional test (not nested in other expressions)
				var conditionalAncestor *ast.Node
				current := node.Parent

				hasNonParenExpression := false

				for current != nil {
					if current.Kind == ast.KindIfStatement ||
						current.Kind == ast.KindWhileStatement ||
						current.Kind == ast.KindDoStatement ||
						current.Kind == ast.KindForStatement ||
						current.Kind == ast.KindConditionalExpression {
						conditionalAncestor = current
						break
					}

					if current.Kind != ast.KindParenthesizedExpression {
						hasNonParenExpression = true
					}

					if current.Kind == ast.KindFunctionDeclaration ||
						current.Kind == ast.KindFunctionExpression ||
						current.Kind == ast.KindArrowFunction ||
						current.Kind == ast.KindMethodDeclaration {
						break
					}
					current = current.Parent
				}

				if conditionalAncestor == nil {
					return
				}

				testExpr := getTestExpression(conditionalAncestor)
				if testExpr == nil {
					return
				}

				if !containsNode(testExpr, node) {
					return
				}

				switch mode {
				case "always":

					ctx.ReportNode(node, buildUnexpectedMessage(getConditionalTypeName(conditionalAncestor)))
				case "except-parens":

					if hasNonParenExpression {

						return
					}

					parenLevels := 0
					current := node.Parent

					for current != nil && current.Kind == ast.KindParenthesizedExpression {
						parenLevels++
						current = current.Parent
					}

					isProperlyParenthesized := parenLevels >= 1

					if !isProperlyParenthesized {
						ctx.ReportNode(node, buildMissingMessage())
					}
				}
			},
		}
	},
})

NoCondAssignRule disallows assignment operators in conditional expressions

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