Skip to content

feat(instrument): Skip instrumentation of loop variables (Phase 2A) #21

@kolkov

Description

@kolkov

Summary

Loop variables (for i, v := range items) are loop-scoped and should not be instrumented as they cannot cause data races when used within their loop body.

Problem

Currently, our AST-based instrumentor adds race detection calls for all variable accesses, including loop variables like:

for i, v := range items {
    race.RaceRead(&i)    // False positive - i is loop-local
    race.RaceWrite(&v)   // False positive - v is loop-local
    process(i, v)
}

Impact: ~30% of current false positives come from loop variable instrumentation.

Solution

Add loop variable detection in visitor.go:

  1. Track loop variable names when entering *ast.ForStmt and *ast.RangeStmt
  2. Skip instrumentation for these variables within loop body
  3. Clean up tracking when exiting loop

Implementation

type instrumentVisitor struct {
    // ... existing fields ...
    loopVars map[string]bool  // Track current loop variables
}

func (v *instrumentVisitor) Visit(node ast.Node) ast.Visitor {
    switch n := node.(type) {
    case *ast.RangeStmt:
        // Track Key and Value identifiers
        if key, ok := n.Key.(*ast.Ident); ok {
            v.loopVars[key.Name] = true
        }
        if value, ok := n.Value.(*ast.Ident); ok {
            v.loopVars[value.Name] = true
        }
        // Walk body, then clean up
        // ...
    case *ast.ForStmt:
        // Track Init statement variables
        // ...
    }
}

func (v *instrumentVisitor) isLoopVariable(ident *ast.Ident) bool {
    return v.loopVars[ident.Name]
}

Acceptance Criteria

  • Loop index variables (i in for i := 0; i < n; i++) are not instrumented
  • Range key/value variables (i, v in for i, v := range items) are not instrumented
  • Nested loops handled correctly (inner loop vars don't affect outer)
  • Variables with same name in different scopes handled correctly
  • Unit tests added for loop variable detection
  • Zygomys false positives reduced by ~30%

Estimated Effort

2-3 days

Related

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions