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
48
49
50
51
52
53
54
55
56
57
58
59
use std::collections::HashMap;
use std::convert::TryFrom;
use std::fmt;
use std::fmt::{Display, Formatter};

use crate::check::context::arg::generic::GenericFunctionArg;
use crate::check::name::{Name, Substitute};
use crate::check::result::TypeErr;
use crate::common::position::Position;

pub const SELF: &str = "self";

pub mod generic;
pub mod python;

/// A Function argument.
///
/// May have a type.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct FunctionArg {
    pub is_py_type: bool,
    pub name: String,
    pub has_default: bool,
    pub vararg: bool,
    pub mutable: bool,
    pub ty: Option<Name>,
}

impl Display for FunctionArg {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(
            f,
            "{}{}{}",
            self.name,
            if let Some(ty) = &self.ty { format!(": {ty}") } else { String::new() },
            if self.has_default { "?" } else { "" }
        )
    }
}

impl TryFrom<(&GenericFunctionArg, &HashMap<Name, Name>, Position)> for FunctionArg {
    type Error = Vec<TypeErr>;

    fn try_from(
        (fun_arg, generics, pos): (&GenericFunctionArg, &HashMap<Name, Name>, Position)
    ) -> Result<Self, Self::Error> {
        Ok(FunctionArg {
            is_py_type: fun_arg.is_py_type,
            name: fun_arg.name.clone(),
            has_default: fun_arg.has_default,
            vararg: fun_arg.vararg,
            mutable: fun_arg.mutable,
            ty: match &fun_arg.ty {
                Some(ty) => Some(ty.substitute(generics, pos)?),
                None => None
            },
        })
    }
}