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
use std::marker::PhantomData;
use std::path::PathBuf;
use std::time::SystemTime;

use rtlola_frontend::mir::RtLolaMir;

use crate::api::monitor::{Event, EventInput, Input, Record, RecordInput, VerdictRepresentation};
use crate::config::{Config, ExecutionMode, MonitorConfig};
use crate::configuration::time::{OutputTimeRepresentation, RelativeFloat, TimeRepresentation};
use crate::monitor::{NoTracer, Tracer, TracingVerdict};
use crate::time::RealTime;
#[cfg(feature = "queued-api")]
use crate::QueuedMonitor;
use crate::{CondDeserialize, CondSerialize, Monitor};

/* Type state of shared config */
/// Represents a state of the [ConfigBuilder]
/// Used to ensure that only valid configurations can be created
pub trait ConfigState {}

/// The config state in which the specification has yet to be configured
#[derive(Debug, Clone, Default, Copy)]
pub struct ConfigureIR {}
impl ConfigState for ConfigureIR {}

/// The config state in which the specification is configured
#[derive(Debug, Clone)]
pub struct IrConfigured {
    ir: RtLolaMir,
}
impl ConfigState for IrConfigured {}

/// The config state in which the specification is configured
#[derive(Debug, Clone)]
pub struct ModeConfigured<InputTime: TimeRepresentation> {
    ir: RtLolaMir,
    input_time_representation: InputTime,
    mode: ExecutionMode,
}
impl<InputTime: TimeRepresentation> ConfigState for ModeConfigured<InputTime> {}

/// An API configuration state in which the input source is configured but the input time is not.
#[derive(Debug, Clone)]
pub struct InputConfigured<InputTime: TimeRepresentation, Source: Input> {
    ir: RtLolaMir,
    input_time_representation: InputTime,
    mode: ExecutionMode,
    source: PhantomData<Source>,
}
impl<Source: Input, InputTime: TimeRepresentation> ConfigState for InputConfigured<InputTime, Source> {}

/// An API configuration state in which the input source is configured but the input time is not.
#[derive(Debug, Clone)]
pub struct VerdictConfigured<InputTime: TimeRepresentation, Source: Input, Verdict: VerdictRepresentation> {
    ir: RtLolaMir,
    input_time_representation: InputTime,
    mode: ExecutionMode,
    source: PhantomData<Source>,
    verdict: PhantomData<Verdict>,
}
impl<Source: Input, Verdict: VerdictRepresentation, InputTime: TimeRepresentation> ConfigState
    for VerdictConfigured<InputTime, Source, Verdict>
{
}

/// The main entry point of the application.
/// Use the various methods to construct a configuration either for running the interpreter directly or to use the [Monitor] API interface.
///
/// An example construction of the API:
/// ````
/// use rtlola_interpreter::monitor::{EventInput, Incremental};
/// use rtlola_interpreter::time::RelativeFloat;
/// use rtlola_interpreter::{ConfigBuilder, Monitor, Value};
///
/// let monitor: Monitor<_, _, Incremental, _> = ConfigBuilder::new()
///     .spec_str("input i: Int64")
///     .offline::<RelativeFloat>()
///     .event_input::<Vec<Value>>()
///     .with_verdict::<Incremental>()
///     .monitor().expect("Failed to create monitor.");
/// ````
#[derive(Debug, Clone)]
pub struct ConfigBuilder<S: ConfigState, OutputTime: OutputTimeRepresentation> {
    /// Which format to use to output time
    output_time_representation: PhantomData<OutputTime>,
    /// The start time to assume
    start_time: Option<SystemTime>,
    /// The current state of the config
    state: S,
}

impl ConfigBuilder<ConfigureIR, RelativeFloat> {
    /// Creates a new configuration to be used with the API.
    pub fn new() -> Self {
        ConfigBuilder {
            output_time_representation: PhantomData::default(),
            start_time: None,
            state: ConfigureIR {},
        }
    }
}

impl Default for ConfigBuilder<ConfigureIR, RelativeFloat> {
    fn default() -> Self {
        Self::new()
    }
}

impl<S: ConfigState, OutputTime: OutputTimeRepresentation> ConfigBuilder<S, OutputTime> {
    /// Sets the format in which time is returned.
    /// See the README for more details on time formats.
    /// For possible formats see the [OutputTimeRepresentation](crate::time::OutputTimeRepresentation) trait.
    pub fn output_time<T: OutputTimeRepresentation>(self) -> ConfigBuilder<S, T> {
        let ConfigBuilder {
            output_time_representation: _,
            start_time,
            state,
        } = self;
        ConfigBuilder {
            output_time_representation: PhantomData::default(),
            start_time,
            state,
        }
    }

    /// Sets the start time of the execution.
    pub fn start_time(mut self, time: SystemTime) -> Self {
        self.start_time = Some(time);
        self
    }
}

impl<OutputTime: OutputTimeRepresentation> ConfigBuilder<ConfigureIR, OutputTime> {
    /// Use an existing ir with the configuration
    pub fn with_ir(self, ir: RtLolaMir) -> ConfigBuilder<IrConfigured, OutputTime> {
        let ConfigBuilder {
            output_time_representation,
            start_time,
            state: _,
        } = self;
        ConfigBuilder {
            output_time_representation,
            start_time,
            state: IrConfigured { ir },
        }
    }

    /// Read the specification from a file at the given path.
    pub fn spec_file(self, path: PathBuf) -> ConfigBuilder<IrConfigured, OutputTime> {
        let ConfigBuilder {
            output_time_representation,
            start_time,
            state: _,
        } = self;
        let config = rtlola_frontend::ParserConfig::from_path(path).unwrap_or_else(|e| {
            eprintln!("{}", e);
            std::process::exit(1)
        });
        let handler = rtlola_frontend::Handler::from(config.clone());
        let ir = rtlola_frontend::parse(config).unwrap_or_else(|e| {
            handler.emit_error(&e);
            std::process::exit(1);
        });
        ConfigBuilder {
            output_time_representation,
            start_time,
            state: IrConfigured { ir },
        }
    }

    /// Read the specification from the given string.
    pub fn spec_str(self, spec: &str) -> ConfigBuilder<IrConfigured, OutputTime> {
        let ConfigBuilder {
            output_time_representation,
            start_time,
            state: _,
        } = self;
        let config = rtlola_frontend::ParserConfig::for_string(spec.to_string());
        let handler = rtlola_frontend::Handler::from(config.clone());
        let ir = rtlola_frontend::parse(config).unwrap_or_else(|e| {
            handler.emit_error(&e);
            std::process::exit(1);
        });
        ConfigBuilder {
            output_time_representation,
            start_time,
            state: IrConfigured { ir },
        }
    }
}

impl<OutputTime: OutputTimeRepresentation> ConfigBuilder<IrConfigured, OutputTime> {
    /// Sets the execute mode to be online, i.e. the time of events is taken by the interpreter.
    pub fn online(self) -> ConfigBuilder<ModeConfigured<RealTime>, OutputTime> {
        let ConfigBuilder {
            output_time_representation,
            start_time,
            state: IrConfigured { ir },
        } = self;

        ConfigBuilder {
            output_time_representation,
            start_time,
            state: ModeConfigured {
                ir,
                input_time_representation: RealTime::default(),
                mode: ExecutionMode::Online,
            },
        }
    }

    /// Sets the execute mode to be offline, i.e. takes the time of events from the input source.
    /// How the input timestamps are interpreted is defined by the type parameter.
    /// See the README for further details on timestamp representations.
    /// For possible [TimeRepresentation]s see the [Time](crate::time) Module.
    pub fn offline<InputTime: TimeRepresentation>(self) -> ConfigBuilder<ModeConfigured<InputTime>, OutputTime> {
        let ConfigBuilder {
            output_time_representation,
            start_time,
            state: IrConfigured { ir },
        } = self;

        ConfigBuilder {
            output_time_representation,
            start_time,
            state: ModeConfigured {
                ir,
                input_time_representation: InputTime::default(),
                mode: ExecutionMode::Offline,
            },
        }
    }
}

impl<InputTime: TimeRepresentation, OutputTime: OutputTimeRepresentation>
    ConfigBuilder<ModeConfigured<InputTime>, OutputTime>
{
    /// Use the predefined [EventInput] method to provide inputs to the API.
    pub fn event_input<E: Into<Event> + CondSerialize + CondDeserialize + Send>(
        self,
    ) -> ConfigBuilder<InputConfigured<InputTime, EventInput<E>>, OutputTime> {
        let ConfigBuilder {
            output_time_representation,
            start_time,
            state:
                ModeConfigured {
                    ir,
                    input_time_representation,
                    mode,
                },
        } = self;

        ConfigBuilder {
            output_time_representation,
            start_time,
            state: InputConfigured {
                ir,
                input_time_representation,
                mode,
                source: PhantomData::default(),
            },
        }
    }

    /// Use the predefined [RecordInput] method to provide inputs to the API.
    pub fn record_input<Inner: Record>(
        self,
    ) -> ConfigBuilder<InputConfigured<InputTime, RecordInput<Inner>>, OutputTime> {
        let ConfigBuilder {
            output_time_representation,
            start_time,
            state:
                ModeConfigured {
                    ir,
                    input_time_representation,
                    mode,
                },
        } = self;

        ConfigBuilder {
            output_time_representation,
            start_time,
            state: InputConfigured {
                ir,
                input_time_representation,
                mode,
                source: PhantomData::default(),
            },
        }
    }

    /// Use a custom input method to provide inputs to the API.
    pub fn custom_input<Source: Input>(self) -> ConfigBuilder<InputConfigured<InputTime, Source>, OutputTime> {
        let ConfigBuilder {
            output_time_representation,
            start_time,
            state:
                ModeConfigured {
                    ir,
                    input_time_representation,
                    mode,
                },
        } = self;

        ConfigBuilder {
            output_time_representation,
            start_time,
            state: InputConfigured {
                ir,
                input_time_representation,
                mode,
                source: PhantomData::default(),
            },
        }
    }
}

impl<InputTime: TimeRepresentation, OutputTime: OutputTimeRepresentation, Source: Input>
    ConfigBuilder<InputConfigured<InputTime, Source>, OutputTime>
{
    /// Sets the [VerdictRepresentation] for the monitor
    pub fn with_verdict<Verdict: VerdictRepresentation>(
        self,
    ) -> ConfigBuilder<VerdictConfigured<InputTime, Source, Verdict>, OutputTime> {
        let ConfigBuilder {
            output_time_representation,
            start_time,
            state:
                InputConfigured {
                    ir,
                    input_time_representation,
                    mode,
                    source,
                },
        } = self;
        ConfigBuilder {
            output_time_representation,
            start_time,
            state: VerdictConfigured {
                ir,
                input_time_representation,
                mode,
                source,
                verdict: Default::default(),
            },
        }
    }
}

impl<
        Source: Input + 'static,
        InputTime: TimeRepresentation,
        Verdict: VerdictRepresentation<Tracing = NoTracer>,
        OutputTime: OutputTimeRepresentation,
    > ConfigBuilder<VerdictConfigured<InputTime, Source, Verdict>, OutputTime>
{
    /// Adds tracing functionality to the evaluator
    pub fn with_tracer<T: Tracer>(
        self,
    ) -> ConfigBuilder<VerdictConfigured<InputTime, Source, TracingVerdict<T, Verdict>>, OutputTime> {
        let ConfigBuilder {
            output_time_representation,
            start_time,
            state:
                VerdictConfigured {
                    ir,
                    input_time_representation,
                    mode,
                    source,
                    verdict: _,
                },
        } = self;
        ConfigBuilder {
            output_time_representation,
            start_time,
            state: VerdictConfigured {
                ir,
                input_time_representation,
                mode,
                source,
                verdict: Default::default(),
            },
        }
    }
}

impl<
        Source: Input + 'static,
        InputTime: TimeRepresentation,
        Verdict: VerdictRepresentation,
        OutputTime: OutputTimeRepresentation,
    > ConfigBuilder<VerdictConfigured<InputTime, Source, Verdict>, OutputTime>
{
    /// Finalize the configuration and generate a configuration.
    pub fn build(self) -> MonitorConfig<Source, InputTime, Verdict, OutputTime> {
        let ConfigBuilder {
            output_time_representation,
            start_time,
            state:
                VerdictConfigured {
                    ir,
                    input_time_representation,
                    mode,
                    ..
                },
        } = self;
        let config = Config {
            ir,
            mode,
            input_time_representation,
            output_time_representation,
            start_time,
        };
        MonitorConfig::new(config)
    }

    /// Create a [Monitor] from the configuration. The entrypoint of the API. The data is provided to the [Input](crate::monitor::Input) source at creation.
    pub fn monitor_with_data(
        self,
        data: Source::CreationData,
    ) -> Result<Monitor<Source, InputTime, Verdict, OutputTime>, Source::Error> {
        self.build().monitor_with_data(data)
    }

    /// Create a [Monitor] from the configuration. The entrypoint of the API.
    pub fn monitor(self) -> Result<Monitor<Source, InputTime, Verdict, OutputTime>, Source::Error>
    where
        Source: Input<CreationData = ()> + 'static,
    {
        self.build().monitor()
    }

    #[cfg(feature = "queued-api")]
    /// Create a [QueuedMonitor] from the configuration. The entrypoint of the API. The data is provided to the [Input](crate::monitor::Input) source at creation.
    pub fn queued_monitor_with_data(
        self,
        data: Source::CreationData,
    ) -> QueuedMonitor<Source, InputTime, Verdict, OutputTime> {
        self.build().queued_monitor_with_data(data)
    }

    #[cfg(feature = "queued-api")]
    /// Create a [QueuedMonitor] from the configuration. The entrypoint of the API.
    pub fn queued_monitor(self) -> QueuedMonitor<Source, InputTime, Verdict, OutputTime>
    where
        Source: Input<CreationData = ()> + 'static,
    {
        self.build().queued_monitor()
    }
}