flow icon indicating copy to clipboard operation
flow copied to clipboard

Null refinement lost with single assignment

Open danvk opened this issue 11 years ago • 12 comments

When I type check this snippet:

function foo(): ?number { return null; }
function log(n: number) { console.log(n); }

function hello() {
  var n = foo();
  if (n == null) {
    throw 'bad!';
  }
  window.setTimeout(() => log(n), 0);
}

I get errors like these:

>> toy.js:3,18,23: ?number
>> This type is incompatible with
>> toy.js:7,17,22: number

This only happens when log(n) is called from a closure. The refinement of n from ?number to number (because of the null check) is lost. Calling log(n) directly is fine.

In general dropping the type refinement is necessary, but it seems superfluous in this case because n is only ever assigned to once. Its value couldn't possibly change.

danvk avatar Feb 19 '15 21:02 danvk

I believe this is similar to https://github.com/facebook/flow/issues/282 in trickiness (in the general case). In order to narrow the type of n, we'd have to prove that n is final (i.e. doesn't escape to somewhere where it could be updated later).

As with #282: This is worth looking into, but there may not be a trivial solution (or an all-encompassing one).

jeffmo avatar Feb 26 '15 19:02 jeffmo

@gabelevi suggested on IRC that supporting const would make this wart go away. I would be quite happy to declare const n instead of var n in my example if it made your life easier.

danvk avatar Feb 26 '15 19:02 danvk

Ah yes, that's a great solution actually!

jeffmo avatar Feb 26 '15 19:02 jeffmo

Hi @danvk, just wanted to confirm that you're right in the original example - with the right analysis we could verify that n would keep its refinement for any possible execution of the closure. Our analysis is insufficiently precise at the moment to catch this, but we hope to continue improving it. Thanks for the example!

bhosmer avatar Mar 01 '15 00:03 bhosmer

As of Flow 0.17 the const fix does not work:

/** @flow */
function foo(): ?number { return null; }
function log(n: number) { console.log(n); }

function hello() {
  const n = foo();
  if (n == null) {
    throw 'bad!';
  }
  window.setTimeout(() => log(n), 0);
}
$ flow status
foo.js:10
 10:   window.setTimeout(() => log(n), 0);
                               ^^^^^^ function call
 10:   window.setTimeout(() => log(n), 0);
                                   ^ null. This type is incompatible with
  3: function log(n: number) { console.log(n); }
                     ^^^^^^ number

foo.js:10
 10:   window.setTimeout(() => log(n), 0);
                               ^^^^^^ function call
 10:   window.setTimeout(() => log(n), 0);
                                   ^ undefined. This type is incompatible with
  3: function log(n: number) { console.log(n); }
                     ^^^^^^ number


Found 2 errors

danvk avatar Oct 15 '15 19:10 danvk

Yeah... we added support for the declaration, but we didn't update code to take advantage of const for improved type checking—like holding onto refinements.

I actually took a stab at this (with a blunt instrument) in #901, but I ran into a complication. @bhosmer, does the pattern in #817 make sense here? Am I right that the simple change in #901 is insufficient?

samwgoldman avatar Oct 15 '15 19:10 samwgoldman

Err, it's more helpful to provide a specific example. There are a few reasons why Flow wouldn't understand this code, but hopefully it shows why const bindings to objects can't stay refined, or makes it clear what my fundamental misunderstanding is.

/* @flow */

type T
  = { t: "a", a: number }
  | { t: "b", b: string };

function f(o: T): () => number {
  const t = o;
  if (t.t === "a") {
    return () => t.a;
  } else {
    return () => parseInt(t.b);
  }
}

var o = { t: "a", a: 0, b: "" };
var cb = f(o);
o.t = "b";
delete o.a;
cb(); // unexpected void, not number

samwgoldman avatar Oct 15 '15 19:10 samwgoldman

@samwgoldman just recapping from IRC:

  1. Yes, you're absolutely right. This is a case where a refinement on a const isn't guaranteed to hold throughout an entire program run.
  2. The abstract family of such cases are refinements whose tests depend on mutable sites within the value - sites which remain mutable even if the variable which holds the value is const. E.g. here the magic ingredients are:
    • the test is t.t === "a", explicitly involving a (mutable) property of the object, and
    • the implications of that test are at the top level, because the type is a tagged union - unlike property tests in general, which only refine the type of the property being tested (and are blown away as usual even if the host object is held in a const variable).
  3. This isn't very inspired, but I think the simplest solution here will be to
    • keep track of the refinement operation that produces a narrowed type (we currently install the tvar "output" of the refinement in the scope entry, but there's no direct back-pointer to the PredicateT operation itself), and
    • exclude refinements that depend on mutable internal state from the preservation behavior. Tagged unions are the poster child, but I could imagine there might be others, e.g. instanceof an interface type.

bhosmer avatar Oct 20 '15 07:10 bhosmer

0.18 will now hold onto refinements for const-bound variables. I confirmed changing the var to const in the original example has no errors.

samwgoldman avatar Oct 23 '15 23:10 samwgoldman

Here's a slightly more elaborate example where const does not help:

/** @flow */

type SeqMap = {[key: number]: string};

function getSequences(k: string): ?SeqMap {
  return (k == 'x') ? null : {};
}

function getAsString(k: string, start: number, stop: number): string {
  const seqs = getSequences(k);
  if (!seqs) return '';

  [].map(x => seqs[start] || '   ');
  return '';
}

and the errors:

hello.js:13
 13:   [].map(x => seqs[start] || '   ');
                   ^^^^^^^^^^^ access of computed property/element. Computed property/element cannot be accessed on possibly null value
 13:   [].map(x => seqs[start] || '   ');
                   ^^^^ null

hello.js:13
 13:   [].map(x => seqs[start] || '   ');
                   ^^^^^^^^^^^ access of computed property/element. Computed property/element cannot be accessed on possibly undefined value
 13:   [].map(x => seqs[start] || '   ');
                   ^^^^ undefined


Found 2 errors

Clearly Flow has lost the refinement, even with const.

danvk avatar Nov 12 '15 19:11 danvk

I tested on master and get no errors. Maybe I was mistaken about the const refinement commit, and it didn't make it into 0.18?

samwgoldman avatar Nov 12 '15 19:11 samwgoldman

Yep, I can confirm that this is no longer an error at HEAD. Guess I'll have to wait for the 0.19 release.

danvk avatar Nov 12 '15 19:11 danvk