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
17 changes: 16 additions & 1 deletion compiler/crates/hy-check/src/freeze.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,11 @@ impl<'a> Checker<'a> {
}

fn emit_use_after_move(&mut self, st: &FnState, u: &Use, mv: &MoveInfo) {
let is_alias = st.aliases.contains_key(&u.name);
// A may-share peer (#27) is an alias in every way that matters here,
// even when the single-parent `aliases` chain does not name it (e.g.
// a projection or composite-literal capture).
let is_alias =
st.aliases.contains_key(&u.name) || st.may_share.contains_key(&u.name);
let orig = resolve_alias(st, &u.name);
let span_str = format!("{}:{}", mv.span.start.line, mv.span.start.col);

Expand Down Expand Up @@ -150,6 +154,17 @@ impl<'a> Checker<'a> {
members.push(a.clone());
}
}
// #27: a move also freezes everything that may share the same mutable
// GC storage — shallow struct/array copies, re-slices, field/index
// projections, and composite literals that embedded a live binding.
// The single-parent `aliases` chain above cannot express that graph,
// so union in the may-share connected component of every member.
let seeded = members.clone();
for m in seeded {
members.extend(st.share_group(&m));
}
members.sort();
members.dedup();
for m in &members {
if let Some(b) = st.env_lookup_mut(m) {
b.moved = Some(MoveInfo {
Expand Down
126 changes: 113 additions & 13 deletions compiler/crates/hy-check/src/loans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@

use crate::foreign::{self, CallMode};
use crate::model::{
as_addr_of, move_operand_ident, Binding, Checker, FnState, Loan, LoanTarget, MoveKind,
TypeShape,
as_addr_of, move_operand_ident, unwrap_parens, Binding, Checker, FnState, Loan, LoanTarget,
MoveKind, TypeShape,
};
use crate::shape::receiver_type_name;
use crate::walk::{self, CallRef};
Expand Down Expand Up @@ -362,15 +362,113 @@ impl<'a> Checker<'a> {
if is_view {
self.extend_call_loans_to_view(st, value, name, idx);
}
// alias recording: `m2 := agg` (reference-typed value)
if let Expr::Ident { name: src, .. } = value {
if let Some(b) = self.lookup_binding(st, src) {
if b.shape.is_reference_alias() {
st.aliases.insert(name.clone(), src.clone());
// may-share recording (#27): a shallow struct/array copy, a
// re-slice, a field/index projection, or a composite literal
// that embeds a live reference binding leaves `name` sharing
// mutable GC storage with its source — so a later `move` of
// either must freeze the other (O5.2). Supersedes the old
// bare-Identifier + reference-only check, which missed every
// one of those #27 forms.
self.record_may_share(st, name, value);
// keep the single-parent alias link for the plain-ident copy:
// it drives the friendlier "frozen alias" diagnostic and the
// existing cross-direction freeze (resolve_alias).
if let Expr::Ident { name: src, .. } = unwrap_parens(value) {
if self.binding_may_share(st, src) {
st.aliases.insert(name.clone(), src.clone());
}
}
}
}
}

/// Does the local binding `name` denote a value that a shallow Go copy
/// would share mutable GC storage with? Locals/params only (`const`
/// values are file-level immutables, not freeze participants).
fn binding_may_share(&self, st: &FnState, name: &str) -> bool {
st.env_lookup(name)
.map(|b| self.shape_may_share(&b.shape))
.unwrap_or(false)
}

/// Record may-share edges for a define/rebind `name <op> value` (#27).
/// Covers the four reported bypass forms: `h2 := h1` (shallow struct/
/// array copy), `m2 := (agg)` / `s2 := s1[:]` (parenthesized / re-sliced
/// RHS), `m2 := h1.m` (field/index projection), and `h := holder{m: agg}`
/// (composite literal capturing a live binding).
fn record_may_share(&self, st: &mut FnState, name: &str, value: &Expr) {
match unwrap_parens(value) {
Expr::Ident { name: src, .. } => {
if self.binding_may_share(st, src) {
st.share_edge(name, src);
}
}
// `s2 := s1[:]` — the result shares s1's backing array
Expr::Slice { base, .. } => {
if let Some(root) = unwrap_parens(base).root_ident() {
if self.binding_may_share(st, root) {
st.share_edge(name, root);
}
}
}
// `m2 := h1.m` / `m2 := arr[i]` — projecting a reference-bearing
// value out leaves it aliasing the composite it was read from
Expr::Field { .. } | Expr::Index { .. } => {
if self.shape_may_share(&self.shape_of_expr(st, unwrap_parens(value))) {
if let Some(root) = value.root_ident() {
if self.binding_may_share(st, root) {
st.share_edge(name, root);
}
}
}
}
// composite literals that embed live reference bindings
Expr::StructLit { fields, .. } => {
for f in fields {
self.record_literal_ref(st, name, &f.value);
}
}
Expr::MapLit { entries, .. } => {
for (k, v) in entries {
self.record_literal_ref(st, name, k);
self.record_literal_ref(st, name, v);
}
}
Expr::SliceLit { items, .. } => {
for it in items {
self.record_literal_ref(st, name, it);
}
}
_ => {}
}
}

/// Recursively collect live reference bindings embedded in a composite
/// literal and link them (may-share) to the freshly bound `name`.
fn record_literal_ref(&self, st: &mut FnState, name: &str, e: &Expr) {
match unwrap_parens(e) {
Expr::Ident { name: src, .. } => {
if self.binding_may_share(st, src) {
st.share_edge(name, src);
}
}
Expr::StructLit { fields, .. } => {
for f in fields {
self.record_literal_ref(st, name, &f.value);
}
}
Expr::MapLit { entries, .. } => {
for (k, v) in entries {
self.record_literal_ref(st, name, k);
self.record_literal_ref(st, name, v);
}
}
Expr::SliceLit { items, .. } => {
for it in items {
self.record_literal_ref(st, name, it);
}
}
_ => {}
}
}

Expand Down Expand Up @@ -413,6 +511,7 @@ impl<'a> Checker<'a> {
managed: bool,
) {
st.aliases.remove(name);
st.share_clear(name);
st.env_define(
name,
Binding {
Expand Down Expand Up @@ -507,13 +606,14 @@ impl<'a> Checker<'a> {
b.ty = ty.clone();
b.moved = None; // a fresh value re-owns the binding
}
// rebind may create a fresh alias
// a rebind re-owns the binding: drop the old alias and
// may-share edges, then re-record from the new value (#27)
st.aliases.remove(name);
if let Expr::Ident { name: src, .. } = &values[0] {
if let Some(b) = self.lookup_binding(st, src) {
if b.shape.is_reference_alias() {
st.aliases.insert(name.clone(), src.clone());
}
st.share_clear(name);
self.record_may_share(st, name, &values[0]);
if let Expr::Ident { name: src, .. } = unwrap_parens(&values[0]) {
if self.binding_may_share(st, src) {
st.aliases.insert(name.clone(), src.clone());
}
}
}
Expand Down
54 changes: 54 additions & 0 deletions compiler/crates/hy-check/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,14 @@ pub(crate) struct FnState {
/// alias name -> target binding name (binding-level only — enough for the
/// 20-program corpus; documented limitation).
pub aliases: HashMap<String, String>,
/// undirected may-share graph (#27): binding name -> names that may share
/// the same mutable GC storage. A Go assign `b := a` is a true alias only
/// for reference types, but a SHALLOW copy of a struct/array that carries
/// a reference field, a re-slice `s[:]`, a field/index projection, or a
/// composite literal that embeds a live binding all leave `b` sharing
/// storage with `a` too. The freeze rule (O5.2) must cover the whole
/// connected component, not just the single-parent `aliases` chain.
pub may_share: HashMap<String, HashSet<String>>,
pub loans: Vec<Loan>,
/// name -> last statement index that references it (Pass A result).
pub last_use: HashMap<String, usize>,
Expand Down Expand Up @@ -252,6 +260,52 @@ impl FnState {
self.env.insert(name.to_string(), b);
}
}

/// Record that `a` and `b` may share mutable GC storage (#27). Undirected:
/// a `move` of either must freeze the other.
pub(crate) fn share_edge(&mut self, a: &str, b: &str) {
if a == b {
return;
}
self.may_share
.entry(a.to_string())
.or_default()
.insert(b.to_string());
self.may_share
.entry(b.to_string())
.or_default()
.insert(a.to_string());
}

/// Drop `name`'s may-share edges: a whole-binding rebind re-owns the
/// binding, so it leaves the old sharing component.
pub(crate) fn share_clear(&mut self, name: &str) {
if let Some(peers) = self.may_share.remove(name) {
for p in peers {
if let Some(set) = self.may_share.get_mut(&p) {
set.remove(name);
}
}
}
}

/// The connected component of `name` under may-share, EXCLUDING `name`
/// itself (bounded to bindings that exist in this environment).
pub(crate) fn share_group(&self, name: &str) -> HashSet<String> {
let mut seen: HashSet<String> = HashSet::new();
let mut stack = vec![name.to_string()];
while let Some(n) = stack.pop() {
if let Some(peers) = self.may_share.get(&n) {
for p in peers {
if seen.insert(p.clone()) {
stack.push(p.clone());
}
}
}
}
seen.remove(name);
seen
}
}

// ---------------------------------------------------------------------------
Expand Down
37 changes: 37 additions & 0 deletions compiler/crates/hy-check/src/shape.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,43 @@ impl<'a> Checker<'a> {
}
}

/// May a value of this shape share mutable GC storage with a shallow Go
/// copy of it? True for reference types (map/slice/pointer), and — the
/// #27 gap — transitively true for a struct or array that CARRIES a
/// reference-typed field/element: Go copies such a value by value, but
/// the reference interior is shared. Used by the freeze rule's alias
/// tracking so `h2 := h1; task f(move h1)` freezes `h2` too.
///
/// `Unknown` is deliberately NOT may-share: an unresolvable shape makes
/// no aliasing claim (the boundary rules still fail closed on it). The
/// depth guard is conservative (deep/recursive struct types claim
/// sharing) and cannot loop on Go's acyclic value types.
pub(crate) fn shape_may_share(&self, shape: &TypeShape) -> bool {
self.shape_may_share_at(shape, 0)
}

fn shape_may_share_at(&self, shape: &TypeShape, depth: usize) -> bool {
if depth > 16 {
return true;
}
if shape.is_reference_alias() {
return true;
}
match shape {
TypeShape::Array(elem) => self.shape_may_share_at(elem, depth + 1),
TypeShape::Struct(Some(name)) => self
.structs
.get(name)
.map(|fields| {
fields.iter().any(|(_, ty)| {
self.shape_may_share_at(&self.shape_of_type(ty), depth + 1)
})
})
.unwrap_or(false),
_ => false,
}
}

/// Does this struct decl guard something with a `sync.*` lock? (Used for
/// the contested-04 note: "Tier 0 does not credit locks at spawn sites".)
pub(crate) fn struct_has_mutex_field(&self, sname: &str) -> bool {
Expand Down
Loading