Files
aho_corasick
atty
beef
bitflags
bstr
byteorder
cfg_if
clap
clap_derive
codespan
codespan_reporting
crc_any
crypto_hash
csv
csv_core
debug_helper
filepath
fixed
fixed_macro
fixed_macro_impl
fixed_macro_types
fnv
foreign_types
foreign_types_shared
getrandom
glob
hashbrown
heck
hex
indexmap
itoa
lazy_static
libc
linked_hash_map
linked_hash_set
logos
logos_derive
lrl_test_compiler
maplit
memchr
memoffset
once_cell
openssl
openssl_sys
os_str_bytes
paste
pest
pest_derive
pest_generator
pest_meta
phf
phf_generator
phf_macros
phf_shared
ppv_lite86
proc_macro2
proc_macro_error
proc_macro_error_attr
proc_macro_hack
quote
rand
rand_chacha
rand_core
regex
regex_automata
regex_syntax
remove_dir_all
ring
rowan
rustc_hash
ryu
semver
semver_parser
serde
serde_derive
serde_json
siphasher
smallvec
smawk
smol_str
spin
stable_deref_trait
strsim
syn
taplo
tempfile
termcolor
text_size
textwrap
toml
triomphe
typenum
ucd_trie
unicode_linebreak
unicode_segmentation
unicode_width
unicode_xid
untrusted
utf8_ranges
vec_map
  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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
use ring::digest::{Context, SHA256};

use serde::Deserialize;
use std::collections::BTreeMap; //BTreeMap instead of hashmap to maintain ordering of arguments

use crate::result::{diagnostic::Location, CompilerResult};

/// Represents a drivers TOML file.
#[derive(Debug, PartialEq, Deserialize)]
pub struct DriversFile {
    /// Drivers in the file
    pub drivers: Drivers,
    /// Hash digest
    pub hash: Vec<u8>, // TODO include file name
}
/// Represents the drivers data within a drivers TOML file.
#[derive(Debug, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Drivers {
    /// Drivers Version
    pub version: String,
    /// Vector of drivers for virtual sensors
    pub sensor: Vec<VirtualSensorDriver>,

    /// Vector of drivers for virtual relays
    pub relay: Vec<VirtualRelayDriver>,
}
/// Represents the metadata for a virtual sensor.
#[derive(Debug, PartialEq, Deserialize)]
pub struct VirtualSensorDriver {
    /// The namespace of the driver.
    pub namespace: String,
    /// The function of the driver
    pub function: String,
    /// Input fields for the driver
    // TODO what order do the fields need to be in
    pub fields: Option<Vec<BTreeMap<String, String>>>,
}

/// Represents the metadata for a virtual relay.
#[derive(Debug, PartialEq, Deserialize)]
pub struct VirtualRelayDriver {
    /// The namespace of the driver.
    pub namespace: String,
    /// The function of the driver
    pub function: String,
    /// Input fields for the driver
    // TODO what order do the fields need to be in
    pub fields: Option<Vec<BTreeMap<String, String>>>,
}

impl Drivers {
    /// Parse the provided file_name as a Drivers.toml file.
    /// Outputs a DriversFile struct wrapped in a CompilerResult.
    pub fn parse(file_id: usize, file_name: String, contents: &str) -> CompilerResult<DriversFile> {
        let mut res = CompilerResult::new("Parsing a drivers file");

        let taplo_parse = taplo::parser::parse(contents);

        let taplo_dom = taplo_parse.clone().into_dom();

        //Check for TOML syntax errors
        if !taplo_parse.errors.is_empty() {
            for error in taplo_parse.errors {
                let location = Location::from_raw(
                    file_id,
                    error.range.start().into(),
                    error.range.end().into(),
                );
                res.error((location, error.to_string()));
            }
        }

        //Check for TOML semantic errors
        if !taplo_dom.errors().is_empty() {
            for error in taplo_dom.errors() {
                res.error(format!("{}\n\t{}", error.to_string(), file_name));
            }
        }

        // Compute hash of the drivers file
        let drivers: Drivers = check!(res, toml::from_str(contents));
        let mut context = Context::new(&SHA256);
        context.update(contents.as_bytes());
        // Get the hash digest and convert it to a vector
        let hash = context.finish().as_ref().to_vec();

        let drivers_file = DriversFile {
            drivers,
            hash: hash,
        };
        res.with_value(drivers_file)
    }
    /// Return the index into the drivers table for the given sensor driver name
    pub fn get_sensor_driver_index(&self, driver_name: &str) -> Option<u16> {
        for (idx, sensor_driver) in self.sensor.iter().enumerate() {
            let sensor_driver_name =
                sensor_driver.namespace.clone() + "/" + sensor_driver.function.clone().as_str();
            if driver_name.eq(sensor_driver_name.as_str()) {
                return Some(idx as u16);
            }
        }
        None
    }
    /// Return a reference to the sensor driver with the given sensor driver name
    pub fn get_sensor_driver(&self, driver_name: &str) -> Option<&VirtualSensorDriver> {
        let driver_idx = self.get_sensor_driver_index(driver_name);
        if let Some(driver_idx) = driver_idx {
            return Some(&self.sensor[driver_idx as usize]);
        }
        None
    }
    /// Return the index into the drivers table for the given relay driver name
    pub fn get_relay_driver_index(&self, driver_name: &str) -> Option<u16> {
        for (idx, relay_driver) in self.relay.iter().enumerate() {
            let relay_driver_name =
                relay_driver.namespace.clone() + "/" + relay_driver.function.clone().as_str();
            if driver_name.eq(relay_driver_name.as_str()) {
                return Some(idx as u16);
            }
        }
        None
    }
    /// Return a reference to the relay driver with the given relay driver name
    pub fn get_relay_driver(&self, driver_name: &str) -> Option<&VirtualRelayDriver> {
        let driver_idx = self.get_relay_driver_index(driver_name);
        if let Some(driver_idx) = driver_idx {
            return Some(&self.relay[driver_idx as usize]);
        }
        None
    }
}

impl VirtualRelayDriver {
    /// Return the index for the given argument name
    pub fn get_arg_index(&self, arg_name: &str) -> Option<u16> {
        if let Some(args) = &self.fields {
            for (idx, arg) in args.iter().enumerate() {
                // This line seems really messy
                if arg.get("name") == Some(&arg_name.to_string()) {
                    return Some(idx as u16);
                }
            }
        }
        None
    }
}

impl VirtualSensorDriver {
    /// Return the index for the given argument name
    pub fn get_arg_index(&self, arg_name: &str) -> Option<u16> {
        if let Some(args) = &self.fields {
            for (idx, arg) in args.iter().enumerate() {
                // This line seems really messy
                if arg.get("name") == Some(&arg_name.to_string()) {
                    return Some(idx as u16);
                }
            }
        }
        None
    }
}

#[cfg(test)]
mod tests {
    use codespan_reporting::files::SimpleFiles;

    use super::*;

    #[test]
    fn toml_test() {
        let input = r#"version = "0.1"

[[relay]]
namespace = "MissionControl"
function = "UDP_Command"
fields = [{ name = "id", type = "u16" }]

[[sensor]]
namespace = "MissionControl"
function = "UDP_Request"
fields = [{ name = "stand_id", type = "u16" }]

[[sensor]]
namespace = "TestStand"
function = "RedundantAggregate"
fields = [
    { name = "device_address_a", type = "u16" },
    { name = "device_address_b", type = "u16" },
    { name = "lower", type = "u16" },
    { name = "upper", type = "u16" },
]
"#;
        // Calculated from python hashing script
        let expected_hash = [
            31, 189, 160, 233, 117, 157, 172, 154, 176, 22, 91, 206, 212, 23, 191, 133, 92, 170,
            250, 217, 194, 189, 23, 33, 93, 196, 146, 95, 97, 5, 246, 194,
        ]
        .to_vec();

        // Compute hash of the drivers file
        let mut context = Context::new(&SHA256);
        context.update(input.as_bytes());
        // Get the hash digest and convert it to a vector
        let test_hash = context.finish().as_ref().to_vec();

        assert_eq!(expected_hash, test_hash);

        // Construct hashmap for every argument to each driver
        // and construct a vector with each argument's hashmap
        let mut sensor_id = BTreeMap::new();
        sensor_id.insert("name".into(), "stand_id".into());
        sensor_id.insert("type".into(), "u16".into());
        //Create vector of hashmaps for the first sensor driver
        let sensor_args_1: Vec<BTreeMap<String, String>> = vec![sensor_id];

        let mut sensor_device_address_a = BTreeMap::new();
        sensor_device_address_a.insert("name".into(), "device_address_a".into());
        sensor_device_address_a.insert("type".into(), "u16".into());
        let mut sensor_device_address_b = BTreeMap::new();
        sensor_device_address_b.insert("name".into(), "device_address_b".into());
        sensor_device_address_b.insert("type".into(), "u16".into());
        let mut sensor_lower = BTreeMap::new();
        sensor_lower.insert("name".into(), "lower".into());
        sensor_lower.insert("type".into(), "u16".into());
        let mut sensor_higher = BTreeMap::new();
        sensor_higher.insert("name".into(), "upper".into());
        sensor_higher.insert("type".into(), "u16".into());
        //Create vector of hashmaps for the second sensor driver
        let sensor_args_2: Vec<BTreeMap<String, String>> = vec![
            sensor_device_address_a,
            sensor_device_address_b,
            sensor_lower,
            sensor_higher,
        ];

        let mut relay_id = BTreeMap::new();
        relay_id.insert("name".into(), "id".into());
        relay_id.insert("type".into(), "u16".into());
        //Create vector of hashmaps for the first relay driver
        let relay_args_1: Vec<BTreeMap<String, String>> = vec![relay_id];

        let sensor_drivers: Vec<VirtualSensorDriver> = vec![
            VirtualSensorDriver {
                namespace: "MissionControl".into(),
                function: "UDP_Request".into(),
                fields: Some(sensor_args_1),
            },
            VirtualSensorDriver {
                namespace: "TestStand".into(),
                function: "RedundantAggregate".into(),
                fields: Some(sensor_args_2),
            },
        ];
        let relay_drivers: Vec<VirtualRelayDriver> = vec![VirtualRelayDriver {
            namespace: "MissionControl".into(),
            function: "UDP_Command".into(),
            fields: Some(relay_args_1),
        }];
        let files = SimpleFiles::new();
        Drivers::parse(0, "empty".to_string(), input)
            .print(&files)
            .expect("Failed to parse drivers file");
        let actual: DriversFile = Drivers::parse(0, "empty".to_string(), input)
            .to_option()
            .unwrap();

        assert_eq!(sensor_drivers, actual.drivers.sensor);
        assert_eq!(relay_drivers, actual.drivers.relay);
        assert_eq!(expected_hash, actual.hash);
    }
}