1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
use ::syn::*;
use crate::helpers::*;

/// The std lib's `Option` type behavior.
pub struct Behavior;

impl super::Behavior for Behavior {
    fn is(&self, sty: &Type) -> bool {
        if let Type::Path(tp) = sty {
            is_same_id(&tp.path, "Option")
        } else {
            false
        }
    }
    fn imports(&self, _sty: &Type, pkg: &str, _crate_name: &str) -> Vec<String> {
        vec![format!("package:{}/dustr/option.dart", pkg)]
    }
    fn name(&self, _sty: &Type) -> String {
        panic!("option of option forbidden")
    }

    fn shim(&self, sty: &Type) -> String {
        let subtype = subtype(sty.clone());
        format!("Pointer<{}>", crate::types::switch(&subtype).shim(&subtype))
    }
    fn ffi(&self, sty: &Type) -> String {
        let subtype = subtype(sty.clone());
        format!("Pointer<{}>", crate::types::switch(&subtype).shim(&subtype))
    }
    fn native(&self, sty: &Type) -> String {
        let subtype = subtype(sty.clone());
        crate::types::switch(&subtype).native(&subtype)
    }

    fn native_to_ffi(&self, sty: &Type, expr: String) -> String {
        let subtype = subtype(sty.clone());
        format!("optional_{}({})", type_name_from_path(&subtype), expr)
    }
    fn ffi_to_native(&self, sty: &Type, expr: String) -> String {
        let subtype = subtype(sty.clone());
        format!(
            "({}.address == 0) ? null : {}",
            expr.clone(),
            crate::types::switch(&subtype).ffi_to_native(&subtype, format!("{}.value", expr)),
        )
    }
}