Skip to content

Java type inference chain method calls and field access #200

@HRV1527

Description

@HRV1527

@vitali87
I had a question regarding the java type inference that it currently does not handle java chain method calls and field access such as :

class Address {
    public String zipCode = "90210";
}

class User {
    public Address address = new Address();
}

public class Main {
    public static void main(String[] args) {
        User obj = new User();
        
        // Chained Field Access
        String zip = obj.address.zipCode;
        System.out.println("Zip: " + zip);
    }
}
class QueryBuilder {
    private String query = "SELECT * ";

    public QueryBuilder from(String table) {
        this.query += "FROM " + table;
        return this; // Returning 'this' enables the chain
    }

    public QueryBuilder where(String condition) {
        this.query += " WHERE " + condition;
        return this;
    }

    public void execute() {
        System.out.println("Executing: " + query);
    }
}

public class Main {
    public static void main(String[] args) {
        QueryBuilder obj = new QueryBuilder();

        // Chained Method Calls
        obj.from("users").where("id = 1").execute();
    }
}
class Engine {
    public void start() {
        System.out.println("Engine started!");
    }
}

class Car {
    // The field
    public Engine engine = new Engine();
}

public class Main {
    public static void main(String[] args) {
        Car obj = new Car();

        // Mixed: obj (Car) -> field (engine) -> method (start)
        obj.engine.start();
    }
}

Also in java type inference the sequence of inferencing is :

            # 2. Analyze local variable declarations in the scope
            self._analyze_java_local_variables(scope_node, local_var_types, module_qn)
            # 3. Analyze field declarations from the containing class
            self._analyze_java_class_fields(scope_node, local_var_types, module_qn)

Which I think should be:

            # 2. Analyze field declarations from the containing class
            self._analyze_java_class_fields(scope_node, local_var_types, module_qn)

            # 3. Analyze local variable declarations in the scope
            self._analyze_java_local_variables(scope_node, local_var_types, module_qn)

Parameters first (already correct)
Class fields second - Fields are declared at class level and their types are fully known without dependencies on local variables
Local variables third - Local variables can reference parameters and fields in their initializers

Originally posted by @HRV1527 in #199

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions