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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
use std::{fmt, str::FromStr};

use nom_locate::LocatedSpan;

use crate::{
    parser::{common::parse_memory_reference, lex, ParseError},
    program::{disallow_leftover, SyntaxError},
};

use super::ArithmeticOperand;

#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub enum ScalarType {
    Bit,
    Integer,
    Octet,
    Real,
}

impl fmt::Display for ScalarType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use ScalarType::*;
        write!(
            f,
            "{}",
            match self {
                Bit => "BIT",
                Integer => "INTEGER",
                Octet => "OCTET",
                Real => "REAL",
            }
        )
    }
}

#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct Vector {
    pub data_type: ScalarType,
    pub length: u64,
}

impl Vector {
    pub fn new(data_type: ScalarType, length: u64) -> Self {
        Self { data_type, length }
    }
}

impl fmt::Display for Vector {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}[{}]", self.data_type, self.length)
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Sharing {
    pub name: String,
    pub offsets: Vec<Offset>,
}

impl Sharing {
    pub fn new(name: String, offsets: Vec<Offset>) -> Self {
        Self { name, offsets }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Offset {
    pub offset: u64,
    pub data_type: ScalarType,
}

impl Offset {
    pub fn new(offset: u64, data_type: ScalarType) -> Self {
        Self { offset, data_type }
    }
}

impl fmt::Display for Offset {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} {}", self.offset, self.data_type)
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Declaration {
    pub name: String,
    pub size: Vector,
    pub sharing: Option<Sharing>,
}

impl Declaration {
    pub fn new(name: String, size: Vector, sharing: Option<Sharing>) -> Self {
        Self {
            name,
            size,
            sharing,
        }
    }
}

impl fmt::Display for Declaration {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "DECLARE {} {}", self.name, self.size)?;
        if let Some(shared) = &self.sharing {
            write!(f, " SHARING {}", shared.name)?;
            if !shared.offsets.is_empty() {
                write!(f, " OFFSET")?;
                for offset in shared.offsets.iter() {
                    write!(f, " {offset}")?
                }
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod test_declaration {
    use super::{Declaration, Offset, ScalarType, Sharing, Vector};
    use insta::assert_snapshot;
    use rstest::rstest;

    #[rstest]
    #[case(
        "Basic Declaration",
        Declaration{
            name: "ro".to_string(),
            size: Vector{data_type: ScalarType::Bit, length: 1},
            sharing: None,

        }
    )]
    #[case(
        "Shared Declaration",
        Declaration{
            name: "ro".to_string(),
            size: Vector{data_type: ScalarType::Integer, length: 2},
            sharing: Some(Sharing{name: "foo".to_string(), offsets: vec![]})
        }
    )]
    #[case(
        "Shared Declaration with Offsets",
        Declaration{
            name: "ro".to_string(),
            size: Vector{data_type: ScalarType::Real, length: 3},
            sharing: Some(Sharing{
                name: "bar".to_string(),
                offsets: vec![
                    Offset{offset: 4, data_type: ScalarType::Bit},
                    Offset{offset: 5, data_type: ScalarType::Bit}
                ]})
        }
    )]
    fn test_display(#[case] description: &str, #[case] declaration: Declaration) {
        insta::with_settings!({
            snapshot_suffix => description,
        }, {
            assert_snapshot!(declaration.to_string())
        })
    }
}

#[derive(Clone, Debug, Hash, PartialEq)]
pub struct MemoryReference {
    pub name: String,
    pub index: u64,
}

impl MemoryReference {
    pub fn new(name: String, index: u64) -> Self {
        Self { name, index }
    }
}

impl Eq for MemoryReference {}

impl fmt::Display for MemoryReference {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}[{}]", self.name, self.index)
    }
}

impl FromStr for MemoryReference {
    type Err = SyntaxError<Self>;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let input = LocatedSpan::new(s);
        let tokens = lex(input)?;
        disallow_leftover(
            parse_memory_reference(&tokens).map_err(ParseError::from_nom_internal_err),
        )
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Load {
    pub destination: MemoryReference,
    pub source: String,
    pub offset: MemoryReference,
}

impl Load {
    pub fn new(destination: MemoryReference, source: String, offset: MemoryReference) -> Self {
        Self {
            destination,
            source,
            offset,
        }
    }
}

impl fmt::Display for Load {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "LOAD {} {} {}",
            self.destination, self.source, self.offset
        )
    }
}

#[derive(Clone, Debug, PartialEq, Hash)]
pub struct Store {
    pub destination: String,
    pub offset: MemoryReference,
    pub source: ArithmeticOperand,
}

impl Store {
    pub fn new(destination: String, offset: MemoryReference, source: ArithmeticOperand) -> Self {
        Self {
            destination,
            offset,
            source,
        }
    }
}

impl fmt::Display for Store {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "STORE {} {} {}",
            self.destination, self.offset, self.source
        )
    }
}