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
use std::collections::HashMap;
use std::convert::TryFrom;
use std::fmt::{Display, Formatter};
use std::fmt;
use crate::check::context::field::generic::GenericField;
use crate::check::context::LookupField;
use crate::check::name::{Empty, Name, Substitute};
use crate::check::name::string_name::StringName;
use crate::check::result::TypeErr;
use crate::common::position::Position;
use crate::Context;
pub mod generic;
pub mod python;
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Field {
pub is_py_type: bool,
pub name: String,
pub mutable: bool,
pub in_class: Option<StringName>,
pub ty: Name,
pub assigned_to: bool,
}
impl Display for Field {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let ty = if self.ty.is_empty() { String::new() } else { format!(": {}", self.ty) };
write!(f, "{}{ty}", &self.name)
}
}
impl LookupField<&str, Field> for Context {
fn field(&self, field: &str, pos: Position) -> Result<Field, Vec<TypeErr>> {
if let Some(generic_field) = self.fields.iter().find(|c| c.name == field) {
let generics = HashMap::new();
Field::try_from((generic_field, &generics, pos))
} else {
let msg = format!("Field {field} is undefined.");
Err(vec![TypeErr::new(pos, &msg)])
}
}
}
impl TryFrom<(&GenericField, &HashMap<Name, Name>, Position)> for Field {
type Error = Vec<TypeErr>;
fn try_from(
(field, generics, pos): (&GenericField, &HashMap<Name, Name>, Position)
) -> Result<Self, Self::Error> {
Ok(Field {
is_py_type: field.is_py_type,
name: field.name.clone(),
mutable: field.mutable,
in_class: match &field.in_class {
Some(in_class) => Some(in_class.substitute(generics, pos)?),
None => None
},
ty: match &field.ty {
Some(ty) => ty.substitute(generics, pos)?,
None => Name::empty()
},
assigned_to: field.assigned_to,
})
}
}