Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,31 @@

## Unreleased

### Fixes from moving Rosaclef to 276dd1f

- An object-literal field's `/** @type {T} */` annotation checks its
initialiser, as a `const`'s does: `/** @type {() => Undefined} */ mark:
null` is an error ("expected '() => Undefined', found 'Null'"), where it
was accepted and `hooks.mark()` threw. A field that starts as `null` is
declared `T | Null`. (The `null` / `undefined` placeholder rule is gone.)
- An importer of a module that failed no longer reports errors in its own,
correct code ("Property 'bank' not found in type Boolean", "expected
'Boolean | Undefined', found '{pattern: …}'"). The failed module's names
are typed `Error`; a type variable that met one stayed free and was
pinned by its first use. It is now `Error` too: unifying with `Error`,
indexing an `Error` value, a constraint on one and a spread of one all
give `Error`.
- A binding written once after its initialiser, by a plain `x = e` in its
own function, is narrowed after that write: the get-or-create idiom
(`let x = m.get(k); if (!x) { x = []; m.set(k, x); } x.push(1);`) and
the `exec` loop (`while (m) { …m[1]…; m = re.exec(s); }`) type-check
without a `const` copy. See
[docs/flow-narrowing-safe.md](docs/flow-narrowing-safe.md), "Extension:
bindings written once".
- A tested property read again (`if (o.f) o.f()`) is still not narrowed:
a getter can give a different value to each read, and a type doesn't say
which fields are getters. Copy it into a `const` and test that.

### Multi-line annotations

Long type annotations can be written across lines, nicely laid out, and mean
Expand Down
4 changes: 4 additions & 0 deletions a.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export const hooks = {
/** @type {() => Undefined} */
mark: 3,
};
3 changes: 3 additions & 0 deletions b.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const hooks = {
mark /*: () => Undefined */: 3,
};
14 changes: 5 additions & 9 deletions crates/inty/src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -458,15 +458,11 @@ pub enum ChainSegment {
},
}

/// Where the annotation came from. Affects how inference treats the
/// initialiser. `Inline` annotations (TS-style `field: T` and the
/// inty-native `/*: T */`) check that the initialiser subsumes the
/// annotated type. `JsDoc` annotations (`/** @type {T} */`) follow
/// TypeScript's JSDoc semantics: a literal `null` / `undefined`
/// initialiser is treated as a placeholder and skipped — the
/// declaration is what types the field, not the seed value. This
/// matches the htmx-style `/** @type {typeof helper} */ field: null`
/// pattern that fills the field via later assignment.
/// Where the annotation came from. Either way the initialiser is
/// checked against the annotated type (a `null` start is declared
/// `T | Null`); a `JsDoc` annotation (`/** @type {T} */`) that doesn't
/// parse is ignored with a warning, as TypeScript ignores JSDoc it
/// doesn't understand, where an `Inline` one is an error.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AnnotationKind {
/// `/*: T */`, TS-style `field: T`, or `/** name: T */` doc form.
Expand Down
89 changes: 87 additions & 2 deletions crates/inty/src/ast/resolve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,33 @@ struct Binding {
read_before_init: bool,
/// How many functions enclose the declaration.
level: usize,
/// Writes after the initialiser.
writes: u32,
/// A write from a function nested inside the declaring one.
nested_write: bool,
/// Where the identifier of a plain `x = e` writing it is.
plain_write: Option<(usize, usize)>,
/// An occurrence in a function nested inside the declaring one.
captured: bool,
}

impl Binding {
/// The one write after the initialiser, when it is a plain `x = e`
/// in the declaring function, and the binding is otherwise stable.
fn sole_write(&self) -> Option<(usize, usize)> {
let declared_once = match self.kind {
Kind::Let | Kind::Param => true,
Kind::Var => {
self.declarators + self.fn_decls <= 1
&& (!self.has_init || (!self.init_in_loop && !self.read_before_init))
}
Kind::Const | Kind::Global => false,
};
(declared_once && self.writes == 1 && !self.nested_write)
.then_some(self.plain_write)
.flatten()
}

fn stable(&self) -> bool {
match self.kind {
Kind::Const => true,
Expand All @@ -97,6 +121,8 @@ impl Binding {
#[derive(Clone, Debug, Default)]
pub struct Resolution {
stable: Vec<bool>,
sole_write: Vec<Option<(usize, usize)>>,
captured: Vec<bool>,
constant: Vec<bool>,
global: Vec<bool>,
names: Vec<String>,
Expand All @@ -120,11 +146,15 @@ impl Resolution {
w.stmt(s);
}
let stable = w.bindings.iter().map(Binding::stable).collect();
let sole_write = w.bindings.iter().map(Binding::sole_write).collect();
let captured = w.bindings.iter().map(|b| b.captured).collect();
let constant = w.bindings.iter().map(|b| b.kind == Kind::Const).collect();
let global = w.bindings.iter().map(|b| b.kind == Kind::Global).collect();
let names = w.bindings.into_iter().map(|b| b.name).collect();
Resolution {
stable,
sole_write,
captured,
constant,
global,
names,
Expand Down Expand Up @@ -157,6 +187,30 @@ impl Resolution {
.is_some_and(|id| self.stable[id as usize])
}

/// Where the identifier of the one write of the binding `name` at
/// `span` refers to is, when that binding is written once after its
/// initialiser, by a plain `x = e` in the function that declares it
/// (not from a nested function), and is otherwise stable. Such a
/// binding holds its initial value until that write runs and a value
/// the write assigned ever after, which is what lets narrowing follow
/// it (`infer::narrow`, "filled bindings").
pub fn sole_write_at(&self, span: Span, name: &str) -> Option<(usize, usize)> {
let id = self.local_at(span, name)?;
self.sole_write[id as usize]
}

/// Whether the binding `id` is never written after its initialiser.
pub fn is_stable(&self, id: BindingId) -> bool {
self.stable.get(id as usize).copied().unwrap_or(false)
}

/// Whether the binding `name` at `span` refers to occurs in a function
/// nested inside the one that declares it.
pub fn captured_at(&self, span: Span, name: &str) -> bool {
self.local_at(span, name)
.is_some_and(|id| self.captured[id as usize])
}

/// Whether the identifier `name` at `span` refers to a binding that can't
/// be assigned: a `const`, or a named function expression's own name.
pub fn constant_at(&self, span: Span, name: &str) -> bool {
Expand Down Expand Up @@ -240,6 +294,10 @@ impl Walker {
init_in_loop: false,
read_before_init: false,
level: self.hoisted.len(),
writes: 0,
nested_write: false,
plain_write: None,
captured: false,
});
(self.bindings.len() - 1) as BindingId
}
Expand Down Expand Up @@ -331,13 +389,31 @@ impl Walker {
if b.kind == Kind::Var && early {
self.bindings[id as usize].read_before_init = true;
}
if self.hoisted.len() > self.bindings[id as usize].level {
self.bindings[id as usize].captured = true;
}
self.register(span, id);
id
}

/// The binding the occurrence of `name` at `span` was registered as.
fn binding_of(&self, name: &str, span: Span) -> Option<BindingId> {
self.occurrences
.get(&(span.start, span.end))?
.iter()
.copied()
.find(|&id| self.bindings[id as usize].name == name)
}

fn write(&mut self, name: &str, span: Span) {
let id = self.occurrence(name, span);
self.bindings[id as usize].assigned = true;
let level = self.hoisted.len();
let b = &mut self.bindings[id as usize];
b.assigned = true;
b.writes += 1;
if level > b.level {
b.nested_write = true;
}
}

/// Record the names an assignment target writes.
Expand Down Expand Up @@ -856,9 +932,18 @@ impl Walker {
self.expr(left);
self.expr(right);
}
Expr::Assign { left, right, .. } => {
Expr::Assign {
op, left, right, ..
} => {
self.expr(right);
self.write_target(left);
if let (crate::ast::AssignOp::Assign, Expr::Ident { name, span }) =
(op, left.as_ref())
{
if let Some(id) = self.binding_of(name, *span) {
self.bindings[id as usize].plain_write = Some((span.start, span.end));
}
}
}
Expr::Conditional {
test,
Expand Down
12 changes: 12 additions & 0 deletions crates/inty/src/builtins/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1093,6 +1093,18 @@ impl InferState {
// type that flowed in already failed inference; making its
// dependent uses fail their type-class checks too would
// produce one noise diagnostic per use site.
// What the constraint would have found out about a value of an
// `Error` type (an element, a field) is `Error` too: left a free
// variable, its first use would pin it (`const c = bad[i];
// c && c.f !== ""` made `c` a `Boolean`).
if let Some(first) = pred.types.first() {
if matches!(self.apply_subst(first), Type::Error) {
for t in &pred.types[1..] {
self.absorb_error(span, t);
}
return Ok(());
}
}
if pred
.types
.iter()
Expand Down
39 changes: 39 additions & 0 deletions crates/inty/src/infer/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,27 @@ impl TypeEnv {
out
}

/// A copy with `key`'s binding at its own scheme, not narrowed.
pub fn unnarrowed(&self, key: &Key) -> Self {
let Some(b) = self.lookup_key(key) else {
return self.clone();
};
let Some(declared) = b.declared.clone() else {
return self.clone();
};
let mutability = b.mutability;
let mut out = self.clone();
out.bindings.insert(
key.clone(),
Entry::new(Binding {
scheme: declared,
mutability,
declared: None,
}),
);
out
}

/// `name`'s own scheme, narrowed or not.
pub fn lookup_declared(&self, name: &str) -> Option<&TypeScheme> {
let b = self.lookup_binding(name)?;
Expand Down Expand Up @@ -254,6 +275,24 @@ impl TypeEnv {
out
}

/// A copy with the bindings `drop` picks at their own schemes.
pub fn without_narrowings_of(&self, drop: impl Fn(&Key) -> bool) -> Self {
let mut out = self.clone();
for (key, e) in &self.bindings {
if let (Some(declared), true) = (&e.binding.declared, drop(key)) {
out.bindings.insert(
key.clone(),
Entry::new(Binding {
scheme: declared.clone(),
mutability: e.binding.mutability,
declared: None,
}),
);
}
}
out
}

/// A copy with every binding's own scheme.
pub fn without_narrowings(&self) -> Self {
let mut out = self.clone();
Expand Down
3 changes: 3 additions & 0 deletions crates/inty/src/infer/features/arrays.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,9 @@ impl InferState {

// Try to resolve immediately for known types
match &obj_type_resolved {
// An element of a value whose type failed (an import from a
// module with errors) is one too, as a member read's is.
Type::Error => Ok(Type::Error),
Type::Array(elem_type) => {
// Array indexing: immediately unify index with Number and return element type
self.subsume(span, &index_type, &Type::Number)?;
Expand Down
30 changes: 26 additions & 4 deletions crates/inty/src/infer/features/bindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,14 @@ impl InferState {
}

/// Infer the type of an assignment.
/// Remember what a plain `x = e` assigned (see `assigned_values`).
fn record_assigned_value(&mut self, op: AssignOp, left: &Expr, value: &Type) {
if let (AssignOp::Assign, Expr::Ident { span, .. }) = (op, left) {
self.assigned_values
.insert((span.start, span.end), value.clone());
}
}

pub(in crate::infer) fn infer_assign(
&mut self,
env: &TypeEnv,
Expand All @@ -309,6 +317,17 @@ impl InferState {
right: &Expr,
span: Span,
) -> InferResult<Type> {
// A variable is stored to at its own type, not one a test or an
// earlier write narrowed it to (a binding written once, see
// `after_sole_write`); its value is read in `env` as it is.
let unnarrowed;
let store_env = match left {
Expr::Ident { name, span } => {
unnarrowed = env.unnarrowed(&self.key_of(*span, name));
&unnarrowed
}
_ => env,
};
// Check for assignment to immutable bindings
self.check_assignment_target(env, left, span)?;

Expand All @@ -318,21 +337,24 @@ impl InferState {
if op == AssignOp::Assign
&& matches!(right, Expr::Function { .. })
&& matches!(left, Expr::Member { .. } | Expr::Ident { .. })
&& lhs_polytype(self, env, left).is_none()
&& lhs_polytype(self, store_env, left).is_none()
{
let left_type = self.infer_store_target(env, left, span, true)?;
let left_type = self.infer_store_target(store_env, left, span, true)?;
if crate::infer::features::functions::extract_callable(&self.zonk_head(&left_type))
.is_some()
{
self.check_expr(env, right, &left_type)?;
self.record_assigned_value(op, left, &left_type);
return Ok(self.zonk_head_into(left_type));
}
let right_type = self.infer_expr(env, right)?;
self.subsume(span, &right_type, &left_type)?;
self.record_assigned_value(op, left, &right_type);
return Ok(self.zonk_head_into(left_type));
}

let right_type = self.infer_expr(env, right)?;
self.record_assigned_value(op, left, &right_type);

// Subsumption check: if the LHS resolves to a polymorphic scheme
// (a polymorphic var, or a polymorphic property of a polymorphic
Expand All @@ -357,7 +379,7 @@ impl InferState {
| AssignOp::LogicalAndAssign
| AssignOp::LogicalOrAssign
) {
if let Some(expected) = lhs_polytype(self, env, left) {
if let Some(expected) = lhs_polytype(self, store_env, left) {
let env_free_before = env.free_vars();
let (skolems, expected_ty) = self.skolemize(&expected);
self.unify(span, &expected_ty, &right_type)?;
Expand Down Expand Up @@ -387,7 +409,7 @@ impl InferState {
op,
AssignOp::Assign | AssignOp::NullishAssign | AssignOp::LogicalOrAssign
);
let left_type = self.infer_store_target(env, left, span, store_only)?;
let left_type = self.infer_store_target(store_env, left, span, store_only)?;
// `x &&= v` and `x ||= v` test `x`, as `&&` and `||` do.
if matches!(op, AssignOp::LogicalAndAssign | AssignOp::LogicalOrAssign) {
self.require_testable(&left_type, span)?;
Expand Down
Loading
Loading