JavaSlicer icon indicating copy to clipboard operation
JavaSlicer copied to clipboard

Crash on Array Element Field Assignment

Open bystc opened this issue 1 month ago • 2 comments

Description

JavaSlicer crashes with IllegalStateException when encountering field assignments on array elements, such as arr[0].field = value or arr[0].field += 5.

Steps to Reproduce

  1. Create a test file with array element field assignment:
public class TestArrayFieldAssignment {
    static class Data {
        int value;
        Data(int v) { this.value = v; }
    }
    
    public static void main(String[] args) {
        Data[] arr = new Data[3];
        arr[0] = new Data(10);
        arr[0].value += 5;  //  This line causes crash
        int result = arr[0].value;
        System.out.println(result);
    }
}

Actual Behavior

Exception in thread "main" java.lang.IllegalStateException: 
only valid assignments are this[.<field>]+ =, and <var>[.<field>]+
    at es.upv.mist.slicing.nodes.VariableVisitor$1.visit(VariableVisitor.java:370)
    at es.upv.mist.slicing.nodes.VariableVisitor$1.visit(VariableVisitor.java:322)
    at com.github.javaparser.ast.expr.FieldAccessExpr.accept(FieldAccessExpr.java:96)

Expected Behavior

The tool should successfully analyze the code and include:

  • The Data class definition
  • Array creation and initialization
  • The field assignment to arr[0].value
  • All dependencies leading to the slicing criterion

Root Cause

In VariableVisitor.java lines 344-395, the code only handles 4 types of field assignment scopes:

  1. var.field = value (NameExpr)
  2. this.field = value (ThisExpr)
  3. foo().field = value (MethodCallExpr)
  4. new Foo().field = value (ObjectCreationExpr)

Missing: arr[0].field = value (ArrayAccessExpr)

// VariableVisitor.java:360-370
if (scope.isMethodCallExpr() || scope.isObjectCreationExpr()) {
    // Handle method call or object creation scope
} else if (scope.isNameExpr() || scope.isThisExpr()) {
    // Handle variable or this scope
} else {
    // ArrayAccessExpr falls here and throws exception!
    throw new IllegalStateException(
        "only valid assignments are this[.<field>]+ =, and <var>[.<field>]+");
}

Suggested Fix

Add support for ArrayAccessExpr as a scope in the field assignment handler:

else if (scope.isArrayAccessExpr()) {
    // Handle array element field access: arr[idx].field = value
    ArrayAccessExpr arrayAccess = scope.asArrayAccessExpr();
    // Process array access and register appropriate dependencies
    arrayAccess.accept(VariableVisitor.this, action);
    // ... (build realName and root appropriately)
}

bystc avatar Oct 23 '25 07:10 bystc