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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
use std::collections::HashSet;
use std::convert::TryFrom;
use std::hash::{Hash, Hasher};
use std::ops::Deref;

use crate::check::ident::Identifier;
use crate::check::name::match_name;
use crate::check::name::Name;
use crate::check::name::string_name::StringName;
use crate::check::result::{TypeErr, TypeResult};
use crate::common::position::Position;
use crate::parse::ast::{AST, Node};

#[derive(Debug, Clone, Eq)]
pub struct GenericField {
    pub is_py_type: bool,
    pub name: String,
    pub pos: Position,
    pub mutable: bool,
    pub in_class: Option<StringName>,
    pub ty: Option<Name>,
    pub assigned_to: bool,
}

pub struct GenericFields {
    pub fields: HashSet<GenericField>,
}

impl Hash for GenericField {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.name.hash(state)
    }
}

impl PartialEq for GenericField {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
    }
}

impl TryFrom<&AST> for GenericField {
    type Error = Vec<TypeErr>;

    fn try_from(ast: &AST) -> TypeResult<GenericField> {
        match &ast.node {
            Node::VariableDef { var, mutable, ty, expr, .. } => Ok(GenericField {
                is_py_type: false,
                name: field_name(var.deref())?,
                mutable: *mutable,
                pos: ast.pos,
                in_class: None,
                ty: match ty {
                    Some(ty) => Some(Name::try_from(ty.deref())?),
                    None => None,
                },
                assigned_to: expr.is_some(),
            }),
            _ => Err(vec![TypeErr::new(ast.pos, "Expected variable")]),
        }
    }
}

impl TryFrom<&AST> for GenericFields {
    type Error = Vec<TypeErr>;

    fn try_from(ast: &AST) -> TypeResult<GenericFields> {
        Ok(GenericFields {
            fields: match &ast.node {
                Node::VariableDef { var, ty, mutable, expr, .. } => {
                    let identifier = Identifier::try_from(var.deref())?;
                    match &ty {
                        Some(ty) => {
                            let ty = Name::try_from(ty.deref())?;
                            Ok(match_name(&identifier, &ty, ast.pos)?
                                .iter()
                                .map(|(id, (inner_mut, ty))| GenericField {
                                    is_py_type: false,
                                    name: id.clone(),
                                    mutable: *mutable || *inner_mut,
                                    pos: ast.pos,
                                    ty: Some(ty.clone()),
                                    in_class: None,
                                    assigned_to: expr.is_some(),
                                })
                                .collect())
                        }
                        None => Ok(identifier
                            .fields(var.pos)?
                            .iter()
                            .map(|(inner_mut, name)| GenericField {
                                is_py_type: false,
                                name: name.clone(),
                                pos: ast.pos,
                                mutable: *mutable || *inner_mut,
                                in_class: None,
                                ty: None,
                                assigned_to: expr.is_some(),
                            })
                            .collect()),
                    }
                }
                _ => Err(vec![TypeErr::new(ast.pos, "Expected variable")]),
            }?,
        })
    }
}

impl GenericField {
    pub fn in_class(
        self,
        class: Option<&StringName>,
        _type_def: bool,
        pos: Position,
    ) -> TypeResult<GenericField> {
        if class.is_some() {
            Ok(GenericField { in_class: class.cloned(), ..self })
        } else {
            Err(vec![TypeErr::new(pos, &String::from("Field must be in class"))])
        }
    }

    pub fn with_ty(&self, name: &Name) -> Self {
        GenericField { ty: Some(name.clone()), ..self.clone() }
    }
}

fn field_name(ast: &AST) -> TypeResult<String> {
    match &ast.node {
        Node::Id { lit } => Ok(lit.clone()),
        _ => {
            let msg = format!("Expected valid identifier, was '{}'", ast.node);
            Err(vec![TypeErr::new(ast.pos, &msg)])
        }
    }
}