Recursively infer generic type arguments

Slightly changed by Luca Bruno.

Fixes bug 626783