1use super::*;
2use crate::parser::{Position, RlError};
3use std::collections::HashMap;
4use std::time::Duration;
5
6#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, Default)]
7pub struct DataId(pub usize);
8impl Id for DataId {
9 fn index(&self) -> usize {
10 self.0
11 }
12}
13
14#[derive(Debug, Clone)]
15pub struct Data {
16 id: DataId,
17 name: String,
18 rl_type: Reference<TypeId>,
19 period: Option<Duration>,
20 position: Option<Position>,
21}
22
23impl Data {
24 pub fn new<S: Into<String>>(
25 name: S,
26 rl_type: Reference<TypeId>,
27 period: Option<Duration>,
28 position: Option<Position>,
29 ) -> Self {
30 let id = DataId::default();
31 let name = name.into();
32 Self {
33 id,
34 name,
35 rl_type,
36 period,
37 position,
38 }
39 }
40
41 pub fn rl_type(&self) -> &Reference<TypeId> {
42 &self.rl_type
43 }
44
45 pub fn set_type(&mut self, id: TypeId) {
46 self.rl_type = Reference::Resolved(id);
47 }
48
49 pub fn period(&self) -> Option<Duration> {
50 self.period
51 }
52
53 pub fn resolve_type(&mut self, map: &HashMap<String, TypeId>) -> Result<(), RlError> {
56 match self.rl_type() {
57 Reference::Unresolved(name, pos) => match map.get(name) {
58 Some(id) => {
59 self.set_type(*id);
60 Ok(())
61 }
62 None => Err(RlError::Resolve {
63 element: format!("type '{}'", name),
64 position: pos.clone(),
65 }),
66 },
67 Reference::Resolved(_) => Ok(()),
68 }
69 }
70}
71
72impl Named<DataId> for Data {
73 fn id(&self) -> DataId {
74 self.id
75 }
76
77 fn set_id(&mut self, id: DataId) {
78 self.id = id;
79 }
80
81 fn name(&self) -> &str {
82 &self.name
83 }
84
85 fn position(&self) -> Option<Position> {
86 self.position.clone()
87 }
88}
89
90impl ToLang for Data {
91 fn to_lang(&self, skillset: &Skillset) -> String {
92 match self.period {
93 Some(period) => format!(
94 "{}: {} period {} ms\n",
95 self.name,
96 self.rl_type.to_lang(skillset),
97 period.as_millis()
98 ),
99 None => format!("{}: {}\n", self.name, self.rl_type.to_lang(skillset)),
100 }
101 }
102}
103
104impl std::fmt::Display for Data {
105 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106 write!(f, "{}", self.name)
107 }
108}