Skip to main content

fic/ty/
foreign.rs

1//! Foreign surface types → fic types: one [`ForeignTypes`] implementation
2//! per [`ForeignLang`], chosen through [`lowering`]. The mirror of the
3//! backend's per-target ABI (#338): that maps a fic type to a machine
4//! type, this maps a language's spelling to a fic type: each language
5//! supplies its scalar table and its machine word; what every language
6//! shares at a C-ABI boundary (a pointer is an address, a struct is
7//! nominal) is [`signature`]'s, which `rast` lowers a called function's
8//! signature with.
9//!
10//! Widths are `AArch64` LP64 (AAPCS64): C `int` is 32 bits, `long` and
11//! pointers 64, plain `char` **unsigned**. A shared per-target data model
12//! is #360.
13
14use crate::ast::PrimitiveType;
15use crate::base::{StructId, TypeRef};
16use crate::foreign::{ForeignFn, ForeignLang, ForeignType};
17
18/// How one foreign language's types lower to fic types.
19pub trait ForeignTypes {
20    /// The language this lowering is for (named in diagnostics).
21    fn lang(&self) -> ForeignLang;
22
23    /// A scalar spelling → fic scalar; `None` when fic has no representation
24    /// for it in this language (`float`, an opaque typedef).
25    fn scalar(&self, spelling: &str) -> Option<PrimitiveType>;
26
27    /// The language's bare machine word ([`ForeignType::Word`]); `None`
28    /// unless the language has one.
29    fn word(&self) -> Option<PrimitiveType> {
30        None
31    }
32}
33
34/// C, as libclang spells types (`unsigned int`, `uint8_t`, `_Bool`).
35pub struct C;
36/// Pancake: every `export fun` argument and return is one machine word.
37pub struct Pancake;
38
39/// The lowering for `lang`.
40pub fn lowering(lang: ForeignLang) -> &'static dyn ForeignTypes {
41    match lang {
42        ForeignLang::C => &C,
43        ForeignLang::Pancake => &Pancake,
44    }
45}
46
47/// `f`'s parameter and return types as fic writes them, `f` declared in
48/// `lang`, or why fic cannot express it (a parameter or a non-`void`
49/// return with no fic type). `structs` resolves a struct name against the
50/// `.fis`'s.
51///
52/// # Errors
53///
54/// Which parameter, or the return, has no fic type.
55pub fn signature(
56    f: &ForeignFn,
57    lang: ForeignLang,
58    structs: &dyn Fn(&str) -> Option<StructId>,
59) -> Result<(Vec<TypeRef>, Option<TypeRef>), String> {
60    let mut params = Vec::with_capacity(f.params.len());
61    for (i, p) in f.params.iter().enumerate() {
62        let ty = type_ref(&p.ty, lang, structs).ok_or_else(|| {
63            let name = p
64                .name
65                .as_deref()
66                .map_or(String::new(), |n| format!(" ('{n}')"));
67            format!(
68                "parameter {}{name} has type '{}', which has no fic type",
69                i + 1,
70                spell(&p.ty)
71            )
72        })?;
73        params.push(ty);
74    }
75    let ret = match &f.ret {
76        ForeignType::Void => None,
77        t => Some(
78            type_ref(t, lang, structs)
79                .ok_or_else(|| format!("it returns '{}', which has no fic type", spell(t)))?,
80        ),
81    };
82    Ok((params, ret))
83}
84
85/// A foreign type as its language spells it, for a diagnostic.
86fn spell(t: &ForeignType) -> String {
87    match t {
88        ForeignType::Void => "void".to_owned(),
89        ForeignType::Scalar(s) => s.clone(),
90        ForeignType::Pointer(t) => format!("{} *", spell(t)),
91        ForeignType::Struct(name) => format!("struct {name}"),
92        ForeignType::Word => "a word".to_owned(),
93    }
94}
95
96/// A foreign value type as a fic type; `None` when fic has none for it.
97fn type_ref(
98    t: &ForeignType,
99    lang: ForeignLang,
100    structs: &dyn Fn(&str) -> Option<StructId>,
101) -> Option<TypeRef> {
102    match t {
103        ForeignType::Void => None,
104        ForeignType::Pointer(_) => Some(TypeRef::Prim(PrimitiveType::Address)),
105        ForeignType::Struct(name) => structs(name).map(TypeRef::Struct),
106        ForeignType::Word => lowering(lang).word().map(TypeRef::Prim),
107        ForeignType::Scalar(s) => lowering(lang).scalar(s).map(TypeRef::Prim),
108    }
109}
110
111impl ForeignTypes for C {
112    fn lang(&self) -> ForeignLang {
113        ForeignLang::C
114    }
115
116    fn scalar(&self, spelling: &str) -> Option<PrimitiveType> {
117        use PrimitiveType as P;
118        Some(match spelling {
119            // AAPCS64 §8.1: plain `char` is unsigned on AArch64.
120            "uint8_t" | "unsigned char" | "char" => P::UInt8,
121            "uint16_t" | "unsigned short" | "unsigned short int" => P::UInt16,
122            "uint32_t" | "unsigned" | "unsigned int" => P::UInt32,
123            "uint64_t"
124            | "unsigned long"
125            | "unsigned long int"
126            | "unsigned long long"
127            | "unsigned long long int"
128            | "size_t" => P::UInt64,
129            "int8_t" | "signed char" => P::Int8,
130            "int16_t" | "short" | "short int" | "signed short" | "signed short int" => P::Int16,
131            "int32_t" | "int" | "signed" | "signed int" => P::Int32,
132            "int64_t" | "long" | "long int" | "signed long" | "long long" | "long long int"
133            | "ssize_t" | "ptrdiff_t" => P::Int64,
134            "bool" | "_Bool" => P::Bool,
135            "uintptr_t" | "intptr_t" => P::Address,
136            _ => return None,
137        })
138    }
139}
140
141impl ForeignTypes for Pancake {
142    fn lang(&self) -> ForeignLang {
143        ForeignLang::Pancake
144    }
145
146    fn scalar(&self, _spelling: &str) -> Option<PrimitiveType> {
147        None
148    }
149
150    fn word(&self) -> Option<PrimitiveType> {
151        Some(PrimitiveType::UInt64)
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158    use crate::base::Idx;
159    use crate::foreign::ForeignParam;
160
161    #[test]
162    fn c_spellings_follow_aapcs64() {
163        for (spelling, expected) in [
164            ("uint8_t", PrimitiveType::UInt8),
165            ("unsigned char", PrimitiveType::UInt8),
166            ("char", PrimitiveType::UInt8), // unsigned on AArch64
167            ("signed char", PrimitiveType::Int8),
168            ("uint16_t", PrimitiveType::UInt16),
169            ("unsigned", PrimitiveType::UInt32),
170            ("unsigned int", PrimitiveType::UInt32),
171            ("size_t", PrimitiveType::UInt64),
172            ("unsigned long long", PrimitiveType::UInt64),
173            ("int", PrimitiveType::Int32),
174            ("long", PrimitiveType::Int64),
175            ("bool", PrimitiveType::Bool),
176            ("_Bool", PrimitiveType::Bool),
177            ("uintptr_t", PrimitiveType::Address),
178        ] {
179            assert_eq!(C.scalar(spelling), Some(expected), "{spelling}");
180        }
181        for bad in ["float", "cb_t"] {
182            assert_eq!(C.scalar(bad), None, "{bad}");
183        }
184        assert_eq!(C.word(), None);
185    }
186
187    #[test]
188    fn pancake_has_only_words() {
189        assert_eq!(Pancake.word(), Some(PrimitiveType::UInt64));
190        assert_eq!(Pancake.scalar("int"), None);
191    }
192
193    #[test]
194    fn lowering_dispatches_on_the_language() {
195        assert_eq!(lowering(ForeignLang::C).lang(), ForeignLang::C);
196        assert_eq!(lowering(ForeignLang::Pancake).lang(), ForeignLang::Pancake);
197    }
198
199    #[test]
200    fn a_signature_lowers_its_structs() {
201        let structs = |name: &str| match name {
202            "Slot" => Some(StructId::new(0)),
203            _ => None,
204        };
205        let f = |ret: ForeignType, params: Vec<ForeignType>| ForeignFn {
206            name: "f".to_owned(),
207            params: params
208                .into_iter()
209                .map(|ty| ForeignParam { name: None, ty })
210                .collect(),
211            ret,
212            variadic: false,
213            span: 0..0,
214        };
215        let scalar = |s: &str| ForeignType::Scalar(s.to_owned());
216        let (params, ret) = signature(
217            &f(
218                ForeignType::Void,
219                vec![
220                    scalar("int"),
221                    ForeignType::Struct("Slot".to_owned()),
222                    ForeignType::Pointer(Box::new(scalar("uint8_t"))),
223                ],
224            ),
225            ForeignLang::C,
226            &structs,
227        )
228        .expect("lowers");
229        assert_eq!(
230            params,
231            vec![
232                TypeRef::Prim(PrimitiveType::Int32),
233                TypeRef::Struct(StructId::new(0)),
234                TypeRef::Prim(PrimitiveType::Address),
235            ]
236        );
237        assert_eq!(ret, None);
238        // A struct fic does not know, or a scalar it cannot represent,
239        // says which.
240        assert_eq!(
241            signature(
242                &f(
243                    ForeignType::Void,
244                    vec![ForeignType::Struct("Nope".to_owned())]
245                ),
246                ForeignLang::C,
247                &structs
248            ),
249            Err("parameter 1 has type 'struct Nope', which has no fic type".to_owned())
250        );
251        assert_eq!(
252            signature(&f(scalar("float"), vec![]), ForeignLang::C, &structs),
253            Err("it returns 'float', which has no fic type".to_owned())
254        );
255        // A Pancake word.
256        let (_, ret) = signature(
257            &f(ForeignType::Word, vec![ForeignType::Word]),
258            ForeignLang::Pancake,
259            &structs,
260        )
261        .expect("lowers");
262        assert_eq!(ret, Some(TypeRef::Prim(PrimitiveType::UInt64)));
263    }
264}