for_direction

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: 3 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ForDirectionRule = rule.CreateRule(rule.Rule{
	Name: "for-direction",
	Run: func(ctx rule.RuleContext, options any) rule.RuleListeners {
		return rule.RuleListeners{
			ast.KindForStatement: func(node *ast.Node) {
				forStmt := node.AsForStatement()
				if forStmt == nil {
					return
				}

				if forStmt.Condition == nil || forStmt.Incrementor == nil {
					return
				}

				condition := forStmt.Condition
				incrementor := forStmt.Incrementor

				if condition.Kind != ast.KindBinaryExpression {
					return
				}

				binary := condition.AsBinaryExpression()
				if binary == nil || binary.OperatorToken == nil {
					return
				}

				operator := binary.OperatorToken.Kind

				switch operator {
				case ast.KindLessThanToken, ast.KindLessThanEqualsToken,
					ast.KindGreaterThanToken, ast.KindGreaterThanEqualsToken:

				default:

					return
				}

				counterOnLeft := true
				counterName := getVariableName(binary.Left)

				if counterName == "" {
					counterOnLeft = false
					counterName = getVariableName(binary.Right)
				}

				if counterName == "" {
					return
				}

				updateVarName := getVariableName(incrementor)

				if updateVarName != counterName {
					return
				}

				expectedDirection := getExpectedDirection(condition, counterOnLeft)
				if expectedDirection == 0 {
					return
				}

				actualDirection := getUpdateDirection(incrementor)

				if actualDirection == 0 {
					actualDirection = getAssignmentDirection(incrementor, &ctx)
				}

				if actualDirection == 0 {
					return
				}

				if expectedDirection != actualDirection {

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

ForDirectionRule enforces that for loop update clauses move the counter in the right direction

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