Skip to content

feat(instrument): Skip instrumentation of function-local short declarations (Phase 2B) #22

@kolkov

Description

@kolkov

Summary

Variables declared with short declaration (:=) that are never assigned to a pointer or passed by reference are function-local and should not be instrumented.

Problem

Currently, our AST-based instrumentor instruments all variable accesses:

func process(data []byte) error {
    result := computeResult(data)  // Local, never escapes
    race.RaceWrite(&result)        // False positive!
    
    if result > threshold {
        msg := "exceeded"          // Local, never escapes  
        race.RaceWrite(&msg)       // False positive!
        return errors.New(msg)
    }
    return nil
}

Impact: ~40% of current false positives come from local variable instrumentation.

Solution

Add basic scope and escape tracking:

Phase 2B-1: Simple Pattern Matching (1-2 days)

Detect obvious non-escaping patterns:

  • Variable used only within same block
  • Variable never has & applied
  • Variable never assigned to struct field or slice element

Phase 2B-2: Block-Level Scope Tracking (3-5 days)

Track variable declarations and their scope:

type scopeInfo struct {
    declaredIn *ast.BlockStmt
    hasAddressOf bool
    assignedToField bool
}

type instrumentVisitor struct {
    // ... existing fields ...
    localVars map[string]*scopeInfo
    currentBlock *ast.BlockStmt
}

Escape Heuristics

Safe to skip (high confidence):

  • Short declaration := with no & operator applied anywhere
  • Variable only used in same function, never passed to other functions
  • Primitive types (int, string, bool) declared locally

Must instrument (conservative):

  • Any variable with & applied
  • Variables passed to function calls (might escape via interface{})
  • Variables assigned to struct fields or slice/map elements
  • Variables captured in closures

Acceptance Criteria

  • Basic pattern matching for obvious non-escaping vars
  • Block-level scope tracking
  • Address-of operator (&) detection
  • Conservative handling of uncertain cases
  • Unit tests for each escape pattern
  • Zygomys false positives reduced by ~40%

Estimated Effort

1-2 weeks

Related

Notes

This is a heuristic approach. For 100% accuracy, Phase 2C (go/types) is needed.

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