Skip to main content

meta_language/translation/
source_signatures.rs

1//! Owned, opt-in facts from actual Rust function source headers.
2//! Value type checking remains in the existing checker; pure owner and
3//! wrapper decisions are translated from the shared JavaScript policy.
4use super::diagnostics::{Result, type_error};
5use super::rust::indirection_rules::accept_rust_source_lifetime_binding;
6use super::source_signature_rules::{
7    accept_rust_source_signature_model, accept_rust_source_signature_owner_kind,
8    accept_rust_source_signature_primitive, accept_rust_source_signature_wrapper,
9};
10use super::types::Type;
11use serde::{Deserialize, Serialize};
12
13/// A resolved owner of a source type, including owned generic children.
14#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(deny_unknown_fields)]
16pub struct SourceOwner {
17    /// Primitive, declaration, standard library, tuple, unit or slice.
18    pub kind: String,
19    /// Actual resolved owner segments, never a source text envelope.
20    pub path: Vec<String>,
21    /// Parsed child type owners in source argument order.
22    pub arguments: Vec<Self>,
23}
24
25/// One owned source parameter or result type and its erased qualifiers.
26#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
27#[serde(deny_unknown_fields)]
28pub struct SourceTypeSignature {
29    /// The value type resolved by the existing checker.
30    #[serde(rename = "type")]
31    pub ty: Type,
32    /// Pointer layers in their actual source order.
33    pub wrappers: Vec<String>,
34    /// One named or elided lifetime per reference layer.
35    pub lifetimes: Vec<Option<String>>,
36    /// Actual header owner, including resolved declaration identities.
37    pub owner: SourceOwner,
38}
39
40/// A source function signature, owned by its checked declaration.
41#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(rename_all = "camelCase", deny_unknown_fields)]
43pub struct SourceSignature {
44    /// Explicit selected source interpretation.
45    pub model: String,
46    /// The source header language.
47    pub language: String,
48    /// Actual parameter positions, matched to the function parameters.
49    pub parameters: Vec<SourceTypeSignature>,
50    /// Actual result position, matched to the function result.
51    pub result: SourceTypeSignature,
52    /// Parsed function lifetime binders in declaration order.
53    pub lifetime_bindings: Vec<String>,
54}
55
56fn fail(message: &str) -> super::diagnostics::TranslationError {
57    type_error(message, None)
58}
59
60fn validate_owner(owner: &SourceOwner, ty: &Type, depth: usize, visits: &mut usize) -> Result<()> {
61    *visits += 1;
62    if *visits > 100_000 || depth > 256 {
63        return Err(fail(
64            "an owned Rust source signature exceeds its resource limit",
65        ));
66    }
67    if !accept_rust_source_signature_owner_kind(&owner.kind)
68        || owner.path.iter().any(String::is_empty)
69    {
70        return Err(fail("an owned Rust source type has an invalid owner"));
71    }
72    let path = owner.path.join("::");
73    match owner.kind.as_str() {
74        "primitive" => {
75            let (bits, signed) = match ty {
76                Type::Fixed { bits, signed } => (bits.to_string(), *signed),
77                _ => (String::new(), false),
78            };
79            if owner.path.len() != 1
80                || !owner.arguments.is_empty()
81                || !accept_rust_source_signature_primitive(ty.kind(), &path, &bits, signed)
82            {
83                return Err(fail(
84                    "an owned Rust source primitive differs from its value type",
85                ));
86            }
87        }
88        "declaration" => {
89            if owner.path.is_empty()
90                || !owner.arguments.is_empty()
91                || !matches!(ty, Type::Data {name} if *name == owner.path.join("."))
92            {
93                return Err(fail(
94                    "an owned Rust source declaration differs from its value type",
95                ));
96            }
97        }
98        "unit" => {
99            if !owner.path.is_empty() || !owner.arguments.is_empty() || *ty != Type::Unit {
100                return Err(fail(
101                    "an owned Rust source unit differs from its value type",
102                ));
103            }
104        }
105        "tuple" => {
106            let Type::Tuple { elements } = ty else {
107                return Err(fail(
108                    "an owned Rust source tuple differs from its value type",
109                ));
110            };
111            if !owner.path.is_empty() || owner.arguments.len() != elements.len() {
112                return Err(fail(
113                    "an owned Rust source tuple differs from its value type",
114                ));
115            }
116            for (child, element) in owner.arguments.iter().zip(elements) {
117                validate_owner(child, element, depth + 1, visits)?;
118            }
119        }
120        "slice" | "library" if owner.kind == "slice" || path == "std::vec::Vec" => {
121            let Type::Array { element, .. } = ty else {
122                return Err(fail(
123                    "an owned Rust source array differs from its value type",
124                ));
125            };
126            if (owner.kind == "slice" && !owner.path.is_empty()) || owner.arguments.len() != 1 {
127                return Err(fail(
128                    "an owned Rust source array differs from its value type",
129                ));
130            }
131            validate_owner(&owner.arguments[0], element, depth + 1, visits)?;
132        }
133        "library" if path == "std::boxed::Box" || path == "alloc::boxed::Box" => {
134            if owner.arguments.len() != 1 {
135                return Err(fail("an owned Rust source box has invalid arguments"));
136            }
137            validate_owner(&owner.arguments[0], ty, depth + 1, visits)?;
138        }
139        "library" if path == "std::string::String" => {
140            if !owner.arguments.is_empty() || *ty != Type::String {
141                return Err(fail(
142                    "an owned Rust source string differs from its value type",
143                ));
144            }
145        }
146        _ => return Err(fail("an owned Rust source type has an unsupported owner")),
147    }
148    Ok(())
149}
150
151/// Check ownership and positional type agreement without source or provenance.
152///
153/// # Errors
154/// Refuses mismatched headers, unknown owners and unsupported qualifier facts.
155pub fn validate_source_signature(
156    signature: &SourceSignature,
157    parameters: &[Type],
158    result: &Type,
159    language: &str,
160) -> Result<()> {
161    if signature.model.is_empty()
162        || !accept_rust_source_signature_model(&signature.model)
163        || signature.language != "Rust"
164        || language != "Rust"
165    {
166        return Err(fail(
167            "an owned Rust source signature has an unsupported model or language",
168        ));
169    }
170    let unique: std::collections::HashSet<_> = signature.lifetime_bindings.iter().collect();
171    if signature.parameters.len() != parameters.len()
172        || unique.len() != signature.lifetime_bindings.len()
173        || signature
174            .lifetime_bindings
175            .iter()
176            .any(|name| !accept_rust_source_lifetime_binding(name, false, false))
177    {
178        return Err(fail(
179            "an owned Rust source signature has inconsistent parameter or lifetime bindings",
180        ));
181    }
182    let mut visits = 0;
183    for (position, expected) in signature
184        .parameters
185        .iter()
186        .zip(parameters)
187        .chain(std::iter::once((&signature.result, result)))
188    {
189        if !position.ty.same(expected) {
190            return Err(fail(
191                "an owned Rust source signature differs from its function type",
192            ));
193        }
194        if position
195            .wrappers
196            .iter()
197            .any(|wrapper| !accept_rust_source_signature_wrapper(wrapper))
198            || position.lifetimes.len()
199                != position
200                    .wrappers
201                    .iter()
202                    .filter(|wrapper| *wrapper == "reference")
203                    .count()
204            || position.lifetimes.iter().flatten().any(|lifetime| {
205                lifetime != "static"
206                    && lifetime != "_"
207                    && !signature.lifetime_bindings.contains(lifetime)
208            })
209        {
210            return Err(fail(
211                "an owned Rust source type has inconsistent wrapper or lifetime facts",
212            ));
213        }
214        validate_owner(&position.owner, &position.ty, 0, &mut visits)?;
215        let mut boxed = 0;
216        let mut leaf = &position.owner;
217        while leaf.kind == "library"
218            && ["std::boxed::Box", "alloc::boxed::Box"].contains(&leaf.path.join("::").as_str())
219        {
220            boxed += 1;
221            leaf = &leaf.arguments[0];
222        }
223        if boxed
224            != position
225                .wrappers
226                .iter()
227                .filter(|wrapper| *wrapper == "box")
228                .count()
229            || ((leaf.kind == "slice" || (leaf.kind == "primitive" && leaf.path[0] == "str"))
230                && !position
231                    .wrappers
232                    .iter()
233                    .any(|wrapper| wrapper == "reference"))
234        {
235            return Err(fail(
236                "an owned Rust source type has inconsistent owner and wrapper facts",
237            ));
238        }
239    }
240    Ok(())
241}