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
64 changes: 63 additions & 1 deletion crates/pyrefly_types/src/simplify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,68 @@ fn simplify_intersections(xs: &mut [Type], heap: &TypeHeap) {
}
}

fn large_alias_union_display_name(xs: &[Type]) -> Option<Box<str>> {
const PRESERVE_LARGE_ALIAS_DISPLAY_MIN_MEMBERS: usize = 2;

let mut alias_name: Option<String> = None;
let mut alias_members: Option<Vec<Type>> = None;
let mut alias_count = 0;
let mut other_branches = Vec::new();
for x in xs.iter().cloned() {
match x {
Type::Union(box Union {
members,
display_name: Some(name),
}) if members.len() >= PRESERVE_LARGE_ALIAS_DISPLAY_MIN_MEMBERS => {
alias_count += 1;
if alias_name.is_none() {
alias_name = Some(name.into_string());
alias_members = Some(members.clone());
}
}
t => other_branches.push(t),
}
}

if alias_count == 1 && !other_branches.is_empty() {
let overlaps_alias_member = |t: &Type| {
let Some(alias_members) = alias_members.as_ref() else {
return false;
};
fn has_overlap(t: &Type, alias_members: &[Type]) -> bool {
match t {
Type::Union(box Union { members, .. }) => {
members.iter().any(|m| has_overlap(m, alias_members))
}
t => alias_members.contains(t),
}
}
has_overlap(t, alias_members)
};
if other_branches.iter().any(overlaps_alias_member) {
return None;
}

other_branches.sort();
other_branches.dedup();
let other = other_branches
.iter()
.map(|t| t.to_string())
.collect::<Vec<_>>()
.join(" | ");
alias_name.map(|name| format!("{name} | {other}").into_boxed_str())
} else {
None
}
}

fn unions_internal(
xs: Vec<Type>,
stdlib: Option<&Stdlib>,
enum_members: Option<&dyn Fn(&Class) -> Option<usize>>,
heap: &TypeHeap,
) -> Type {
let large_alias_display_name = large_alias_union_display_name(&xs);
try_collapse(xs, heap).unwrap_or_else(|xs| {
let mut res = flatten_and_dedup(xs, heap);
if let Some(stdlib) = stdlib {
Expand All @@ -81,7 +137,13 @@ fn unions_internal(
}
collapse_tuple_unions_with_empty(&mut res, heap);
// `res` is collapsible again if `flatten_and_dedup` drops `xs` to 0 or 1 elements
try_collapse(res, heap).unwrap_or_else(|members| heap.mk_union(members))
try_collapse(res, heap).unwrap_or_else(|members| {
if let Some(name) = large_alias_display_name.clone() {
heap.mk_union_with_name(members, name)
} else {
heap.mk_union(members)
}
})
})
}

Expand Down
27 changes: 21 additions & 6 deletions pyrefly/lib/alt/solve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1390,12 +1390,27 @@ impl<'a, Ans: LookupAnswer> AnswersSolver<'a, Ans> {
self.scoped_type_params(scoped_tparams.as_ref(), errors)
}
};
Forallable::TypeAlias(TypeAliasData::Value(ta)).forall(self.validated_tparams(
range,
tparams,
TParamsSource::TypeAlias,
errors,
))
let validated_tparams =
self.validated_tparams(range, tparams, TParamsSource::TypeAlias, errors);
if validated_tparams.is_empty() {
let name = name.as_str();
match ta.as_type_mut() {
Type::Union(box Union { display_name, .. }) => {
if display_name.is_none() {
*display_name = Some(name.into());
}
}
Type::Type(inner) => {
if let Type::Union(box Union { display_name, .. }) = inner.as_mut()
&& display_name.is_none()
{
*display_name = Some(name.into());
}
}
_ => {}
}
}
Forallable::TypeAlias(TypeAliasData::Value(ta)).forall(validated_tparams)
}

/// Create TParams for a recursive reference to a type alias. This is essentially a
Expand Down
106 changes: 106 additions & 0 deletions pyrefly/lib/test/decorators.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,104 @@
use crate::test::util::TestEnv;
use crate::testcase;

fn env_with_flask_typing_alias() -> TestEnv {
let mut env = TestEnv::new();
env.add(
"flask.typing",
r#"
from __future__ import annotations
import typing as t

ResponseValue = t.Union[
str,
bytes,
dict[str, t.Any],
list[t.Any],
]

HeadersValue = t.Union[
dict[str, str],
list[tuple[str, str]],
]

ResponseReturnValue = t.Union[
ResponseValue,
tuple[ResponseValue, int],
tuple[ResponseValue, int, HeadersValue],
]
"#,
);
env.add(
"flask",
r#"
from __future__ import annotations
from collections.abc import Callable
from typing import ParamSpec, TypeVar

from flask.typing import ResponseReturnValue

P = ParamSpec("P")
R = TypeVar("R")

class LoginManager:
def unauthorized(self) -> ResponseReturnValue: ...

class App:
login_manager: LoginManager

def ensure_sync(self, func: Callable[P, R]) -> Callable[P, R]: ...

current_app: App
"#,
);
env.add(
"libs.login",
r#"
from __future__ import annotations
from collections.abc import Callable
from functools import wraps
from typing import ParamSpec, TypeVar

from flask import current_app

P = ParamSpec("P")
R = TypeVar("R")

def login_required(func: Callable[P, R]):
@wraps(func)
def decorated_view(*args: P.args, **kwargs: P.kwargs):
if args:
return current_app.login_manager.unauthorized()
return current_app.ensure_sync(func)(*args, **kwargs)
return decorated_view
"#,
);
env.add(
"controllers.console.wraps",
r#"
from __future__ import annotations
from collections.abc import Callable

def setup_required(view: Callable[..., int]) -> Callable[..., int]: ...
"#,
);
env.add(
"controllers.console.app.mcp_server",
r#"
from __future__ import annotations

from controllers.console.wraps import setup_required
from libs.login import login_required

@setup_required # E: Argument `(*args: Unknown, **kwargs: Unknown) -> ResponseReturnValue | R` is not assignable to parameter `view` with type `(...) -> int` in function `controllers.console.wraps.setup_required`
@login_required
def handler(*args, **kwargs) -> int:
return 0
"#,
);
env
}

testcase!(
test_simple_function_decorator,
r#"
Expand Down Expand Up @@ -412,6 +510,14 @@ def f0(arg: Callable[..., int]) -> Callable[..., int]: ...
"#,
);

testcase!(
test_decorator_error_uses_external_union_alias,
env_with_flask_typing_alias(),
r#"
import controllers.console.app.mcp_server
"#,
);

// Reported in https://github.com/facebook/pyrefly/issues/491
testcase!(
test_total_ordering,
Expand Down
2 changes: 1 addition & 1 deletion pyrefly/lib/test/type_alias.rs
Original file line number Diff line number Diff line change
Expand Up @@ -887,7 +887,7 @@ x4: TA | C = object() # E: `object` is not assignable to `C | int | str`
x5: TA | C = val1
x6: TA | C = val2
x7: TA | C = C()
c2: Callable[[int], int] = f2 # E: `(x: C | int | str) -> C | int | str` is not assignable to `(int) -> int`
c2: Callable[[int], int] = f2 # E: `(x: TA | C) -> TA | C` is not assignable to `(int) -> int`
"#,
);

Expand Down