google / google/closure-compiler
Overridden methods of hoisted base class constructors not inferred correctly
- Dominant language
- JavaScript
- Stars
- 7.7k
- Forks
- 1.2k
- Avg merge
- 2d 12h
- Merged PRs (30d)
- 6
Description
[repro]
The following should produce a type error, but it does not:
```js
/** @constructor */
var Base = function() {}
/** @param {number} x */
Base.prototype.baz = function(x) {};
/** @constructor @extends {Base} */
function Foo() {};
/** @override */
Foo.prototype.baz = function(x) {
var /** string */ y = x;
};
```
What seems to be happening is that TypedScopeCreator analyzes the hoisted function `Foo` first, before looking at `Base`, and then in `#finishConstructorDefinition`, it sets a `NamedType` as the superclass. It then analyzes `Base`, `Base.prototype.baz`, and finally `Foo.prototype.baz`. When it looks for the overridden method, it calls `#getProperyType("baz")` on `Foo.prototype`, which is an instance of the `NamedType` and so has a permanently empty `PropertyMap`. This results in unknown for the overridden type, and so the body of the function is analyzed with an unknown parameter type, missing the expected type error.
The `PropertyMap` is fixed after typed scope creation, when all the scopes are resolved, but by that time the damage is already done.
Several possible solutions:
* don't call `#finishConstructorDefinition` while preorder analyzing hoisted functions, and then finish it when doing normal function analysis
* do some limited type resolution early; but we can't do a full resolution and we certainly don't want to prevent additional work from happening during the full resolve
* take a more sophisticated approach to resolution where references to NamedTypes are stored and updated immediately when more information becomes available (cf. reference counting vs garbage collection)
[repro]: https://closure-compiler-debugger.appspot.com/#input0%3D%252F**%2520%2540constructor%2520*%252F%250Avar%2520Base%2520%253D%2520function()%2520%257B%257D%250A%252F**%2520%2540param%2520%257Bnumber%257D%2520x%2520*%252F%250ABase.prototype.baz%2520%253D%2520function(x)%2520%257B%257D%253B%250A%250A%252F**%2520%2540constructor%2520%2540extends%2520%257BBase%257D%2520*%252F%250Afunction%2520Foo()%2520%257B%257D%253B%250A%252F**%2520%2540override%2520*%252F%250AFoo.prototype.baz%2520%253D%2520function(x)%2520%257B%250A%2520%2520var%2520%252F**%2520string%2520*%252F%2520y%2520%253D%2520x%253B%250A%257D%253B%26input1%26conformanceConfig%26externs%26refasterjs-template%26CHECK_SYMBOLS%3Dtrue%26MISSING_PROPERTIES%3Dtrue%26TRANSPILE%3Dtrue%26CHECK_TYPES%3Dtrue%26CLOSURE_PASS%3Dtrue%26PRESERVE_TYPE_ANNOTATIONS%3Dtrue%26PRETTY_PRINT%3Dtrue
Contributor guide
Assessment
This issue has not been assessed yet.