Skip to content
Merged
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
76 changes: 64 additions & 12 deletions compiler/crates/hy-check/src/freeze.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,26 @@ use hy_diag::Diagnostic;
use hy_syntax::Expr;
use std::collections::HashSet;

/// Follow an alias chain to its root (bounded: alias cycles are a parser
/// bug, not a checker concern, but never loop forever on one).
/// Follow an alias chain to its root. If a mutual rebind (`m2 := m; m = m2`)
/// created a cycle in `st.aliases`, return the lexicographically smallest
/// member of the cycle so every member of the cycle resolves to the same
/// canonical root.
pub(crate) fn resolve_alias(st: &FnState, name: &str) -> String {
let mut cur = name.to_string();
let mut seen: Vec<String> = vec![cur.clone()];
for _ in 0..16 {
match st.aliases.get(&cur) {
Some(next) => cur = next.clone(),
Some(next) => {
if let Some(pos) = seen.iter().position(|s| s == next) {
return seen[pos..]
.iter()
.min()
.cloned()
.unwrap_or_else(|| cur.clone());
}
cur = next.clone();
seen.push(cur.clone());
}
None => break,
}
}
Expand All @@ -30,22 +43,61 @@ impl<'a> Checker<'a> {
// Use-after-move / use-after-consume detection
// -----------------------------------------------------------------------

/// Check one statement's uses against the frozen state. One diagnostic
/// per (statement, binding): the first use site is reported.
/// Check one statement's uses against the frozen state, including
/// same-statement double-moves (`task both(move m, move m)`) and
/// same-statement move-plus-read (`a, b := move m, m`).
pub(crate) fn check_uses(&mut self, st: &FnState, uses: &[Use]) {
let mut reported: HashSet<String> = HashSet::new();
let mut stmt_moves: Vec<(String, String, MoveInfo)> = Vec::new();
for u in uses {
if !reported.insert(u.name.clone()) {
continue;
}
let moved = match self.lookup_binding(st, &u.name) {
Some(b) => b.moved.clone(),
None => continue,
};
let Some(mv) = moved else {
continue; // via_move uses of live bindings are transfers, exempt
};
self.emit_use_after_move(st, u, &mv);
if let Some(mv) = moved {
if reported.insert(u.name.clone()) {
self.emit_use_after_move(st, u, &mv);
}
continue;
}
let root = resolve_alias(st, &u.name);
if let Some((_, _, prior_mv)) = stmt_moves.iter().find(|(_, r, _)| r == &root) {
if reported.insert(format!("{}@{}", u.name, u.span.start.line)) {
self.emit_use_after_move(st, u, prior_mv);
}
continue;
}
if u.via_move {
stmt_moves.push((
u.name.clone(),
root,
MoveInfo {
span: u.span,
kind: MoveKind::Moved,
desc: format!("`move {}` earlier in the same statement", u.name),
},
));
}
}
// Also check if an earlier `non_via_move` read in the same statement
// preceded a `via_move` transfer of the same binding/alias group.
for u in uses {
if !u.via_move {
let root = resolve_alias(st, &u.name);
if let Some((mv_name, _, mv_info)) = stmt_moves
.iter()
.find(|(_, r, mv)| r == &root && mv.span != u.span)
{
if self
.lookup_binding(st, mv_name)
.map(|b| !b.shape.is_sendable_by_type())
.unwrap_or(false)
&& reported.insert(format!("{}@{}", u.name, u.span.start.line))
{
self.emit_use_after_move(st, u, mv_info);
}
}
}
}
}

Expand Down
160 changes: 159 additions & 1 deletion compiler/crates/hy-check/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -501,7 +501,9 @@ fn check_fn(ck: &mut Checker<'_>, f: &FnDecl) {
// the closure pass's capture view is the COMPLETED base env (A5) — a
// capture of a block-local now resolves to nothing and fails closed
// (HYB-E3005) at the boundary, exactly like any unresolvable name.
st.scopes.clear();
while !st.scopes.is_empty() {
st.scope_pop();
}

// Closure-boundary pass (closures.rs): task/send/select-send STATEMENTS
// inside closure bodies are concurrency boundaries in the emitted Go —
Expand Down Expand Up @@ -538,6 +540,162 @@ mod tests {
assert!(r.diagnostics.is_empty(), "{:?}", r.diagnostics);
}

#[test]
fn shadow_scope_does_not_wipe_outer_alias_e3003() {
// An inner block shadowing `m2 := 1` must not wipe the outer alias
// `m2 -> m`: moving `m` after the block (or inside the block) must
// still freeze outer `m2` (HYB-E3003).
let r_after = check(
"fn worker(m map[string]int, done chan<- bool) { m[\"k\"] = 1\n done <- true }\n\
fn main() {\n\
m := map[string]int{\"k\": 0}\n\
m2 := m\n\
if true {\n\
m2 := 1\n\
fmt.println(m2)\n\
}\n\
done := make(chan bool, 1)\n\
task worker(move m, done)\n\
m2[\"k\"] = 2\n\
}",
);
assert_eq!(
r_after.verdict,
Verdict::Reject,
"{:?}",
r_after.diagnostics
);
assert_eq!(first_error_rule(&r_after).as_deref(), Some("A1b"));
assert!(r_after.diagnostics.iter().any(|d| d.code == "HYB-E3003"));

let r_inside = check(
"fn worker(m map[string]int, done chan<- bool) { m[\"k\"] = 1\n done <- true }\n\
fn main() {\n\
m := map[string]int{\"k\": 0}\n\
m2 := m\n\
done := make(chan bool, 1)\n\
if true {\n\
m2 := 1\n\
fmt.println(m2)\n\
task worker(move m, done)\n\
}\n\
m2[\"k\"] = 2\n\
}",
);
assert_eq!(
r_inside.verdict,
Verdict::Reject,
"{:?}",
r_inside.diagnostics
);
assert_eq!(first_error_rule(&r_inside).as_deref(), Some("A1b"));
assert!(r_inside.diagnostics.iter().any(|d| d.code == "HYB-E3003"));
}

#[test]
fn mutual_alias_rebind_cycle_still_freezes_on_move_e3003() {
// `m2 := m; m = m2` used to create a 2-cycle `m <-> m2` where 16
// hops of `resolve_alias` resolved `"m"` to `"m"` and `"m2"` to `"m2"`,
// leaving `m2` unfrozen after `move m`.
let r = check(
"fn worker(m map[string]int, done chan<- bool) { m[\"k\"] = 1\n done <- true }\n\
fn main() {\n\
m := map[string]int{\"k\": 0}\n\
m2 := m\n\
m = m2\n\
done := make(chan bool, 1)\n\
task worker(move m, done)\n\
m2[\"k\"] = 2\n\
}",
);
assert_eq!(r.verdict, Verdict::Reject, "{:?}", r.diagnostics);
assert_eq!(first_error_rule(&r).as_deref(), Some("A1b"));
assert!(r.diagnostics.iter().any(|d| d.code == "HYB-E3003"));
}

#[test]
fn same_statement_double_move_and_move_plus_read_reject_e3003() {
// Moving the same binding (or its alias) twice in one statement, or
// moving and reading it in the same multi-define, must reject with HYB-E3003.
let r_spawn = check(
"fn both(a map[string]int, b map[string]int) { a[\"k\"] = 1\n b[\"k\"] = 2 }\n\
fn main() {\n\
m := map[string]int{\"k\": 0}\n\
task both(move m, move m)\n\
}",
);
assert_eq!(
r_spawn.verdict,
Verdict::Reject,
"{:?}",
r_spawn.diagnostics
);
assert!(r_spawn.diagnostics.iter().any(|d| d.code == "HYB-E3003"));

let r_multi = check(
"fn worker(m map[string]int, done chan<- bool) { m[\"k\"] = 1\n done <- true }\n\
fn main() {\n\
m := map[string]int{\"k\": 0}\n\
a, b := move m, move m\n\
done := make(chan bool, 1)\n\
task worker(move a, done)\n\
b[\"k\"] = 2\n\
}",
);
assert_eq!(
r_multi.verdict,
Verdict::Reject,
"{:?}",
r_multi.diagnostics
);
assert!(r_multi.diagnostics.iter().any(|d| d.code == "HYB-E3003"));

let r_move_and_read = check(
"fn worker(m map[string]int, done chan<- bool) { m[\"k\"] = 1\n done <- true }\n\
fn main() {\n\
m := map[string]int{\"k\": 0}\n\
a, b := move m, m\n\
done := make(chan bool, 1)\n\
task worker(move a, done)\n\
b[\"k\"] = 2\n\
}",
);
assert_eq!(
r_move_and_read.verdict,
Verdict::Reject,
"{:?}",
r_move_and_read.diagnostics
);
assert!(r_move_and_read
.diagnostics
.iter()
.any(|d| d.code == "HYB-E3003"));

// Shadowing the outer root `m` (`m := 1`) inside a block before moving
// an alias `m2` of the outer `m` must still freeze the outer `m`.
let r_shadow_root = check(
"fn worker(m map[string]int, done chan<- bool) { m[\"k\"] = 1\n done <- true }\n\
fn main() {\n\
m := map[string]int{\"k\": 0}\n\
done := make(chan bool, 1)\n\
if true {\n\
m2 := m\n\
m := 1\n\
task worker(move m2, done)\n\
_ = m\n\
}\n\
m[\"k\"] = 2\n\
}",
);
assert_eq!(
r_shadow_root.verdict,
Verdict::Reject,
"{:?}",
r_shadow_root.diagnostics
);
assert_eq!(first_error_rule(&r_shadow_root).as_deref(), Some("A1b"));
}

#[test]
fn a1c_spawn_shared_map_rejects() {
let r = check(
Expand Down
56 changes: 56 additions & 0 deletions compiler/crates/hy-check/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,14 @@ pub(crate) struct Loan {
pub(crate) struct FnState {
/// The function's BASE scope: receiver, params, and top-level defines.
pub env: HashMap<String, Binding>,
/// Saved alias maps for outer scopes when entering block scopes so an
/// inner shadowing define (`if true { m2 := 1 }`) cannot wipe outer
/// alias links (`m2 -> m`).
pub alias_scopes: Vec<HashMap<String, String>>,
/// Same discipline for the may-share edges (the seam's second freeze
/// map, pr-35): a shadowing define's `share_clear` must not survive the
/// block either — the snapshot restores at pop.
pub share_scopes: Vec<HashMap<String, HashSet<String>>>,
/// Block scopes, innermost last (issue #14): a define inside a nested
/// block lands in the top layer and DIES at block exit, so an inner
/// `m := 1` can no longer overwrite the outer `m`'s binding and launder
Expand Down Expand Up @@ -226,11 +234,59 @@ impl FnState {
/// Enter a block scope (walk.rs's Push events).
pub(crate) fn scope_push(&mut self) {
self.scopes.push(HashMap::new());
self.alias_scopes.push(self.aliases.clone());
self.share_scopes.push(self.may_share.clone());
}

/// Exit the innermost block scope (walk.rs's Pop events).
pub(crate) fn scope_pop(&mut self) {
// Capture any moves on inner aliases before the inner scope and alias
// map are popped (handles the case where an inner alias `m2 := m` was
// moved while the outer root `m` was shadowed inside the block).
let mut inner_root_moves: Vec<(String, MoveInfo)> = Vec::new();
for (a, target) in &self.aliases {
let root = crate::freeze::resolve_alias(self, target);
if let Some(mv) = self.env_lookup(a).and_then(|b| b.moved.clone()) {
inner_root_moves.push((root, mv));
}
}
self.scopes.pop();
if let Some(outer_aliases) = self.alias_scopes.pop() {
self.aliases = outer_aliases;
if let Some(outer_share) = self.share_scopes.pop() {
self.may_share = outer_share;
}
for (root, mv) in inner_root_moves {
if let Some(br) = self.env_lookup_mut(&root) {
if br.moved.is_none() {
br.moved = Some(mv);
}
}
}
// If an outer binding was moved while one of its outer aliases
// was shadowed inside the block, propagate the freeze across the
// restored outer alias group now that the shadow has died.
let keys: Vec<String> = self.aliases.keys().cloned().collect();
for a in keys {
let root = crate::freeze::resolve_alias(self, &a);
let moved = self
.env_lookup(&root)
.and_then(|b| b.moved.clone())
.or_else(|| self.env_lookup(&a).and_then(|b| b.moved.clone()));
if let Some(mv) = moved {
if let Some(ba) = self.env_lookup_mut(&a) {
if ba.moved.is_none() {
ba.moved = Some(mv.clone());
}
}
if let Some(br) = self.env_lookup_mut(&root) {
if br.moved.is_none() {
br.moved = Some(mv);
}
}
}
}
}
}

/// Innermost-first binding lookup (scopes, then the base env).
Expand Down
Loading