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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
#![deny(missing_docs)]

//! Compilation of XIO jobsets for deployment on a device.

#[macro_use]
extern crate failure;

extern crate bidir_map;
extern crate xio_base_datatypes;
extern crate xio_hwdb;
extern crate xio_instructionset;
extern crate xio_jobset;

mod error;

use base::{HasDataType, HasStorageType, IsInStorageType};
use bidir_map::BidirMap;
use error::CodeLocation;
pub use error::{Error, ErrorKind};
use failure::Fail;
use std::collections::{BTreeMap, BTreeSet};
use std::ops::Shl;
use xio_base_datatypes as base;
use xio_hwdb as hwdb;
use xio_instructionset as instructionset;
use xio_jobset as jobset;

type Result<T> = std::result::Result<T, error::Error>;

/// A compiled jobset which can be deployed to a XIO device.
#[derive(Debug)]
pub struct CompiledJobSet {
    /// The parameters of the jobset.
    pub parameters: CompiledParameterSet,
    /// The job index mapping (which job gets placed at which index).
    pub job_mapping: BidirMap<String, u16>,
    /// The jobs compiled to XIO job commands.
    pub jobs: BTreeMap<String, Vec<u16>>,
}

impl CompiledJobSet {
    /// Build a vector of XIO job commands.
    pub fn build_jobs(&self) -> Result<Vec<Vec<u16>>> {
        Ok((0..self.jobs.len())
            .map(|i| {
                let name = self
                    .job_mapping
                    .get_by_second(&(i as u16))
                    .ok_or_else(|| ErrorKind::ProgrammerError {
                        msg: format!(
                            "Expected job at index {} not found",
                            i
                        ),
                    })?
                    .to_string();
                self.jobs
                    .get(&name)
                    .ok_or_else(|| {
                        ErrorKind::ProgrammerError {
                            msg: format!(
                                "Expected job at index {:?} not found",
                                name
                            ),
                        }.into()
                    })
                    .map(|v| v.clone())
            })
            .collect::<Result<Vec<_>>>()?)
    }
}

/// A compiled parameter set to be used in a XIO jobset.
#[derive(Debug)]
pub struct CompiledParameterSet {
    /// The parameter index mapping (index where parameters are stored).
    pub parameter_mapping: BidirMap<String, u16>,
    /// The statically assigned parameter values.
    pub parameters: BTreeMap<String, base::ParameterValueRaw>,
    /// The parameter values that get set before jobs are run.
    pub runtime_parameters: BTreeMap<String, base::DataValueRaw>,
    /// The XIO capabilities which are assigned to this job.
    pub assigned_capabilities: BTreeSet<String>,
}

impl CompiledParameterSet {
    /// Build a vector of all static parameter values.
    pub fn build_request_parameters(
        &self,
    ) -> Result<Vec<base::ParameterValueRaw>> {
        Ok((0..self.parameter_mapping.len())
            .map(|i| {
                let name = self
                    .parameter_mapping
                    .get_by_second(&(i as u16))
                    .ok_or_else(|| ErrorKind::ProgrammerError {
                        msg: format!(
                            "Expected parameter at index {} not found",
                            i
                        ),
                    })?
                    .to_string();
                self.parameters
                    .get(&name)
                    .ok_or_else(|| {
                        ErrorKind::MappedParameterNotFound {
                            name: name.to_string(),
                        }.into()
                    })
                    .map(|v| v.clone())
            })
            .collect::<Result<Vec<_>>>()?)
    }

    /// Build map of all parameters that get set before jobs are run.
    pub fn build_runtime_parameters(
        &self,
    ) -> Result<BTreeMap<u16, base::DataValueRaw>> {
        Ok(self
            .runtime_parameters
            .iter()
            .map(|(k, v)| {
                let index = self
                    .parameter_mapping
                    .get_by_first(&k.to_string())
                    .ok_or_else(|| ErrorKind::ProgrammerError {
                        msg: format!(
                            "Runtime parameter at index {} not found",
                            k
                        ),
                    })?;
                Ok((*index, v.clone()))
            })
            .collect::<Result<BTreeMap<u16, base::DataValueRaw>>>()?)
    }
}

/// A XIO hardware target for which a jobset gets compiled.
#[derive(Debug)]
pub struct HardwareTarget {
    /// The id of the device.
    pub id: String,
    /// The description of the device.
    pub description: hwdb::HardwareBoardDescription,
    /// The modules description of the device.
    pub modules: BTreeMap<String, hwdb::Module>,
    /// The instruction set which is used for compilation.
    pub instructions: instructionset::InstructionMap,
}

impl HardwareTarget {
    /// If successful, returns the referenced value, and a string containing
    /// the id of the capability that contains the channel.
    fn channel_reference(
        &self,
        name: &str,
        assignment: &jobset::ChannelAssignment,
        hardware_board: &str,
        required_datatype: &base::DataType,
    ) -> Result<(base::ParameterValueRaw, String)> {
        let assigned_capability = assignment.capability.to_string();
        let capability = self
            .description
            .capabilities
            .get(&assigned_capability)
            .ok_or_else(|| ErrorKind::CapabilityNotFound {
                name: assignment.capability.to_string(),
                parameter_name: name.to_string(),
                hardware_board: hardware_board.to_string(),
            })?;
        let module = self.modules.get(&capability.module).ok_or_else(
            || ErrorKind::ModuleDescriptionNotFound {
                name: capability.module.to_string(),
                parameter_name: name.to_string(),
                capability_name: assignment.capability.to_string(),
                hardware_board: hardware_board.to_string(),
            },
        )?;
        let channel_index = module
            .channels
            .iter()
            .position(|c| c.id == assignment.channel)
            .ok_or_else(|| ErrorKind::ModuleChannelNotFound {
                name: assignment.channel.to_string(),
                module_name: capability.module.to_string(),
                parameter_name: name.to_string(),
            })?;
        let channel = &module.channels[channel_index];
        if channel.channel_type != *required_datatype {
            return Err(ErrorKind::ChannelDataTypeMismatch {
                index: channel_index as u16,
                name: assignment.channel.to_string(),
                module_name: capability.module.to_string(),
                required_datatype: required_datatype.clone(),
                found_datatype: channel.channel_type.clone(),
                parameter_name: name.to_string(),
            }.into());
        }

        let reference = base::ModuleChannelReference {
            module_id: capability.id,
            channel_id: channel_index as u16,
        };

        use base::DataType::*;
        use base::ParameterValue::{
            BooleanChannel, Int16Channel, Int32Channel, Int64Channel,
            Int8Channel, ParameterMaskChannel, UInt16Channel,
            UInt32Channel, UInt64Channel, UInt8Channel,
        };
        match channel.channel_type {
            Boolean => {
                Ok((BooleanChannel(reference), assigned_capability))
            }
            Int8 => Ok((Int8Channel(reference), assigned_capability)),
            Int16 => Ok((Int16Channel(reference), assigned_capability)),
            Int32 => Ok((Int32Channel(reference), assigned_capability)),
            Int64 => Ok((Int64Channel(reference), assigned_capability)),
            UInt8 => Ok((UInt8Channel(reference), assigned_capability)),
            UInt16 => Ok((UInt16Channel(reference), assigned_capability)),
            UInt32 => Ok((UInt32Channel(reference), assigned_capability)),
            UInt64 => Ok((UInt64Channel(reference), assigned_capability)),
            ParameterMask => {
                Ok((ParameterMaskChannel(reference), assigned_capability))
            }
            Invalid => Err(ErrorKind::InvalidDataType {
                name: name.to_string(),
            }.into()),
        }
    }
}

/// A trait for XIO jobset compilation.
pub trait XioJobSetCompile {
    /// Compile a jobset.
    fn compile(&self, target: &HardwareTarget) -> Result<CompiledJobSet>;
}

impl XioJobSetCompile for jobset::JobSet {
    fn compile(&self, target: &HardwareTarget) -> Result<CompiledJobSet> {
        let compiled_parameters =
            compile_parameters(&self.parameters, target, &self.channels)?;
        compile_jobs(&self.jobs, compiled_parameters, &target.instructions)
    }
}

struct ParameterEntry {
    description_layer: String,
    description: jobset::ParameterDescription,
    value: Option<base::DataValueDescriptive>,
}

#[derive(Default)]
struct ParameterBuilder {
    entries: BTreeMap<String, ParameterEntry>,
}

impl ParameterBuilder {
    fn overlay(
        mut self,
        layer: &jobset::ParameterSet,
    ) -> Result<ParameterBuilder> {
        for (ref k, ref v) in &layer.descriptions {
            // check that the layer only contains new parameter descriptions
            if let Some(d) = self.entries.get(&k.to_string()) {
                return Err(ErrorKind::ParameterAlreadyDescribed {
                    name: k.to_string(),
                    original_layer: d.description_layer.to_string(),
                    offending_layer: layer.name.to_string(),
                }.into());
            }
            let description = (*v).clone();
            // check that parameter value overrides are respected
            {
                use base::OverrideOption::*;
                use base::StorageType::*;
                use ErrorKind::*;
                match (
                    layer.values.contains_key(&k.to_string()),
                    &description.override_option,
                    &description.storage,
                ) {
                    (true, &Enforce, _) => {
                        // override-enforced parameters *must not* be defined
                        // on the same overlay
                        return Err(ParameterOverrideEnforceNotRespected {
                            name: k.to_string(),
                            layer: layer.name.to_string(),
                        }.into());
                    }
                    (false, &Forbid, &Fixed) => {
                        // override-forbid parameters *must* be defined
                        // on the same overlay
                        return Err(ParameterOverrideForbidNotSatisfied {
                            name: k.to_string(),
                            layer: layer.name.to_string(),
                        }.into());
                    }
                    _ => {}
                }
            }
            let entry = ParameterEntry {
                description_layer: layer.name.to_string(),
                description,
                value: None,
            };
            self.entries.insert(k.to_string(), entry);
        }
        for (ref k, ref v) in &layer.values {
            if let Some(d) = self.entries.get_mut(&k.to_string()) {
                // check for the variables that were defined in a lower
                // level overlay
                if d.description.override_option
                    == base::OverrideOption::Forbid
                    && d.description_layer != layer.name
                {
                    return Err(ErrorKind::ParameterOverrideNotAllowed {
                        name: k.to_string(),
                        layer: layer.name.to_string(),
                    }.into());
                }
                // check parameter types
                use base::TryConvertTo;
                let t = &d.description.data_type;

                let value = v.try_convert_to(t).map_err(|e| {
                    e.context(ErrorKind::ParameterTypeMismatch {
                        name: k.to_string(),
                        defined_type: (*t).clone(),
                        defined_layer: d.description_layer.clone(),
                        value: (**v).clone(),
                        value_layer: layer.name.to_string(),
                    })
                })?;
                d.value = Some(value);
            } else {
                return Err(ErrorKind::ParameterNotYetDescribed {
                    name: k.to_string(),
                    layer: layer.name.to_string(),
                }.into());
            }
        }
        Ok(self)
    }

    fn finalize(
        self,
        target: &HardwareTarget,
        mapping: &BTreeMap<String, jobset::ChannelAssignment>,
    ) -> Result<CompiledParameterSet> {
        // Move the referenced parameters to the front, so the
        // probability to cover them in a mask is much higher
        let referenced_parameters = self
            .entries
            .iter()
            .filter_map(|(_, v)| v.value.clone())
            .filter_map(|v| {
                if let base::DataValue::ParameterMask(ref list) = v {
                    Some(list.clone())
                } else {
                    None
                }
            })
            .flat_map(|list| list.into_iter())
            .collect::<BTreeSet<String>>();
        let mut non_referenced_parameters = self
            .entries
            .keys()
            .map(|v| v.to_string())
            .collect::<BTreeSet<String>>();

        for p in &referenced_parameters {
            if non_referenced_parameters.take(p).is_none() {
                return Err(ErrorKind::MappedParameterNotFound {
                    name: p.to_string(),
                }.into());
            }
        }

        let parameter_mapping = referenced_parameters
            .into_iter()
            .chain(non_referenced_parameters.into_iter())
            .enumerate()
            .map(|(i, v)| (v.to_string(), i as u16))
            .collect::<BidirMap<String, u16>>();
        let mut parameters = BTreeMap::new();
        let mut runtime_parameters = BTreeMap::new();
        let mut assigned_capabilities = BTreeSet::new();

        for (ref k, ref v) in &self.entries {
            let (value, runtime_value) = match v.description.storage {
                base::StorageType::Fixed => {
                    if let Some(ref v) = v.value {
                        (
                            base::ParameterValueRaw::from(
                                v.to_raw(&parameter_mapping)?,
                            ),
                            None,
                        )
                    } else {
                        return Err(
                            ErrorKind::ParameterWithFixedStorageAndNoValue {
                                name: k.to_string(),
                            }.into(),
                        );
                    }
                }
                base::StorageType::Channel => {
                    let assignment = mapping
                        .get(&k.to_string())
                        .ok_or_else(|| {
                            ErrorKind::ParameterNotMappedInHardwareAssignment {
                            name: k.to_string(),
                            hardware_board: target.id.to_string(),
                        }
                        })?;
                    let (reference, assigned_capability) = target
                        .channel_reference(
                            k,
                            assignment,
                            &target.id,
                            &v.description.data_type,
                        )?;
                    assigned_capabilities.insert(assigned_capability);
                    (
                        reference,
                        match v.value {
                            Some(ref v) => {
                                Some(v.to_raw(&parameter_mapping)?)
                            }
                            None => None,
                        },
                    )
                }
            };
            parameters.insert(k.to_string(), value);
            if let Some(r) = runtime_value {
                // TODO: check that the parameter type matches
                runtime_parameters.insert(
                    k.to_string(),
                    r, // TODO: convert with &parameter_mapping if necessary
                );
            }
        }

        Ok(CompiledParameterSet {
            parameter_mapping,
            parameters,
            runtime_parameters,
            assigned_capabilities,
        })
    }
}

fn compile_parameters(
    parameters: &[jobset::ParameterSet],
    target: &HardwareTarget,
    mapping: &BTreeMap<String, jobset::ChannelAssignment>,
) -> Result<CompiledParameterSet> {
    let mut builder = ParameterBuilder::default();
    for layer in parameters {
        builder = builder.overlay(&layer)?;
    }
    builder.finalize(target, mapping)
}

fn compile_jobs(
    jobs: &BTreeMap<String, xio_jobset::Job>,
    parameters: CompiledParameterSet,
    instructions: &instructionset::InstructionMap,
) -> Result<CompiledJobSet> {
    let jobs = jobs
        .iter()
        .map(|(k, v)| {
            Ok((
                k.to_string(),
                compile_job(v, &parameters, instructions, k)?,
            ))
        })
        .collect::<Result<BTreeMap<String, Vec<u16>>>>()?;
    let job_mapping = jobs
        .keys()
        .enumerate()
        .map(|(i, n)| (n.to_string(), i as u16))
        .collect::<BidirMap<String, u16>>();
    Ok(CompiledJobSet {
        jobs,
        job_mapping,
        parameters,
    })
}

fn compile_job(
    job: &xio_jobset::Job,
    parameters: &CompiledParameterSet,
    instructions: &instructionset::InstructionMap,
    job_name: &str,
) -> Result<Vec<u16>> {
    let mut commands = Vec::new();
    for (command_index, command) in job.commands.iter().enumerate() {
        let command_index = command_index as u16;
        let location = CodeLocation::Command {
            job: job_name.to_string(),
            command_index,
            command_caption: command.caption.to_string(),
        };
        commands.extend(compile_command_with_conditions(
            command,
            parameters,
            instructions,
            &location,
        )?);
    }
    Ok(commands)
}

fn compile_command_with_conditions(
    command: &xio_jobset::Command,
    parameters: &CompiledParameterSet,
    instructions: &instructionset::InstructionMap,
    location: &CodeLocation,
) -> Result<Vec<u16>> {
    let instruction = instructions.get(&command.command_type).ok_or_else(
        || ErrorKind::InstructionNotFound {
            name: command.command_type.to_string(),
            location: location.clone(),
        },
    )?;

    use instructionset::InstructionCategory::*;
    match instruction.category() {
        CommandWithoutTimeExtent if command.conditions.is_empty() => {
            compile_command(command, parameters, instruction, location)
        }
        CommandWithoutTimeExtent => {
            Err(ErrorKind::CommandWithoutTimeExtentButConditions {
                location: location.clone(),
                command_type: command.command_type.to_string(),
            }.into())
        }
        CommandWithTimeExtent if !command.conditions.is_empty() => {
            let mut commands = compile_command(
                command,
                parameters,
                instruction,
                location,
            )?;
            commands.extend(compile_conditions(
                &command.conditions,
                parameters,
                instructions,
                location,
            )?);
            Ok(commands)
        }
        CommandWithTimeExtent => {
            Err(ErrorKind::CommandWithTimeExtentButNoConditions {
                location: location.clone(),
                command_type: command.command_type.to_string(),
            }.into())
        }
        Condition => Err(ErrorKind::FoundConditionInCommands {
            location: location.clone(),
            command_type: command.command_type.to_string(),
        }.into()),
        Invalid => Err(ErrorKind::InvalidInstructionCategory {
            location: location.clone(),
            command_type: command.command_type.to_string(),
        }.into()),
    }
}

trait HasParameters {
    fn get_parameters(&self) -> &BTreeMap<String, String>;
}

trait HasFlags {
    fn get_flags(&self) -> u8 {
        0u8
    }
}

impl HasParameters for jobset::Command {
    fn get_parameters(&self) -> &BTreeMap<String, String> {
        &self.parameters
    }
}

impl HasParameters for jobset::Condition {
    fn get_parameters(&self) -> &BTreeMap<String, String> {
        &self.parameters
    }
}

impl HasFlags for jobset::Command {}

impl HasFlags for jobset::Condition {
    fn get_flags(&self) -> u8 {
        if self.exit_job {
            0b0001u8
        } else {
            0b0000u8
        }
    }
}

fn compile_command<T: HasParameters + HasFlags>(
    command: &T,
    parameters: &CompiledParameterSet,
    instruction: &instructionset::Instruction,
    location: &CodeLocation,
) -> Result<Vec<u16>> {
    // extract required parameter information
    let mut param_groups = BTreeMap::new();
    let mut param_names = BTreeSet::new();

    for param in &instruction.parameters {
        let group = param_groups
            .entry(param.group.to_string())
            .or_insert_with(BTreeSet::new);
        group.insert(param.id.to_string());
        param_names.insert(param.id.to_string());
    }
    // empty group means the params are actually not in a group
    param_groups.remove(&"".to_string());

    // verify that the parameter names are the same as the required
    // parameters
    let effective_param_names = command
        .get_parameters()
        .keys()
        .map(|k| k.to_string())
        .collect::<BTreeSet<String>>();
    if effective_param_names != param_names {
        return Err(ErrorKind::WrongParameters {
            found: effective_param_names,
            required: param_names,
            location: location.clone(),
        }.into());
    }

    // verify that each group contains parameters of the same type only
    for (group, params) in param_groups {
        let params = params
            .iter()
            .map(|k| {
                Ok(command
                    .get_parameters()
                    .get(&k.to_string())
                    .ok_or_else(|| ErrorKind::ParameterNotFound {
                        name: k.to_string(),
                    })?)
            })
            .collect::<Result<Vec<_>>>()?
            .into_iter()
            .map(|k| {
                Ok((
                    k.to_string(),
                    parameters.parameters.get(k).ok_or_else(|| {
                        ErrorKind::ParameterNotFound {
                            name: k.to_string(),
                        }
                    })?,
                ))
            })
            .collect::<Result<BTreeMap<String, &base::ParameterValueRaw>>>(
            )?
            .into_iter()
            .map(|(k, v)| (k, v.data_type()))
            .collect::<BTreeMap<String, base::DataType>>();
        if params
            .values()
            .cloned()
            .collect::<BTreeSet<base::DataType>>()
            .len() > 1
        {
            return Err(ErrorKind::ParametersInGroupAreOfDifferentTypes {
                parameters: params
                    .keys()
                    .map(|s| s.to_string())
                    .collect::<BTreeSet<String>>(),
                location: location.clone(),
                group,
            }.into());
        }
    }

    let code = u16::from(command.get_flags()).shl(12) | instruction.code;
    let mut chunks = vec![code];

    for param in &instruction.parameters {
        let id = &param.id;
        let param_index = command.get_parameters()[id].to_string();
        let value = parameters.parameters[&param_index].clone();
        if !value.is_in_storage(&param.storage) {
            return Err(ErrorKind::ParameterStorageDoesNotFit {
                name: param_index.to_string(),
                location: location.clone(),
                required_storage: param.storage.clone(),
                found_storage: value.storage_type(),
            }.into());
        }
        let param_index = parameters
            .parameter_mapping
            .get_by_first(&param_index)
            .ok_or_else(|| ErrorKind::ParameterNotFound {
                name: id.to_string(),
            })?;
        chunks.push(*param_index);
    }

    Ok(chunks)
}

fn compile_conditions(
    conditions: &[xio_jobset::Condition],
    parameters: &CompiledParameterSet,
    instructions: &instructionset::InstructionMap,
    location: &CodeLocation,
) -> Result<Vec<u16>> {
    let mut commands = Vec::new();
    for (condition_index, condition) in conditions.iter().enumerate() {
        let condition_index = condition_index as u16;
        let location = location.clone().with_condition(
            condition_index,
            condition.caption.to_string(),
        );
        let instruction = instructions
            .get(&condition.command_type)
            .ok_or_else(|| ErrorKind::InstructionNotFound {
                name: condition.command_type.to_string(),
                location: location.clone(),
            })?;
        let command = compile_command(
            condition,
            parameters,
            instruction,
            &location,
        )?;
        commands.extend(command);
    }
    Ok(commands)
}