wala/WALA — pull request #12 by vazexqi (2013-03-29 22:38:11+00:00)
Title: PrimAndStringOp bug in AstJavaTypeInference

#### Problem

I was using AstJavaTypeInference and discovered a bug with the way that string + primitives are handled. I've included a test case in the pull request but here's the gist of it

```java
package javaonepointfive;

public class TypeInferencePrimAndStringOp {
public static void main(String[] args) {
int a = 2;
String result = "a" + a;
}
}

```

Trying to infer the type of `result` ends with a `Unexpected type: class com.ibm.wala.analysis.typeInference.JavaPrimitiveType` exception.

#### Cause

After tracing it down, I found that PrimAndStringOp uses a field call `stringClass` in AstJavaTypeInference but that field does not get a chance to be initialized _before_ it is used. That is because the first line in AstJavaTypeInference is a call to super that initializes the AbstractFixedPointSolver, which calls the `initialize()` and `solve()` functions, which in turn, calls the `evaluate` function in PrimAndStringOp.

Here's the original constructor for AstJavaTypeInference:

```java
public AstJavaTypeInference(IR ir, IClassHierarchy cha, boolean doPrimitives) {
super(ir, cha, JavaPrimitiveType.BOOLEAN, doPrimitives);
this.stringClass = cha.lookupClass(TypeReference.JavaLangString);

```

#### (Possible) Solution

I used lazy initialization for stringClass to ensure that it is initialized when it is first used in the `evaluate` function in PrimAndStringOp.

```java
IClass getStringClass() {
if (stringClass == null) {
this.stringClass = cha.lookupClass(TypeReference.JavaLangString);
}
return stringClass;
}
```