Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
40 changes: 35 additions & 5 deletions src/v3/compiler/src/dag.rs
Original file line number Diff line number Diff line change
Expand Up @@ -600,24 +600,36 @@ pub struct ValueNode {
/// `OperatorKind` enum is only a lookup key, not a parallel
/// authority.
///
/// 4-pattern check on (Callable, Operator):
/// 4-pattern check on (Callable, FieldProject, Operator):
/// - Pattern 1 (fact placement): fails. Callable dispatches via
/// the declaration's Arrow body; Operator dispatches via the
/// the declaration's Arrow body; FieldProject dispatches via a
/// parent Conj + field label; Operator dispatches via the
/// operand type's algebra walk.
/// - Pattern 2 (variant-is-data): fails. Callable carries a
/// DeclarationId; Operator carries an OperatorKind.
/// DeclarationId; FieldProject carries a `(DeclarationId,
/// String)` pair; Operator carries an OperatorKind.
/// - Pattern 3 (algebraic form): fails.
/// - Pattern 4 (dimensional): fails.
///
/// Verdict: mixed lifecycle. `Callable` is terminal;
/// Verdict: mixed lifecycle. `Callable` and `FieldProject` are
/// terminal;
/// `Operator` is 🟡 scaffold with an explicit M2+ dissolution
/// trigger (surface grammar adoption of direct algebra field
/// access or a parse-time desugaring pass).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TransformTarget {
/// A user function or resolved declaration. Inference walks the
/// referenced declaration's `Arrow` connective via `resolve_arrow`.
Callable(DeclarationId),
/// Structural projection on a Conj-typed parent value. The
/// `parent_type` is the declaration lowered from the input
/// port's type at the point the projection is emitted; the
/// `field_label` names the child field to project. No synthesized
/// accessor declaration, no name recovery from an Arrow target.
FieldProject {
parent_type: DeclarationId,
field_label: String,
},
/// A primitive binary operator. Inference dispatches on the
/// `OperatorKind` variant directly: arithmetic returns the operand
/// type, comparison returns Bool. No declaration is allocated.
Expand Down Expand Up @@ -687,6 +699,20 @@ pub enum BranchPattern {
ResolvedVariant(DeclarationId),
}

#[derive(Debug, Clone)]
pub struct PayloadBinding {
/// Authored arm-local name from the surface pattern
/// (`Some(payload)` -> `"payload"`). Lowering consumes it to
/// extend the arm-local scope; inference does not consult it.
/// It remains on the substrate as carry-forward for readable
/// downstream rendering.
pub binding_name: String,
/// Typed port carrying the variant payload value for this arm.
/// Lowering allocates and types the port when it unwraps a
/// single-positional variant payload.
pub payload_port: PortId,
}

#[derive(Debug, Clone)]
pub struct Path {
pub body: NodeId,
Expand All @@ -695,6 +721,10 @@ pub struct Path {
/// Discriminator for both `if`/`else` (on Bool) and `match`
/// (on any Disj). See `BranchPattern`.
pub pattern: BranchPattern,
/// Optional payload extraction for this arm. Present for
/// `Variant(binding)` surface patterns; absent for bare-variant
/// arms and `if`/`else`.
pub binding: Option<PayloadBinding>,
}

#[derive(Debug, Clone)]
Expand Down
63 changes: 61 additions & 2 deletions src/v3/compiler/src/emit_rust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -550,15 +550,33 @@ impl<'a> Ctx<'a> {
}

fn render_transform(&self, t: &TransformNode) -> Result<String, EmitError> {
match t.target {
TransformTarget::Operator(op) => self.render_operator(t, op),
match &t.target {
TransformTarget::Operator(op) => self.render_operator(t, *op),
TransformTarget::FieldProject { field_label, .. } => {
self.render_field_project(t, field_label)
}
TransformTarget::Callable(_) => Err(EmitError::UnsupportedBehavior(
"TransformTarget::Callable (user function call) is not yet supported by emit_rust"
.to_string(),
)),
}
}

fn render_field_project(
&self,
t: &TransformNode,
field_label: &str,
) -> Result<String, EmitError> {
if t.inputs.len() != 1 {
return Err(EmitError::UnsupportedBehavior(format!(
"field projection .{field_label} arity {} is not supported; expected exactly one parent input",
t.inputs.len()
)));
}
let parent_expr = self.render_port(t.inputs[0])?;
Ok(format!("{parent_expr}.{field_label}"))
}

fn render_operator(
&self,
t: &TransformNode,
Expand Down Expand Up @@ -826,3 +844,44 @@ fn walk_to_algebra_conj(dag: &Dag, start: DeclarationId) -> Option<DeclarationId
}
None
}

#[cfg(test)]
mod tests {
use super::*;
use crate::diagnostics::SourceSpan;

#[test]
fn render_field_project_emits_parent_dot_field() {
let mut dag = Dag::new();
let parent_port = dag.alloc_port(None);
let node_id = dag.alloc_node_id();
let output = dag.alloc_port(Some(node_id));
let parent_type = dag.declarations()[0].id;
dag.push_node(Behavior::Transform(TransformNode {
id: node_id,
target: TransformTarget::FieldProject {
parent_type,
field_label: "value".to_string(),
},
inputs: vec![parent_port],
output,
span: SourceSpan::new("<test>", 0, 0),
}));

let indexes = RealizationIndexes::build(&dag).expect("indexes build");
let mut bound_names = HashMap::new();
bound_names.insert(parent_port, "parent".to_string());
let ctx = Ctx {
dag: &dag,
indexes: &indexes,
branch_marker: dag.branch_marker().expect("branch marker"),
bound_names: &bound_names,
};

let rendered = match dag.node(node_id) {
Behavior::Transform(t) => ctx.render_transform(t).expect("field project renders"),
other => panic!("expected Transform node, got {other:?}"),
};
assert_eq!(rendered, "parent.value");
}
}
131 changes: 131 additions & 0 deletions src/v3/compiler/src/infer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,12 @@ fn decide_transform(dag: &Dag, t: &TransformNode) -> Decision {
// `resolve_arrow` through any Instantiation / ResolvedIdentifier
// chain to recover the concrete Arrow signature.
let signature = match &t.target {
TransformTarget::FieldProject {
parent_type,
field_label,
} => {
return decide_field_project(dag, t, *parent_type, field_label);
}
TransformTarget::Operator(op_kind) => {
let lhs_type = match t.inputs.first() {
None => {
Expand Down Expand Up @@ -699,6 +705,109 @@ impl SubstStack {
}
}

fn decide_field_project(
dag: &Dag,
t: &TransformNode,
parent_type: DeclarationId,
field_label: &str,
) -> Decision {
if t.inputs.len() != 1 {
return Decision::Fail(
t.output,
Diagnostic::ArityMismatch {
function: format!(".{field_label}"),
expected: 1,
actual: t.inputs.len(),
span: t.span.clone(),
},
);
}

let input_ty = match dag.port(t.inputs[0]).state() {
PortState::Uninferred => return Decision::Retry,
PortState::Unresolved => {
return Decision::Fail(
t.output,
Diagnostic::ResolveError {
name: format!("(upstream failure in field `{field_label}`)"),
span: t.span.clone(),
},
);
}
PortState::Resolved(ty) => *ty,
};

let Some(expected_conj_id) = walk_to_conj_decl(dag, parent_type) else {
return Decision::Fail(
t.output,
Diagnostic::ResolveError {
name: format!(
"field `{field_label}` cannot be projected from `{}` because it does not walk to a Conj type",
target_display_name(dag, parent_type),
),
span: t.span.clone(),
},
);
};
let Some(actual_conj_id) = walk_to_conj_decl(dag, input_ty.declaration) else {
return Decision::Fail(
t.output,
Diagnostic::ResolveError {
name: format!(
"field `{field_label}` cannot be projected from `{}` because it does not walk to a Conj type",
target_display_name(dag, input_ty.declaration),
),
span: t.span.clone(),
},
);
};
if expected_conj_id != actual_conj_id {
return Decision::Fail(
t.output,
Diagnostic::TypeMismatch {
expected: TypeShape::new(parent_type),
actual: input_ty,
span: t.span.clone(),
},
);
}

let children = match &dag.declaration(expected_conj_id).connective {
TypeConnective::Conj { children } => children,
_ => unreachable!("walk_to_conj_decl returned a non-Conj declaration"),
};
let Some(field_decl_id) = children
.iter()
.find(|field| field.label == field_label)
.map(|field| field.ty)
else {
return Decision::Fail(
t.output,
Diagnostic::ResolveError {
name: format!(
"field `{field_label}` does not exist on `{}`",
target_display_name(dag, parent_type),
),
span: t.span.clone(),
},
);
};
let Some(output_ty) = walk_to_type_shape(dag, field_decl_id, &SubstStack::new(), 0) else {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Substitute template args when inferring field projection output

decide_field_project computes the projected field type with walk_to_type_shape(..., &SubstStack::new(), ...), which drops any instantiation context from parent_type. For generic records (e.g., Box<Int> with field type T), this either fails (TypeParam lookup has no substitution) or yields an unsubstituted type, so valid projections like b.value cannot type-resolve correctly.

Useful? React with 👍 / 👎.

return Decision::Fail(
t.output,
Diagnostic::ResolveError {
name: format!(
"field `{field_label}` on `{}` does not resolve to a port type",
target_display_name(dag, parent_type),
),
span: t.span.clone(),
},
);
};

Decision::Set(t.output, output_ty)
}

const WALK_DEPTH_LIMIT: usize = 32;

/// §8.9 operator dispatch via structural algebra walk.
Expand Down Expand Up @@ -1043,6 +1152,24 @@ fn walk_to_type_shape(
}
}

fn walk_to_conj_decl(dag: &Dag, start: DeclarationId) -> Option<DeclarationId> {
let mut current = start;
for _ in 0..WALK_DEPTH_LIMIT {
let decl = dag.declaration(current);
match &decl.connective {
TypeConnective::Conj { .. } => return Some(current),
TypeConnective::Instantiation { template, .. } => {
current = *template;
}
TypeConnective::Atom(AtomPayload::ResolvedIdentifier(next)) => {
current = *next;
}
_ => return None,
}
}
None
}

/// Best-effort human-readable name for a Transform.target DeclarationId,
/// used in diagnostics. Walks through resolved Identifier atoms to find
/// something nameable.
Expand All @@ -1066,6 +1193,10 @@ fn target_display_name(dag: &Dag, target: DeclarationId) -> String {
fn transform_target_display_name(dag: &Dag, target: &TransformTarget) -> String {
match target {
TransformTarget::Callable(id) => target_display_name(dag, *id),
TransformTarget::FieldProject {
parent_type,
field_label,
} => format!("{}.{}", target_display_name(dag, *parent_type), field_label),
TransformTarget::Operator(op_kind) => op_kind.symbol().to_string(),
}
}
Expand Down
Loading
Loading