babel / babel

🐠 Babel is a compiler for writing next generation JavaScript.
https://babel.dev
MIT License
43.24k stars 5.65k forks source link

`path.getTypeAnnotation()` throws #5178

Open kangax opened 7 years ago

kangax commented 7 years ago

Ran into this while fixing some Babili issues.

https://astexplorer.net/#/GbUDVxRZlD

Input Code

var a;
if (typeof a === "") {
  a;
}

Expected Behavior

Should not throw

Current Behavior

Throws "Invalid typeof value"

This is coming from inferAnnotationFromBinaryExpression which somehow produces null, passing it to createTypeAnnotationBasedOnTypeof in flow.js which doesn't understand "null" as one of the types.

/cc'ing @jeffmo since this is possibly related to Flow.

babel-bot commented 7 years ago

Hey @kangax! We really appreciate you taking the time to report an issue. The collaborators on this project attempt to help as many people as possible, but we're a limited number of volunteers, so it's possible this won't be addressed swiftly.

If you need any help, or just have general Babel or JavaScript questions, we have a vibrant Slack community that typically always has someone willing to help. You can sign-up here for an invite.

hzoo commented 7 years ago

Oh thought it might of had to do with https://github.com/babel/babel/pull/3414 by @amasad but maybe not.

jeffmo commented 7 years ago

Hmm, AFAIK this isn't related to Flow other than syntax...but I'm not really familiar with this code.

Random guess: Does Babel try to infer types somewhere? If so, maybe it gets confused by the "" typeof comparison?

kangax commented 7 years ago

Yep, AFAICS, Babel tries to infer annotation — https://github.com/babel/babel/blob/master/packages/babel-traverse/src/path/index.js#L38

This suite looks useful and explains things a little — https://github.com/babel/babel/blob/8c35b320d37a957b629e75f59a9f52292cfd6b8e/packages/babel-traverse/test/inference.js#L57-L175

Looks like this is just an inference bug. I'll fix it.