rils_frontend 0.4.0

Static analysis and semantic frontend for the Rils scripting language
Documentation
//! Recheck generic shared projections when concrete type arguments are known.

use super::*;

/// A projection whose permissions depend on a generic function's arguments.
/// The expression and span identify the original source, not a generated copy.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SharedProjectionConstraint {
    pub expression: crate::ExprId,
    pub span: Span,
    pub module_path: Vec<String>,
    pub value_type: Type,
    pub access: SharedAccess,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SharedAccess {
    Projection(Vec<SharedProjectionStep>),
    Clone,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SharedProjectionStep {
    pub object_type: Type,
    pub explicit_dereference: bool,
}

pub(crate) struct PendingProjection {
    pub owner_name: Span,
    pub constraint: SharedProjectionConstraint,
}

/// Report only proven violations. Unresolved types remain unchecked here;
/// runtime checks cover visible children but cannot inspect arbitrary opaque
/// native or host payloads.
pub fn check_shared_projection(
    declarations: &crate::semantic::DeclarationTypeResolver,
    constraint: &SharedProjectionConstraint,
    bindings: &HashMap<String, Type>,
) -> Option<AnalysisDiagnostic> {
    let (shared, message) = match &constraint.access {
        SharedAccess::Clone => (
            true,
            "cannot clone a mutable reference through a shared reference",
        ),
        SharedAccess::Projection(path) => (
            path.iter().any(|step| {
                let mut ty = declarations.resolve(
                    &step.object_type.substitute(bindings),
                    &constraint.module_path,
                );
                while let Type::Reference { mutable, inner } = ty {
                    if !mutable {
                        return true;
                    }
                    if step.explicit_dereference {
                        break;
                    }
                    ty = *inner;
                }
                false
            }),
            "cannot extract a mutable reference through a shared reference",
        ),
    };
    let value_type = constraint.value_type.substitute(bindings);
    let carries = match &constraint.access {
        SharedAccess::Clone => super::reference_permissions::clone_carries_mutable_reference(
            declarations,
            &constraint.module_path,
            &value_type,
        ),
        SharedAccess::Projection(_) => {
            carries_mutable_reference(declarations, &constraint.module_path, &value_type)
        }
    };
    (shared && carries).then(|| AnalysisDiagnostic::error(message, constraint.span))
}

impl Checker<'_> {
    pub(super) fn record_shared_projection(&mut self, expression: &Expr) {
        let Some(owner_name) = self.deferred_owner else {
            return;
        };
        let Some(value_type) = self.expression_types.get(expression).cloned() else {
            return;
        };
        let mut path_types = Vec::new();
        let mut current = expression;
        loop {
            let object = match current {
                Expr::Member { object, .. } | Expr::Index { object, .. } => object.as_ref(),
                Expr::Unary {
                    operator: UnaryOp::Dereference,
                    operand,
                    ..
                } => operand.as_ref(),
                _ => break,
            };
            if let Some(ty) = self.expression_types.get(object) {
                path_types.push(SharedProjectionStep {
                    object_type: ty.clone(),
                    explicit_dereference: matches!(current, Expr::Unary { .. }),
                });
            }
            current = object;
        }
        let expression_id = self
            .expression_types
            .id(expression)
            .expect("checked projection belongs to the indexed program");
        self.deferred_projections.push(PendingProjection {
            owner_name,
            constraint: SharedProjectionConstraint {
                expression: expression_id,
                span: expression.span(),
                module_path: self.module_path.clone(),
                value_type,
                access: SharedAccess::Projection(path_types),
            },
        });
    }

    pub(super) fn record_shared_clone(&mut self, expression: &Expr, owner: &Type) {
        let Some(owner_name) = self.deferred_owner else {
            return;
        };
        let expression_id = self
            .expression_types
            .id(expression)
            .expect("checked clone belongs to the indexed program");
        self.deferred_projections.push(PendingProjection {
            owner_name,
            constraint: SharedProjectionConstraint {
                expression: expression_id,
                span: expression.span(),
                module_path: self.module_path.clone(),
                value_type: owner.clone(),
                access: SharedAccess::Clone,
            },
        });
    }
}