rtlola_hir/hir.rs
1//! This module covers the High-Level Intermediate Representation (HIR) of an RTLola specification.
2//!
3//! The [RtLolaHir] is specifically designed to allow for convenient manipulation and analysis. Hence, it is perfect for working *on* the specification rather than work *with* it.
4//! # Most Notable Structs and Enums
5//! * [RtLolaMir](https://docs.rs/rtlola_frontend/struct.RtLolaMir.html) is the root data structure representing the specification.
6//! * [Output] represents a single output stream. The data structure is enriched with information regarding streams accessing it or accessed by it and much more. For input streams confer [Input].
7//! * [StreamReference] used for referencing streams within the Mir.
8//! * [Expression] represents an expression. It contains its [ExpressionKind] and its type. The latter contains all information specific to a certain kind of expression such as sub-expressions of operators.
9//!
10//! # See Also
11//! * [rtlola_frontend](https://docs.rs/rtlola_frontend) for an overview regarding different representations.
12//! * [from_ast](crate::from_ast) / [fully_analyzed](crate::fully_analyzed) to obtain an [RtLolaHir] for a specification in form of an Ast.
13//! * [RtLolaHir] for a data structs designed for working _on_it.
14//! * [RtLolaAst](rtlola_parser::RtLolaAst), which is the most basic and down-to-syntax data structure available for RTLola.
15
16mod expression;
17mod feature_selector;
18mod print;
19pub mod selector;
20
21use std::collections::HashMap;
22use std::fmt::Debug;
23use std::time::Duration;
24
25pub use feature_selector::{Feature, FeatureSelector};
26use rtlola_parser::ast::Tag;
27use rtlola_reporting::Span;
28use serde::{Deserialize, Serialize};
29use uom::si::rational64::Frequency as UOM_Frequency;
30
31pub use crate::hir::expression::*;
32pub use crate::modes::ast_conversion::TransformationErr;
33pub use crate::modes::dependencies::{DependencyErr, DependencyGraph, EdgeWeight, Origin};
34pub use crate::modes::memory_bounds::MemorizationBound;
35pub use crate::modes::ordering::{Layer, StreamLayers};
36use crate::modes::HirMode;
37pub use crate::modes::{
38 BaseMode, CompleteMode, DepAnaMode, DepAnaTrait, HirStage, MemBoundMode, MemBoundTrait,
39 OrderedMode, OrderedTrait, TypedMode, TypedTrait,
40};
41use crate::stdlib::FuncDecl;
42pub use crate::type_check::{
43 ActivationCondition, ConcretePacingType, ConcreteStreamPacing, ConcreteValueType, StreamType,
44};
45
46/// This struct constitutes the Mid-Level Intermediate Representation (MIR) of an RTLola specification.
47///
48/// The [RtLolaHir] is specifically designed to allow for convenient manipulation and analysis. Hence, it is perfect for working *on* the specification rather than work *with* it.
49///
50/// # Most Notable Structs and Enums
51/// * [RtLolaMir](https://docs.rs/rtlola_frontend/struct.RtLolaMir.html) is the root data structure representing the specification.
52/// * [Output] represents a single output stream. The data structure is enriched with information regarding streams accessing it or accessed by it and much more. For input streams confer [Input].
53/// * [StreamReference] used for referencing streams within the Mir.
54/// * [Expression] represents an expression. It contains its [ExpressionKind] and its type. The latter contains all information specific to a certain kind of expression such as sub-expressions of operators.
55///
56/// # Type-State
57/// The Hir follows a type-state pattern. To this end, it has a type parameter, its HirMode. The Hir starts in the [BaseMode] and progresses through different stages until reaching [CompleteMode].
58/// Each stage constitutes another level of refinement and adds functionality. The functionality can be accesses by importing the respective trait and requiring the mode of the Hir to implement the trait.
59/// The following traits exist.
60/// * [DepAnaTrait] provides access to a dependency graph (see [petgraph](petgraph::stable_graph::StableGraph)) and functions to access immediate neighbors of streams. Obtained via [determine_evaluation_order](RtLolaHir::<TypeMode>::determine_evaluation_order).
61/// * [TypedTrait] provides type information. Obtained via [check_types](crate::hir::RtLolaHir::<DepAnaMode>::check_types).
62/// * [OrderedTrait] provides information regarding the evaluation order of streams. Obtained via [determine_evaluation_order](crate::hir::RtLolaHir::<TypedMode>::determine_evaluation_order).
63/// * [MemBoundTrait] provides information on how many values of a stream have to be kept in memory at the same time. Obtained via [determine_memory_bounds](crate::hir::RtLolaHir::<OrderedMode>::determine_memory_bounds).
64///
65/// Progression through different stages is managed by the [HirStage] trait, in particular [HirStage::progress].
66///
67/// # See Also
68/// * [rtlola_frontend](https://docs.rs/rtlola_frontend) for an overview regarding different representations.
69/// * [from_ast](crate::from_ast) / [fully_analyzed](crate::fully_analyzed) to obtain an [RtLolaHir] for a specification in form of an Ast.
70/// * [RtLolaHir] for a data structs designed for working _on_it.
71/// * [RtLolaAst](rtlola_parser::RtLolaAst), which is the most basic and down-to-syntax data structure available for RTLola.
72#[derive(Debug, Clone)]
73pub struct RtLolaHir<M: HirMode> {
74 /// Collection of input streams
75 pub(crate) inputs: Vec<Input>,
76 /// Collection of output streams
77 pub(crate) outputs: Vec<Output>,
78 /// Next free input reference used to create new input streams
79 pub(crate) next_input_ref: usize,
80 /// Next free output reference used to create new output streams
81 pub(crate) next_output_ref: usize,
82 /// Maps expression ids to their expressions.
83 pub(crate) expr_maps: ExpressionMaps,
84 /// A list of the global tags of the specification
85 pub(crate) global_tags: HashMap<String, Tag>,
86 /// The current mode
87 pub(crate) mode: M,
88}
89
90pub(crate) type Hir<M> = RtLolaHir<M>;
91
92impl<M: HirMode> Hir<M> {
93 /// Provides access to an iterator over all input streams.
94 pub fn inputs(&self) -> impl Iterator<Item = &Input> {
95 self.inputs.iter()
96 }
97
98 /// Provides access to an iterator over all output streams.
99 pub fn outputs(&self) -> impl Iterator<Item = &Output> {
100 self.outputs.iter()
101 }
102
103 /// Provides access to an iterator over all triggers.
104 pub fn triggers(&self) -> impl Iterator<Item = &Output> {
105 self.outputs()
106 .filter(|output| matches!(output.kind, OutputKind::Trigger(_)))
107 }
108
109 /// Yields the number of input streams present in the Hir. Not necessarily equal to the number of input streams in the specification.
110 pub fn num_inputs(&self) -> usize {
111 self.inputs.len()
112 }
113
114 /// Yields the number of output streams present in the Hir. Not necessarily equal to the number of output streams in the specification.
115 pub fn num_outputs(&self) -> usize {
116 self.outputs.len()
117 }
118
119 /// Yields the number of triggers present in the Hir. Not necessarily equal to the number of triggers in the specification.
120 pub fn num_triggers(&self) -> usize {
121 self.triggers().count()
122 }
123
124 /// Provides access to an iterator over all streams, i.e., inputs, outputs, and triggers.
125 pub fn all_streams(&'_ self) -> impl Iterator<Item = SRef> + '_ {
126 self.inputs
127 .iter()
128 .map(|i| i.sr)
129 .chain(self.outputs.iter().map(|o| o.sr))
130 }
131
132 /// Retrieves an input stream based on its name. Fails if no such input stream exists.
133 pub fn get_input_with_name(&self, name: &str) -> Option<&Input> {
134 self.inputs.iter().find(|&i| i.name == name)
135 }
136
137 /// Retrieves an output stream based on its name. Fails if no such output stream exists.
138 pub fn get_output_with_name(&self, name: &str) -> Option<&Output> {
139 self.outputs.iter().find(|&o| o.name() == name)
140 }
141
142 /// Retrieves an output stream based on a stream reference. Fails if no such stream exists or `sref` is a [StreamReference::In].
143 pub fn output(&self, sref: SRef) -> Option<&Output> {
144 self.outputs().find(|o| o.sr == sref)
145 }
146
147 /// Retrieves an input stream based on a stream reference. Fails if no such stream exists or `sref` is a [StreamReference::Out].
148 pub fn input(&self, sref: SRef) -> Option<&Input> {
149 self.inputs().find(|i| i.sr == sref)
150 }
151
152 /// Provides access to a collection of references for all windows occurring in the Hir.
153 pub fn window_refs(&self) -> Vec<WRef> {
154 self.expr_maps
155 .sliding_windows
156 .keys()
157 .chain(self.expr_maps.discrete_windows.keys())
158 .cloned()
159 .collect()
160 }
161
162 /// Provides access to a collection of references for all sliding windows occurring in the Hir.
163 pub fn sliding_windows(&self) -> Vec<&Window<SlidingAggr>> {
164 self.expr_maps.sliding_windows.values().clone().collect()
165 }
166
167 /// Provides access to a collection of references for all discrete windows occurring in the Hir.
168 pub fn discrete_windows(&self) -> Vec<&Window<DiscreteAggr>> {
169 self.expr_maps.discrete_windows.values().clone().collect()
170 }
171
172 /// Provides access to a collection of references for all discrete windows occurring in the Hir.
173 pub fn instance_aggregations(&self) -> Vec<&InstanceAggregation> {
174 self.expr_maps
175 .instance_aggregations
176 .values()
177 .clone()
178 .collect()
179 }
180
181 /// Retrieves an expression for a given expression id.
182 ///
183 /// # Panic
184 /// Panics if the expression does not exist.
185 pub fn expression(&self, id: ExprId) -> &Expression {
186 &self.expr_maps.exprid_to_expr[&id]
187 }
188
189 /// Retrieves a function declaration for a given function name.
190 ///
191 /// # Panic
192 /// Panics if the declaration does not exist.
193 pub fn func_declaration(&self, func_name: &str) -> &FuncDecl {
194 &self.expr_maps.func_table[func_name]
195 }
196
197 /// Retrieves a single sliding window for a given reference.
198 ///
199 /// # Panic
200 /// Panics if no such window exists.
201 pub fn single_sliding(&self, window: WRef) -> Window<SlidingAggr> {
202 *self
203 .sliding_windows()
204 .into_iter()
205 .find(|w| w.reference == window)
206 .unwrap()
207 }
208
209 /// Retrieves a single discrete window for a given reference.
210 ///
211 /// # Panic
212 /// Panics if no such window exists.
213 pub fn single_discrete(&self, window: WRef) -> Window<DiscreteAggr> {
214 *self
215 .discrete_windows()
216 .into_iter()
217 .find(|w| w.reference == window)
218 .unwrap()
219 }
220
221 /// Retrieves a single instance aggregation for a given reference.
222 ///
223 /// # Panic
224 /// Panics if no such aggregation exists.
225 pub fn single_instance_aggregation(&self, window: WRef) -> &InstanceAggregation {
226 self.instance_aggregations()
227 .iter()
228 .find(|w| w.reference == window)
229 .unwrap()
230 }
231
232 /// Retrieves the spawn definition of a particular output stream or trigger or `None` for input references.
233 pub fn spawn(&self, sr: SRef) -> Option<SpawnDef> {
234 match sr {
235 SRef::In(_) => None,
236 SRef::Out(_) => {
237 let output = self.outputs.iter().find(|o| o.sr == sr);
238 output.and_then(|o| o.spawn()).map(|st| {
239 SpawnDef::new(
240 st.expression.map(|e| self.expression(e)),
241 st.condition.map(|e| self.expression(e)),
242 &st.pacing,
243 st.span,
244 )
245 })
246 }
247 }
248 }
249
250 /// Retrieves the spawn condition of a particular output stream or `None` for input and trigger references.
251 /// If all parts of the [SpawnDef] are needed, see [RtLolaHir::spawn]
252 pub fn spawn_cond(&self, sr: SRef) -> Option<&Expression> {
253 match sr {
254 SRef::In(_) => None,
255 SRef::Out(_) => self
256 .outputs
257 .iter()
258 .find(|o| o.sr == sr)
259 .and_then(|o| o.spawn_cond())
260 .map(|eid| self.expression(eid)),
261 }
262 }
263
264 /// Retrieves the spawn expresion of a particular output stream or `None` for input and trigger references.
265 /// If all parts of the [SpawnDef] are needed, see [RtLolaHir::spawn]
266 pub fn spawn_expr(&self, sr: SRef) -> Option<&Expression> {
267 match sr {
268 SRef::In(_) => None,
269 SRef::Out(_) => self
270 .outputs
271 .iter()
272 .find(|o| o.sr == sr)
273 .and_then(|o| o.spawn_expr())
274 .map(|eid| self.expression(eid)),
275 }
276 }
277
278 /// Retrieves the spawn pacing of a particular output stream or `None` for input and trigger references.
279 /// If all parts of the [SpawnDef] are needed, see [RtLolaHir::spawn]
280 pub fn spawn_pacing(&self, sr: SRef) -> Option<&AnnotatedPacingType> {
281 match sr {
282 SRef::In(_) => None,
283 SRef::Out(_) => self
284 .outputs
285 .iter()
286 .find(|o| o.sr == sr)
287 .and_then(|o| o.spawn_pacing()),
288 }
289 }
290
291 /// Same behavior as [spawn].
292 /// # Panic
293 /// Panics if the stream does not exist or is an input/trigger.
294 #[cfg(test)]
295 pub(crate) fn spawn_unchecked(&self, sr: SRef) -> SpawnDef {
296 self.spawn(sr)
297 .expect("Invalid for input and triggers references")
298 }
299
300 /// Retrieves the eval definitions of a particular output stream or trigger or `None` for input references.
301 pub fn eval(&self, sr: SRef) -> Option<Vec<EvalDef>> {
302 match sr {
303 SRef::In(_) => None,
304 SRef::Out(_) => {
305 let output = self.outputs.iter().find(|o| o.sr == sr);
306 output.map(|o| {
307 o.eval()
308 .iter()
309 .map(|eval| {
310 EvalDef::new(
311 eval.condition.map(|id| self.expression(id)),
312 self.expression(eval.expr),
313 &eval.annotated_pacing_type,
314 eval.span,
315 )
316 })
317 .collect()
318 })
319 }
320 }
321 }
322
323 /// Retrieves all eval conditions of the clauses of a particular output stream or `None` for input and trigger references.
324 /// For each eval clause of the stream, the element in the Vec is `None` if no condition is
325 /// or the coresponding condition otherwise.
326 /// If all parts of the [EvalDef] are needed, see [RtLolaHir::eval]
327 pub fn eval_cond(&self, sr: SRef) -> Option<Vec<Option<&Expression>>> {
328 match sr {
329 SRef::In(_) => None,
330 SRef::Out(o) => {
331 if o < self.outputs.len() {
332 self.outputs.iter().find(|o| o.sr == sr).map(|output| {
333 output
334 .eval
335 .iter()
336 .map(|e| e.condition.map(|eid| self.expression(eid)))
337 .collect()
338 })
339 } else {
340 Some(vec![None])
341 }
342 }
343 }
344 }
345
346 /// Retrieves the eval expressions of all eval clauses of a particular output stream or trigger and `None` for input references.
347 /// If all parts of the [EvalDef] are needed, see [RtLolaHir::eval]
348 pub fn eval_expr(&self, sr: SRef) -> Option<Vec<&Expression>> {
349 match sr {
350 SRef::In(_) => None,
351 SRef::Out(_) => self.outputs.iter().find(|o| o.sr == sr).map(|output| {
352 output
353 .eval
354 .iter()
355 .map(|eval| self.expression(eval.expr))
356 .collect()
357 }),
358 }
359 }
360
361 /// Retrieves the annotated eval pacing of each eval clause of a particular output stream or trigger `None` for input references.
362 /// If all parts of the [EvalDef] are needed, see [RtLolaHir::eval]
363 pub fn eval_pacing(&self, sr: SRef) -> Option<Vec<&AnnotatedPacingType>> {
364 match sr {
365 SRef::In(_) => None,
366 SRef::Out(_) => {
367 let output = self.outputs.iter().find(|o| o.sr == sr)?;
368 Some(
369 output
370 .eval
371 .iter()
372 .map(|eval| &eval.annotated_pacing_type)
373 .collect(),
374 )
375 }
376 }
377 }
378
379 /// Same behavior as [`eval`](fn@Hir).
380 /// # Panic
381 /// Panics if the stream does not exist or is an input.
382 pub(crate) fn eval_unchecked(&self, sr: StreamReference) -> Vec<EvalDef> {
383 self.eval(sr).expect("Invalid for input references")
384 }
385
386 /// Retrieves the expressions representing the close definition of a particular output stream or `None` for input and trigger references.
387 pub fn close(&self, sr: SRef) -> Option<CloseDef> {
388 match sr {
389 SRef::In(_) => None,
390 SRef::Out(_) => {
391 let ct = self
392 .outputs
393 .iter()
394 .find(|o| o.sr == sr)
395 .and_then(|o| o.close());
396 ct.map(|ct| CloseDef::new(Some(self.expression(ct.condition)), &ct.pacing, ct.span))
397 }
398 }
399 }
400
401 /// Retrieves the expression representing the close condition of a particular output stream or `None` for input and trigger references.
402 /// If all parts of the [CloseDef] are needed, see [RtLolaHir::close]
403 pub fn close_cond(&self, sr: SRef) -> Option<&Expression> {
404 match sr {
405 SRef::In(_) => None,
406 SRef::Out(_) => self
407 .outputs
408 .iter()
409 .find(|o| o.sr == sr)
410 .and_then(|o| o.close_cond())
411 .map(|eid| self.expression(eid)),
412 }
413 }
414
415 /// Retrieves the close pacing of a particular output stream or `None` for input and trigger references.
416 /// If all parts of the [CloseDef] are needed, see [RtLolaHir::close]
417 pub fn close_pacing(&self, sr: SRef) -> Option<&AnnotatedPacingType> {
418 match sr {
419 SRef::In(_) => None,
420 SRef::Out(_) => self
421 .outputs
422 .iter()
423 .find(|o| o.sr == sr)
424 .and_then(|o| o.close_pacing()),
425 }
426 }
427
428 /// Same behavior as [`close`](fn@Hir).
429 /// # Panic
430 /// Panics if the stream does not exist or is an input/trigger.
431 #[cfg(test)]
432 pub(crate) fn close_unchecked(&self, sr: StreamReference) -> CloseDef {
433 self.close(sr)
434 .expect("Invalid for input and triggers references")
435 }
436
437 /// Generates a map from a [StreamReference] to the name of the corresponding stream.
438 pub fn names(&self) -> HashMap<SRef, String> {
439 self.inputs()
440 .map(|i| (i.sr, i.name.clone()))
441 .chain(self.outputs().map(|o| (o.sr, o.name())))
442 .collect()
443 }
444
445 /// Returns the global tags annotated to the specification
446 pub fn global_tags(&self) -> &HashMap<String, Tag> {
447 &self.global_tags
448 }
449}
450
451/// A collection of maps for expression-related lookups, i.e., expressions, functions, and windows.
452#[derive(Clone, Debug)]
453pub(crate) struct ExpressionMaps {
454 exprid_to_expr: HashMap<ExprId, Expression>,
455 sliding_windows: HashMap<WRef, Window<SlidingAggr>>,
456 discrete_windows: HashMap<WRef, Window<DiscreteAggr>>,
457 instance_aggregations: HashMap<WRef, InstanceAggregation>,
458 func_table: HashMap<String, FuncDecl>,
459}
460
461impl ExpressionMaps {
462 /// Creates a new expression map.
463 pub(crate) fn new(
464 exprid_to_expr: HashMap<ExprId, Expression>,
465 sliding_windows: HashMap<WRef, Window<SlidingAggr>>,
466 discrete_windows: HashMap<WRef, Window<DiscreteAggr>>,
467 instance_aggregations: HashMap<WRef, InstanceAggregation>,
468 func_table: HashMap<String, FuncDecl>,
469 ) -> Self {
470 Self {
471 exprid_to_expr,
472 sliding_windows,
473 discrete_windows,
474 instance_aggregations,
475 func_table,
476 }
477 }
478}
479
480/// Represents the name of a function including its arguments.
481#[derive(Debug, Clone)]
482pub enum FunctionName {
483 /// the function has a fixed number of (possibly named) arguments
484 FixedParameters {
485 /// The name of the function
486 name: String,
487 /// For each argument its name (or None if it does not have a name)
488 arg_names: Vec<Option<String>>,
489 },
490 /// The function has an arbitrary amount of (unnamed) arguments
491 ArbitraryParameters {
492 /// The name of the function
493 name: String,
494 },
495}
496
497impl FunctionName {
498 /// Creates a new FunctionName with a predefined number of arguments.
499 pub(crate) fn new(name: String, arg_names: &[Option<String>]) -> Self {
500 Self::FixedParameters {
501 name,
502 arg_names: Vec::from(arg_names),
503 }
504 }
505
506 pub(crate) fn new_repeating(name: String) -> Self {
507 Self::ArbitraryParameters { name }
508 }
509
510 pub(crate) fn name(&self) -> &str {
511 match self {
512 FunctionName::FixedParameters { name, .. } => name,
513 FunctionName::ArbitraryParameters { name } => name,
514 }
515 }
516}
517
518impl PartialEq for FunctionName {
519 fn eq(&self, other: &Self) -> bool {
520 match (self, other) {
521 (Self::ArbitraryParameters { name }, other)
522 | (other, Self::ArbitraryParameters { name }) => name == other.name(),
523 (
524 Self::FixedParameters {
525 name: s_name,
526 arg_names: s_arg_names,
527 },
528 Self::FixedParameters {
529 name: o_name,
530 arg_names: o_arg_names,
531 },
532 ) => s_name == o_name && s_arg_names == o_arg_names,
533 }
534 }
535}
536
537impl std::hash::Hash for FunctionName {
538 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
539 match self {
540 FunctionName::FixedParameters { name, arg_names: _ } => name,
541 FunctionName::ArbitraryParameters { name } => name,
542 }
543 .hash(state)
544 }
545}
546
547impl Eq for FunctionName {}
548
549/// Represents an input stream in an RTLola specification.
550#[derive(Debug, Clone)]
551pub struct Input {
552 /// The name of the stream.
553 pub name: String,
554 /// The reference pointing to this stream.
555 pub(crate) sr: SRef,
556 /// The user annotated Type
557 pub(crate) annotated_type: AnnotatedType,
558 /// The tags of this stream.
559 pub tags: HashMap<String, Tag>,
560 /// The code span the input represents
561 pub(crate) span: Span,
562}
563
564impl Input {
565 /// Yields the reference referring to this input stream.
566 pub fn sr(&self) -> StreamReference {
567 self.sr
568 }
569
570 /// Yields the span referring to a part of the specification from which this stream originated.
571 pub fn span(&self) -> Span {
572 self.span
573 }
574}
575
576/// Whether the given output stream is a regular named output or represents a trigger
577#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, Ord, PartialOrd)]
578pub enum OutputKind {
579 /// The output is a regular named output stream
580 NamedOutput(String),
581 /// The output represents a trigger
582 Trigger(usize),
583}
584
585/// Represents an output stream in an RTLola specification.
586#[derive(Debug, Clone)]
587pub struct Output {
588 /// The kind of the stream.
589 pub kind: OutputKind,
590 /// The user annotated Type
591 pub(crate) annotated_type: Option<AnnotatedType>,
592 /// The parameters of a parameterized output stream; The vector is empty in non-parametrized streams
593 pub(crate) params: Vec<Parameter>,
594 /// The optional information on the spawning behavior of the stream
595 pub(crate) spawn: Option<Spawn>,
596 /// The information regarding evaluation expression and condition of the stream
597 pub(crate) eval: Vec<Eval>,
598 /// The optional closing condition
599 pub(crate) close: Option<Close>,
600 /// The reference pointing to this stream.
601 pub(crate) sr: SRef,
602 /// The tags of this stream.
603 pub tags: HashMap<String, Tag>,
604 /// The code span the output represents
605 pub(crate) span: Span,
606}
607
608impl Output {
609 /// Returns the name of this stream.
610 pub fn name(&self) -> String {
611 match &self.kind {
612 OutputKind::NamedOutput(s) => s.clone(),
613 OutputKind::Trigger(idx) => format!("trigger_{idx}"),
614 }
615 }
616
617 /// Returns an iterator over the parameters of this stream.
618 pub fn params(&self) -> impl Iterator<Item = &Parameter> {
619 self.params.iter()
620 }
621
622 /// Yields the reference referring to this input stream.
623 pub fn sr(&self) -> StreamReference {
624 self.sr
625 }
626
627 /// Returns the [Spawn] template of the stream
628 pub(crate) fn spawn(&self) -> Option<&Spawn> {
629 self.spawn.as_ref()
630 }
631
632 /// Returns the expression id for the spawn condition of this stream
633 /// If all parts of [Spawn] are required, see [spawn](fn@Hir)
634 pub(crate) fn spawn_cond(&self) -> Option<ExprId> {
635 self.spawn.as_ref().and_then(|st| st.condition)
636 }
637
638 /// Returns the expression id for the spawn expression of this stream
639 /// If all parts of [Spawn] are required, see [spawn](fn@Hir)
640 pub(crate) fn spawn_expr(&self) -> Option<ExprId> {
641 self.spawn.as_ref().and_then(|st| st.expression)
642 }
643
644 /// Returns the pacing for the spawn condition of this stream
645 /// If all parts of [Spawn] are required, see [spawn](fn@Hir)
646 #[allow(dead_code)]
647 pub(crate) fn spawn_pacing(&self) -> Option<&AnnotatedPacingType> {
648 self.spawn.as_ref().map(|st| &st.pacing)
649 }
650
651 /// Returns the [Close] template of the stream
652 pub(crate) fn close(&self) -> Option<&Close> {
653 self.close.as_ref()
654 }
655
656 /// Returns the expression id for the close condition of this stream
657 /// If all parts of [Close] are required, see [close](fn@Hir)
658 pub(crate) fn close_cond(&self) -> Option<ExprId> {
659 self.close.as_ref().map(|ct| ct.condition)
660 }
661
662 /// Returns the pacing for the close condition of this stream
663 /// If all parts of [Close] are required, see [close](fn@Hir))
664 #[allow(dead_code)]
665 pub(crate) fn close_pacing(&self) -> Option<&AnnotatedPacingType> {
666 self.close.as_ref().map(|ct| &ct.pacing)
667 }
668
669 /// Returns the [Eval] template of the stream
670 pub(crate) fn eval(&self) -> &[Eval] {
671 &self.eval
672 }
673
674 /// Yields the span referring to a part of the specification from which this stream originated.
675 pub fn span(&self) -> Span {
676 self.span
677 }
678}
679
680/// Represents a single parameter of a parametrized output stream.
681#[derive(Debug, PartialEq, Clone, Eq)]
682pub struct Parameter {
683 /// The name of this parameter
684 pub name: String,
685 /// The annotated type of this parameter
686 pub(crate) annotated_type: Option<AnnotatedType>,
687 /// The index of this parameter
688 pub(crate) idx: usize,
689 /// The code span of the parameter
690 pub(crate) span: Span,
691}
692
693impl Parameter {
694 /// Yields the index of this parameter. If the index is 3, then the parameter is the fourth parameter of the respective stream.
695 pub fn index(&self) -> usize {
696 self.idx
697 }
698
699 /// Yields the span referring to a part of the specification where this parameter occurs.
700 pub fn span(&self) -> Span {
701 self.span
702 }
703}
704
705#[derive(Debug, Clone, Copy, PartialEq, Eq)]
706/// Frequency of an annotated pacing information for stream
707pub struct AnnotatedFrequency {
708 /// A span to the part of the specification containing the frequency
709 pub span: Span,
710 /// The actual frequency
711 pub value: UOM_Frequency,
712}
713
714/// Pacing information for stream; contains either a frequency or a condition on input streams.
715#[derive(Debug, Clone, Copy, PartialEq, Eq)]
716pub enum AnnotatedPacingType {
717 /// The global evaluation frequency
718 GlobalFrequency(AnnotatedFrequency),
719 /// The local evaluation frequency
720 LocalFrequency(AnnotatedFrequency),
721 /// The expression which constitutes the condition under which the stream should be evaluated.
722 Event(ExprId),
723 /// The stream is not annotated with a pacing
724 NotAnnotated(Span),
725}
726
727impl Default for AnnotatedPacingType {
728 fn default() -> Self {
729 AnnotatedPacingType::NotAnnotated(Span::default())
730 }
731}
732
733impl AnnotatedPacingType {
734 /// Returns the span of the annotated type.
735 pub fn span<M: HirMode>(&self, hir: &Hir<M>) -> Span {
736 match self {
737 AnnotatedPacingType::GlobalFrequency(freq)
738 | AnnotatedPacingType::LocalFrequency(freq) => freq.span,
739 AnnotatedPacingType::Event(id) => hir.expression(*id).span,
740 AnnotatedPacingType::NotAnnotated(span) => *span,
741 }
742 }
743}
744
745/// Information regarding the spawning behavior of a stream
746#[derive(Debug, Clone, Default)]
747pub(crate) struct Spawn {
748 /// The expression defining the parameter instances. If the stream has more than one parameter, the expression needs to return a tuple, with one element for each parameter
749 pub(crate) expression: Option<ExprId>,
750 /// The activation condition describing when a new instance is created.
751 pub(crate) pacing: AnnotatedPacingType,
752 /// An additional condition for the creation of an instance, i.e., an instance is only created if the condition is true.
753 pub(crate) condition: Option<ExprId>,
754 /// The range in the specification corresponding to the spawn clause.
755 pub(crate) span: Span,
756}
757
758impl Spawn {
759 /// Returns a reference to the `Expression` representing the spawn expression if it exists
760 pub(crate) fn spawn_expr<'a, M: HirMode>(
761 &self,
762 hir: &'a RtLolaHir<M>,
763 ) -> Option<&'a Expression> {
764 self.expression.map(|eid| hir.expression(eid))
765 }
766
767 /// Returns a vector of `Expression` references representing the expressions with which the parameters of the stream are initialized
768 pub(crate) fn spawn_args<'a, M: HirMode>(&self, hir: &'a RtLolaHir<M>) -> Vec<&'a Expression> {
769 self.spawn_expr(hir)
770 .map(|se| match &se.kind {
771 ExpressionKind::Tuple(spawns) => spawns.iter().collect(),
772 _ => vec![se],
773 })
774 .unwrap_or_default()
775 }
776
777 /// Returns a reference to the `Expression` representing the spawn condition if it exists
778 pub(crate) fn spawn_cond<'a, M: HirMode>(
779 &self,
780 hir: &'a RtLolaHir<M>,
781 ) -> Option<&'a Expression> {
782 self.condition.map(|eid| hir.expression(eid))
783 }
784}
785
786/// Information regarding the evaluation condition and evaluation behavior of a stream
787#[derive(Debug, Clone)]
788pub(crate) struct Eval {
789 /// The activation condition, which defines when a new value of a stream is computed.
790 pub(crate) annotated_pacing_type: AnnotatedPacingType,
791 /// The expression defining when an instance is evaluated
792 pub(crate) condition: Option<ExprId>,
793 /// The stream expression of a output stream, e.g., a + b.offset(by: -1).defaults(to: 0)
794 pub(crate) expr: ExprId,
795 /// The range in the specification corresponding to the eval clause.
796 pub(crate) span: Span,
797}
798
799/// Information regarding the closing behavior of a stream
800#[derive(Debug, Clone)]
801pub(crate) struct Close {
802 /// The expression defining if an instance is closed
803 pub(crate) condition: ExprId,
804 /// The activation condition describing when an instance is closed
805 pub(crate) pacing: AnnotatedPacingType,
806 /// The range in the specification corresponding to the close clause.
807 pub(crate) span: Span,
808}
809
810/// The Hir Spawn definition is composed of two optional expressions and the annotated pacing.
811/// The first one refers to the spawn expression while the second one represents the spawn condition.
812#[derive(Debug, Clone, Copy)]
813pub struct SpawnDef<'a> {
814 /// The expression of the stream is spawned with, setting the parameters, e.g. spawn with (3,x)
815 pub expression: Option<&'a Expression>,
816 /// The conditional expression of the spawn, e.g. when x > 5
817 pub condition: Option<&'a Expression>,
818 /// The pacing type of the spawn, e.g. @1Hz or @input_i
819 pub annotated_pacing: &'a AnnotatedPacingType,
820 /// The range in the specification corresponding to the spawn clause.
821 pub span: Span,
822}
823
824impl<'a> SpawnDef<'a> {
825 /// Constructs a new [SpawnDef]
826 pub fn new(
827 expression: Option<&'a Expression>,
828 condition: Option<&'a Expression>,
829 annotated_pacing: &'a AnnotatedPacingType,
830 span: Span,
831 ) -> Self {
832 Self {
833 expression,
834 condition,
835 annotated_pacing,
836 span,
837 }
838 }
839}
840
841/// The Hir Eval definition is composed of three expressions and the annotated pacing.
842/// The first one refers to the evaluation condition, while the second one represents the evaluation expression, defining the value of the stream.
843#[derive(Debug, Clone, Copy)]
844pub struct EvalDef<'a> {
845 /// The evaluation condition has to evaluated to true in order for the stream expression to be evaluated.
846 pub condition: Option<&'a Expression>,
847 /// The stream expression defines the computed value of the stream.
848 pub expression: &'a Expression,
849 /// The annotated pacing of the stream evaluation, describing when the condition and expression should be evaluated in a temporal manner.
850 pub annotated_pacing: &'a AnnotatedPacingType,
851 /// The range in the specification corresponding to the eval clause.
852 pub span: Span,
853}
854
855impl<'a> EvalDef<'a> {
856 /// Constructs a new [EvalDef]
857 pub fn new(
858 condition: Option<&'a Expression>,
859 expr: &'a Expression,
860 annotated_pacing: &'a AnnotatedPacingType,
861 span: Span,
862 ) -> Self {
863 Self {
864 condition,
865 expression: expr,
866 annotated_pacing,
867 span,
868 }
869 }
870}
871
872/// The Hir Close definition is composed of the Close condition expression and the annotated pacing.
873#[derive(Debug, Clone, Copy)]
874pub struct CloseDef<'a> {
875 /// The close condition, defining when a stream instance is closed and no longer evaluated.
876 pub condition: Option<&'a Expression>,
877 /// The annotated pacing, indicating when the condition should be evaluated.
878 pub annotated_pacing: &'a AnnotatedPacingType,
879 /// The range in the specification corresponding to the close clause.
880 pub span: Span,
881}
882
883impl<'a> CloseDef<'a> {
884 /// Constructs a new [CloseDef]
885 pub fn new(
886 condition: Option<&'a Expression>,
887 annotated_pacing: &'a AnnotatedPacingType,
888 span: Span,
889 ) -> Self {
890 Self {
891 condition,
892 annotated_pacing,
893 span,
894 }
895 }
896}
897
898/// Represents the annotated given type for constants, input streams, etc.
899/// It is converted from the AST type and an input for the type checker.
900/// After typechecking HirType is used to represent all type information.
901#[derive(Debug, PartialEq, Eq, Clone, Hash)]
902pub(crate) enum AnnotatedType {
903 Int(u32),
904 Fixed(u32, u32),
905 Float(u32),
906 UInt(u32),
907 UFixed(u32, u32),
908 Bool,
909 String,
910 Bytes,
911 Option(Box<AnnotatedType>),
912 Tuple(Vec<AnnotatedType>),
913 Numeric,
914 Fractional,
915 Signed,
916 Sequence,
917 Param(usize, String),
918 Any,
919}
920
921impl AnnotatedType {
922 /// Yields a collection of primitive types and their names.
923 pub(crate) fn primitive_types() -> Vec<(&'static str, &'static AnnotatedType)> {
924 let mut types = vec![];
925 types.extend_from_slice(&crate::stdlib::PRIMITIVE_TYPES);
926 types.extend_from_slice(&crate::stdlib::PRIMITIVE_TYPES_ALIASES);
927
928 types
929 }
930}
931
932/// Allows for referencing a window instance.
933#[derive(Hash, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
934pub enum WindowReference {
935 /// Refers to a sliding window
936 Sliding(usize),
937 /// Refers to a discrete window
938 Discrete(usize),
939 /// Refers to a instance aggregation
940 Instance(usize),
941}
942
943pub(crate) type WRef = WindowReference;
944
945impl WindowReference {
946 /// Provides access to the index inside the reference.
947 pub fn idx(self) -> usize {
948 match self {
949 WindowReference::Sliding(u) => u,
950 WindowReference::Discrete(u) => u,
951 WindowReference::Instance(u) => u,
952 }
953 }
954}
955
956/// Allows for referencing an input stream within the specification.
957pub type InputReference = usize;
958/// Allows for referencing an output stream within the specification.
959pub type OutputReference = usize;
960
961/// Allows for referencing a stream within the specification.
962#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Serialize, Deserialize)]
963pub enum StreamReference {
964 /// References an input stream.
965 In(InputReference),
966 /// References an output stream.
967 Out(OutputReference),
968}
969
970pub(crate) type SRef = StreamReference;
971
972impl StreamReference {
973 /// Returns the index inside the reference if it is an output reference. Panics otherwise.
974 pub fn out_ix(&self) -> usize {
975 match self {
976 StreamReference::In(_) => unreachable!(),
977 StreamReference::Out(ix) => *ix,
978 }
979 }
980
981 /// Returns the index inside the reference if it is an input reference. Panics otherwise.
982 pub fn in_ix(&self) -> usize {
983 match self {
984 StreamReference::Out(_) => unreachable!(),
985 StreamReference::In(ix) => *ix,
986 }
987 }
988
989 /// Returns the index inside the reference disregarding whether it is an input or output reference.
990 pub fn ix_unchecked(&self) -> usize {
991 match self {
992 StreamReference::In(ix) | StreamReference::Out(ix) => *ix,
993 }
994 }
995
996 /// True if the reference is an instance of [StreamReference::In], false otherwise.
997 pub fn is_input(&self) -> bool {
998 match self {
999 StreamReference::Out(_) => false,
1000 StreamReference::In(_) => true,
1001 }
1002 }
1003
1004 /// True if the reference is an instance of [StreamReference::Out], false otherwise.
1005 pub fn is_output(&self) -> bool {
1006 match self {
1007 StreamReference::Out(_) => true,
1008 StreamReference::In(_) => false,
1009 }
1010 }
1011}
1012
1013impl PartialOrd for StreamReference {
1014 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1015 Some(self.cmp(other))
1016 }
1017}
1018
1019impl Ord for StreamReference {
1020 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1021 use std::cmp::Ordering;
1022 match (self, other) {
1023 (StreamReference::In(i), StreamReference::In(i2)) => i.cmp(i2),
1024 (StreamReference::Out(o), StreamReference::Out(o2)) => o.cmp(o2),
1025 (StreamReference::In(_), StreamReference::Out(_)) => Ordering::Less,
1026 (StreamReference::Out(_), StreamReference::In(_)) => Ordering::Greater,
1027 }
1028 }
1029}
1030
1031/// Offset used in the lookup expression
1032#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
1033pub enum Offset {
1034 /// A strictly positive discrete offset, e.g., `4`, or `42`
1035 FutureDiscrete(u32),
1036 /// A non-negative discrete offset, e.g., `0`, `-4`, or `-42`
1037 PastDiscrete(u32),
1038 /// A positive real-time offset, e.g., `-3ms`, `-4min`, `-2.3h`
1039 FutureRealTime(Duration),
1040 /// A non-negative real-time offset, e.g., `0`, `4min`, `2.3h`
1041 PastRealTime(Duration),
1042}
1043
1044impl Offset {
1045 /// Returns `true`, iff the Offset is negative
1046 pub(crate) fn has_negative_offset(&self) -> bool {
1047 match self {
1048 Offset::FutureDiscrete(_) | Offset::FutureRealTime(_) => false,
1049 Offset::PastDiscrete(o) => *o != 0,
1050 Offset::PastRealTime(o) => o.as_nanos() != 0,
1051 }
1052 }
1053
1054 pub(crate) fn as_memory_bound(&self) -> MemorizationBound {
1055 match self {
1056 Offset::PastDiscrete(o) => {
1057 MemorizationBound::Bounded(*o) + MemorizationBound::Bounded(1)
1058 }
1059 Offset::FutureDiscrete(_) => unimplemented!(),
1060 Offset::FutureRealTime(_) => unimplemented!(),
1061 Offset::PastRealTime(_) => unimplemented!(),
1062 }
1063 }
1064}
1065
1066impl PartialOrd for Offset {
1067 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1068 Some(self.cmp(other))
1069 }
1070}
1071
1072impl Ord for Offset {
1073 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1074 use std::cmp::Ordering;
1075 use Offset::*;
1076 match (self, other) {
1077 (PastDiscrete(_), FutureDiscrete(_))
1078 | (PastRealTime(_), FutureRealTime(_))
1079 | (PastDiscrete(_), FutureRealTime(_))
1080 | (PastRealTime(_), FutureDiscrete(_)) => Ordering::Less,
1081
1082 (FutureDiscrete(_), PastDiscrete(_))
1083 | (FutureDiscrete(_), PastRealTime(_))
1084 | (FutureRealTime(_), PastDiscrete(_))
1085 | (FutureRealTime(_), PastRealTime(_)) => Ordering::Greater,
1086
1087 (FutureDiscrete(a), FutureDiscrete(b)) => a.cmp(b),
1088 (PastDiscrete(a), PastDiscrete(b)) => b.cmp(a),
1089
1090 (_, _) => unimplemented!(),
1091 }
1092 }
1093}