Skip to main content

mt_mtc/
lib.rs

1/// Comile compiler for .mt files and resolve variables or functions.
2use core::fmt;
3use std::{collections::HashMap, path::PathBuf, str::FromStr};
4
5use anyhow::anyhow;
6use ariadne::{Color, Label, Report, ReportKind, Source};
7use logos::{Lexer, Logos};
8
9use chumsky::{
10    container::Seq,
11    input::{Stream, ValueInput},
12    prelude::*,
13};
14use mt_net::{ActionPlan, COMPARE_NODE_NAME, Rules, VariableHuman};
15
16fn floating_millimeter<'a>(lex: &mut Lexer<'a, Token<'a>>) -> Option<f64> {
17    let slice = lex.slice();
18    let f: f64 = slice[..slice.len() - 2].parse().ok()?;
19    Some(f)
20}
21
22fn floating_centimeter<'a>(lex: &mut Lexer<'a, Token<'a>>) -> Option<f64> {
23    let slice = lex.slice();
24    let f: f64 = slice[..slice.len() - 2].parse().ok()?;
25    Some(f * 10.0)
26}
27
28fn floating_meter<'a>(lex: &mut Lexer<'a, Token<'a>>) -> Option<f64> {
29    let slice = lex.slice();
30    let f: f64 = slice[..slice.len() - 1].parse().ok()?;
31    Some(f * 10.0 * 100.0)
32}
33
34fn integer_millimeter<'a>(lex: &mut Lexer<'a, Token<'a>>) -> Option<i64> {
35    let slice = lex.slice();
36    let f: i64 = slice[..slice.len() - 2].parse().ok()?;
37    Some(f)
38}
39
40fn integer_centimeter<'a>(lex: &mut Lexer<'a, Token<'a>>) -> Option<i64> {
41    let slice = lex.slice();
42    let f: i64 = slice[..slice.len() - 2].parse().ok()?;
43    Some(f * 10)
44}
45
46fn integer_meter<'a>(lex: &mut Lexer<'a, Token<'a>>) -> Option<i64> {
47    let slice = lex.slice();
48    let f: i64 = slice[..slice.len() - 1].parse().ok()?;
49    Some(f * 10 * 100)
50}
51
52fn integer_second<'a>(lex: &mut Lexer<'a, Token<'a>>) -> Option<i64> {
53    let slice = lex.slice();
54    let f: i64 = slice[..slice.len() - 1].parse().ok()?;
55    Some(f * 1000)
56}
57
58fn integer_minute<'a>(lex: &mut Lexer<'a, Token<'a>>) -> Option<i64> {
59    let slice = lex.slice();
60    let len = if slice.ends_with('s') { 4 } else { 3 };
61    let f: i64 = slice[..slice.len() - len].parse().ok()?;
62    Some(f * 60 * 1000)
63}
64
65fn integer_millisec<'a>(lex: &mut Lexer<'a, Token<'a>>) -> Option<i64> {
66    let slice = lex.slice();
67    let f: i64 = slice[..slice.len() - 2].parse().ok()?;
68    Some(f)
69}
70
71fn integer_hour<'a>(lex: &mut Lexer<'a, Token<'a>>) -> Option<i64> {
72    let slice = lex.slice();
73    let len = if slice.ends_with('s') { 5 } else { 4 };
74    let f: i64 = slice[..slice.len() - len].parse().ok()?;
75    Some(f * 60 * 60 * 1000)
76}
77
78fn floating_second<'a>(lex: &mut Lexer<'a, Token<'a>>) -> Option<f64> {
79    let slice = lex.slice();
80    let f: f64 = slice[..slice.len() - 1].parse().ok()?;
81    Some(f * 1000.0)
82}
83
84fn floating_minute<'a>(lex: &mut Lexer<'a, Token<'a>>) -> Option<f64> {
85    let slice = lex.slice();
86    let len = if slice.ends_with('s') { 4 } else { 3 };
87    let f: f64 = slice[..slice.len() - len].parse().ok()?;
88    Some(f * 60.0 * 1000.0)
89}
90
91fn floating_millisec<'a>(lex: &mut Lexer<'a, Token<'a>>) -> Option<f64> {
92    let slice = lex.slice();
93    let f: f64 = slice[..slice.len() - 2].parse().ok()?;
94    Some(f)
95}
96
97fn floating_hour<'a>(lex: &mut Lexer<'a, Token<'a>>) -> Option<f64> {
98    let slice = lex.slice();
99    let len = if slice.ends_with('s') { 5 } else { 4 };
100    let f: f64 = slice[..slice.len() - len].parse().ok()?;
101    Some(f * 60.0 * 60.0 * 1000.0)
102}
103
104fn rm_first<'a>(lex: &mut Lexer<'a, Token<'a>>) -> &'a str {
105    let slice = lex.slice();
106    &slice[1..slice.len()]
107}
108
109fn rm_last<'a>(lex: &mut Lexer<'a, Token<'a>>) -> &'a str {
110    let slice = lex.slice();
111    &slice[0..slice.len() - 1]
112}
113
114fn rm_first_and_last<'a>(lex: &mut Lexer<'a, Token<'a>>) -> &'a str {
115    let slice = lex.slice();
116    &slice[1..slice.len() - 1]
117}
118
119#[derive(Debug, PartialEq, Clone, Copy)]
120pub enum SensorType {
121    Lidar,
122    Imu,
123    Odom,
124    Mixed,
125    Any,
126}
127
128impl FromStr for SensorType {
129    type Err = std::io::Error;
130
131    fn from_str(s: &str) -> Result<Self, Self::Err> {
132        Ok(match s.to_lowercase().as_str() {
133            "cloud" => Self::Lidar,
134            "imu" => Self::Imu,
135            "odom" => Self::Odom,
136            "mixed" => Self::Mixed,
137            _ => Self::Any,
138        })
139    }
140}
141
142pub const POINTCLOUD_ROS2_TYPE: &str = "sensor_msgs/msg/PointCloud2";
143pub const IMU_ROS2_TYPE: &str = "sensor_msgs/msg/Imu";
144pub const ODOM_ROS2_TYPE: &str = "nav_msgs/msg/Odometry";
145
146impl SensorType {
147    pub fn is(&self, query: &str) -> bool {
148        match self {
149            SensorType::Lidar => query == POINTCLOUD_ROS2_TYPE,
150            SensorType::Imu => query == IMU_ROS2_TYPE,
151            SensorType::Mixed => {
152                query == POINTCLOUD_ROS2_TYPE || query == IMU_ROS2_TYPE || query == ODOM_ROS2_TYPE
153            }
154            SensorType::Any => true,
155            SensorType::Odom => query == ODOM_ROS2_TYPE,
156        }
157    }
158}
159
160#[derive(Debug, PartialEq, Clone)]
161enum PlayType {
162    SensorCount {
163        sensors: Vec<String>,
164    },
165    UntilSensorCount {
166        sending: Vec<String>,
167        until_sensors: Vec<String>,
168    },
169}
170
171#[derive(Logos, Debug, PartialEq, Clone)]
172#[logos(skip r"[ \t\f]+")]
173enum Token<'a> {
174    Error,
175
176    // -- Control --
177    #[token("+")]
178    OpPlus,
179
180    #[token("-")]
181    OpMinus,
182
183    // #[token("<")]
184    // OpInclude,
185    #[regex(".", priority = 1)]
186    Dot,
187
188    #[token(",")]
189    Comma,
190
191    #[regex(r"(#.*)?\n")]
192    NewLine,
193
194    #[token("(")]
195    BracketOpen,
196
197    #[token(")")]
198    BracketClose,
199
200    #[token("{")]
201    BlockStart,
202
203    #[token("}")]
204    BlockEnd,
205
206    #[token("[")]
207    LParen,
208
209    #[token("]")]
210    RParen,
211
212    // -- Operators --
213    #[token("==")]
214    OpCompare,
215
216    #[regex("<-|=")]
217    OpAssignToLeft,
218
219    #[regex("->", priority = 1000)]
220    OpAssignToRight,
221
222    #[token("..")]
223    OpRange,
224
225    #[regex(r"\.?\/+[^ \n]*")]
226    Path(&'a str),
227
228    // Relative path or Marina namespace/name[:tag...] reference. Keeping it as
229    // one token makes reset! accept the same unquoted target users pass to the
230    // CLI while ordinary variables retain their existing grammar.
231    #[regex(r"[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.:\-]+", priority = 10)]
232    Target(&'a str),
233
234    #[regex(r#""[^"]+""#, rm_first_and_last)]
235    String(&'a str),
236
237    // #[token("::")]
238    // EnumDivider,
239
240    // -- Keywords --
241    #[token("if")]
242    KwIf,
243
244    #[token("loop")]
245    KwLoop,
246
247    #[token("LOG")]
248    KwLog,
249
250    #[token("~")]
251    DoNotCareOptim,
252
253    // -- Embedded functions (Wind) --
254    #[regex(r"pf!")]
255    FnPlayFrames,
256
257    #[token("reset!")]
258    FnReset,
259
260    #[token("rule!")]
261    FnRule,
262
263    // -- Expressions --
264    #[token("true")]
265    True,
266
267    #[token("false")]
268    False,
269
270    #[regex(r"[+-]?\d+", |lex| lex.slice().parse().ok())]
271    IntegerNumber(i64),
272
273    #[regex(r"[+-]?(\d+)?\.\d*", |lex| lex.slice().parse().ok())]
274    FloatingNumber(f64),
275
276    #[regex(r"[+-]?(\d+)?\.\d*mm", floating_millimeter)]
277    #[regex(r"[+-]?(\d+)?\.\d*m]", floating_meter)]
278    #[regex(r"[+-]?(\d+)?\.\d*cm", floating_centimeter)]
279    FloatingNumberMillimeter(f64),
280
281    #[regex(r"[+-]?(\d+)?\.\d*s]", floating_second)]
282    #[regex(r"[+-]?(\d+)?\.\d*ms]", floating_millisec)]
283    #[regex(r"[+-]?(\d+)?\.\d*mins?]", floating_minute)]
284    #[regex(r"[+-]?(\d+)?\.\d*hours?]", floating_hour)]
285    FloatingNumberMillisecond(f64),
286
287    #[regex(r"[+-]?(\d+cm)", integer_centimeter)]
288    #[regex(r"[+-]?(\d+mm)", integer_millimeter)]
289    #[regex(r"[+-]?(\d+m)", integer_meter)]
290    IntegerNumberMillimeter(i64),
291
292    #[regex(r"[+-]?(\d+s)", integer_second)]
293    #[regex(r"[+-]?(\d+ms)", integer_millisec)]
294    #[regex(r"[+-]?(\d+mins)", integer_minute)]
295    #[regex(r"[+-]?(\d+hours)", integer_hour)]
296    IntegerNumberMillisecond(i64),
297
298    #[regex(r"[a-zA-Z_:]+\d*[a-zA-Z_:\d]*\.", rm_last)]
299    VarNamespace(&'a str),
300
301    #[regex(r"[a-zA-Z_:]+\d*[a-zA-Z_:\d]*")]
302    Variable(&'a str),
303
304    #[regex(r"_[a-zA-Z_:]+\d*[a-zA-Z_:\d]*", rm_first)]
305    PredefVariable(&'a str),
306}
307
308impl fmt::Display for Token<'_> {
309    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
310        match self {
311            Self::VarNamespace(ns) => write!(f, "Namespace({:?})", ns),
312            Self::Path(path) => write!(f, "Path({:?})", path),
313            Self::Target(target) => write!(f, "Target({:?})", target),
314            Self::String(string) => write!(f, "String({:?})", string),
315            // Self::EnumDivider => write!(f, "::"),
316            Self::FnReset => write!(f, "reset()"),
317            Self::FnRule => write!(f, "rule()"),
318            Self::Comma => write!(f, ","),
319            Self::KwLog => write!(f, "LOG"),
320            Self::OpPlus => write!(f, "+"),
321            Self::Dot => write!(f, "."),
322            Self::OpMinus => write!(f, "-"),
323            Self::Error => write!(f, "<error>"),
324            Self::NewLine => write!(f, "\\n"),
325            Self::BracketOpen => write!(f, "["),
326            Self::BracketClose => write!(f, "]"),
327            Self::BlockStart => write!(f, "{{"),
328            Self::BlockEnd => write!(f, "}}"),
329            Self::LParen => write!(f, "("),
330            Self::RParen => write!(f, ")"),
331            Self::OpCompare => write!(f, "=="),
332            Self::OpAssignToLeft => write!(f, "<-"),
333            Self::OpAssignToRight => write!(f, "->"),
334            Self::OpRange => write!(f, ".."),
335            Self::KwIf => write!(f, "if"),
336            Self::KwLoop => write!(f, "loop"),
337            Self::DoNotCareOptim => write!(f, "~"),
338            Self::FnPlayFrames => write!(f, "play_frames()"),
339            Self::True => write!(f, "true"),
340            Self::False => write!(f, "false"),
341            Self::IntegerNumber(s) => write!(f, "{}", s),
342            Self::FloatingNumber(s) => write!(f, "{}", s),
343            Self::FloatingNumberMillimeter(s) => write!(f, "{}mm", s),
344            Self::FloatingNumberMillisecond(s) => write!(f, "{}ms", s),
345            Self::IntegerNumberMillimeter(s) => write!(f, "{}mm", s),
346            Self::IntegerNumberMillisecond(s) => write!(f, "{}ms", s),
347            Self::Variable(s) => write!(f, "{}", s),
348            Self::PredefVariable(s) => write!(f, "_{}", s),
349        }
350    }
351}
352
353#[derive(Debug, Clone, Copy)]
354pub enum NumVal {
355    Floating(f64),
356    Integer(i64),
357}
358
359impl PartialEq for NumVal {
360    fn eq(&self, other: &Self) -> bool {
361        let tolerance = 1e-6; // Adjust this value as needed
362        match (self, other) {
363            (NumVal::Floating(fl), NumVal::Floating(fr)) => (fl - fr).abs() < tolerance,
364            (NumVal::Floating(_), NumVal::Integer(_)) => false,
365            (NumVal::Integer(_), NumVal::Floating(_)) => false,
366            (NumVal::Integer(il), NumVal::Integer(ir)) => il == ir,
367        }
368    }
369}
370
371impl Eq for NumVal {}
372
373impl NumVal {
374    pub fn integerize_unit_val(self) -> NumVal {
375        if let NumVal::Floating(f) = self {
376            NumVal::Integer(f.round() as i64)
377        } else {
378            self
379        }
380    }
381}
382
383#[derive(Debug, Clone, Copy, PartialEq, Eq)]
384pub enum Unit {
385    TimeMilliseconds,
386    WayMillimeter,
387}
388
389#[derive(Debug, Clone, PartialEq, Eq)]
390pub enum Val {
391    UnitedVal(UnitVal),
392    NumVal(NumVal),
393    StringVal(String),
394    BoolVal(bool),
395}
396
397#[derive(Debug, Clone, Copy, PartialEq, Eq)]
398pub struct UnitVal {
399    pub val: u64,
400    pub unit: Unit,
401}
402
403#[derive(Debug, Clone, PartialEq, Eq)]
404pub enum Rhs {
405    Range { from: Option<Val>, to: Option<Val> },
406    Var(Var),
407    Path(String),
408    // Expr() TODO evaluate so in the end it becomes atomic Rhs
409    Val(Val),
410    Array(Vec<Box<Self>>),
411}
412
413#[derive(Debug, Clone, PartialEq, Eq, Hash)]
414pub enum Var {
415    Log,
416    Predef {
417        name: String,
418        namespace: Vec<String>,
419    },
420    User {
421        name: String,
422        namespace: Vec<String>,
423    },
424}
425
426fn vec_prepend<T: Clone>(prepend: &[T], source: &[T]) -> Vec<T> {
427    let mut out = prepend.to_vec();
428    out.extend(source.iter().cloned());
429    out
430}
431
432impl Var {
433    pub fn add_namespace(self, ns: &[String]) -> Self {
434        match self {
435            Var::User { name, namespace } => Var::User {
436                name,
437                namespace: vec_prepend(ns, &namespace),
438            },
439            Var::Log => Var::Log,
440            Var::Predef { name, namespace } => Var::Predef {
441                name,
442                namespace: vec_prepend(ns, &namespace),
443            },
444        }
445    }
446}
447
448impl FromStr for Var {
449    type Err = anyhow::Error;
450
451    fn from_str(s: &str) -> Result<Self, Self::Err> {
452        let splitted = s.split(".").collect::<Vec<_>>();
453
454        let l = splitted.len();
455        if l < 1 {
456            return Err(anyhow!("Nothing to parse"));
457        }
458
459        let last = splitted[l - 1];
460
461        Ok(if last == COMPARE_NODE_NAME {
462            Self::Log
463        } else {
464            let mut v: Vec<String> = vec![];
465            if l > 1 {
466                v.extend(splitted.into_iter().take(l - 1).map(String::from));
467            }
468            if let Some(predef) = last.strip_prefix("_") {
469                Self::Predef {
470                    name: predef.to_owned(),
471                    namespace: v,
472                }
473            } else {
474                Self::User {
475                    name: last.to_owned(),
476                    namespace: v,
477                }
478            }
479        })
480    }
481}
482
483#[derive(Debug)]
484pub struct Evaluated {
485    pub rules: Rules,
486    pub wind: Vec<WindFunction>,
487    pub vars: VariableHistory,
488}
489
490impl Default for Evaluated {
491    fn default() -> Self {
492        Self::new()
493    }
494}
495
496impl Evaluated {
497    pub fn new() -> Self {
498        Self {
499            rules: Rules::new(),
500            wind: vec![],
501            vars: VariableHistory::new(vec![]),
502        }
503    }
504}
505
506#[derive(Debug)]
507pub enum WindFunction {
508    Reset(String),
509    SendFrames(PlayKindUnitedPass3),
510}
511
512#[derive(Debug, Clone)]
513pub struct Root<'a> {
514    pub rules: RuleSexpr,
515    pub wind: Vec<StatementKind<'a>>,
516    pub vardefs: Vec<Statement>,
517}
518
519pub type PlayTimeMsRange = (u64, u64);
520
521#[derive(Debug, PartialEq, Clone)]
522pub enum PlayTrigger {
523    DurationMs(u64),
524    DurationRelFactor(f64),
525    Variable(String),
526}
527
528#[derive(Debug, PartialEq, Clone, Copy)]
529pub enum PlayMode {
530    Dynamic,
531    Fix,
532}
533
534#[derive(Debug, PartialEq, Clone, Copy)]
535pub enum AbsTimeRange {
536    Open,
537    UpperOpen(u64),
538    LowerOpen(u64),
539    Closed((u64, u64)),
540}
541
542#[derive(Debug, PartialEq, Clone, Copy)]
543pub enum PlayCount {
544    TimeRelativeMs(u64),
545    TimeRangeMs(AbsTimeRange),
546    Amount(u64),
547}
548
549#[derive(Debug, PartialEq, Clone)]
550pub enum SensorIdentification {
551    Topic(String),    // no type given, compare by topics
552    Type(SensorType), // type given but no topics, check for types
553    TopicAndType { topic: String, msg_type: SensorType }, // both given but only use topics for collect until because it is more fine grained
554}
555
556#[derive(Debug, PartialEq, Clone)]
557pub struct AnySensor {
558    pub name: String, // custom name given by config
559    pub id: SensorIdentification,
560    pub short: Option<String>, // to be used while parsing to not write so much
561}
562
563#[derive(Debug, PartialEq, Clone)]
564pub enum PlayKindUnited {
565    SensorCount {
566        sensors: Vec<String>,
567        count: PlayCount,
568        trigger: Option<PlayTrigger>,
569        play_mode: PlayMode,
570    },
571    UntilSensorCount {
572        sending: Vec<String>,
573        until_sensors: Vec<String>,
574        until_count: PlayCount,
575        trigger: Option<PlayTrigger>,
576        play_mode: PlayMode,
577    },
578}
579
580#[derive(Debug, PartialEq, Clone)]
581pub enum PlayKindUnitedPass3 {
582    SensorCount {
583        sensors: Vec<AnySensor>,
584        count: PlayCount,
585        trigger: Option<PlayTrigger>,
586        play_mode: PlayMode,
587    },
588    UntilSensorCount {
589        sending: Vec<AnySensor>,
590        until_sensors: Vec<AnySensor>,
591        until_count: PlayCount,
592        trigger: Option<PlayTrigger>,
593        play_mode: PlayMode,
594    },
595}
596
597#[derive(Debug, Clone)]
598pub enum StatementKind<'a> {
599    Rule(Rule<'a>),
600    VariableDef(Statement),
601    Reset(String),
602    SendFrames { kind: PlayKindUnited, at: String },
603    VariableNamespaceBlock(Vec<Statement>),
604}
605
606#[derive(Debug, Clone)]
607pub enum StatementKindPass1<'a> {
608    Rule(Rule<'a>),
609    VariableDef(Statement),
610    Reset(String),
611    Include {
612        namespace: Vec<String>,
613        path: String,
614    },
615    SendFrames(PlayKindUnited),
616    VariableNamespaceBlock {
617        ns: Vec<&'a str>,
618        stmts: Vec<Box<StatementKindPass1<'a>>>,
619    },
620    Loop {
621        count: usize,
622        stmts: Vec<Box<StatementKindPass1<'a>>>,
623    },
624}
625
626#[derive(Debug, Clone)]
627pub enum StatementKindOwnedPass1 {
628    Rule(RuleOwned),
629    Include {
630        namespace: Vec<String>,
631        path: String,
632    },
633    VariableDef(Statement),
634    VariableNamespaceBlock {
635        ns: Vec<String>,
636        stmts: Vec<Box<StatementKindOwnedPass1>>,
637    },
638    Reset(String),
639    SendFrames(PlayKindUnited),
640    Loop {
641        count: usize,
642        stmts: Vec<Box<StatementKindOwnedPass1>>,
643    },
644}
645
646#[derive(Debug, Clone)]
647pub enum StatementKindOwned {
648    Rule(RuleOwned),
649    VariableDef(Statement),
650    Reset(String),
651    SendFrames(PlayKindUnited),
652}
653
654#[derive(Debug, Clone)]
655pub enum StatementKindOwnedPass3 {
656    Rule(RuleOwned),
657    VariableDef(Statement),
658    Reset(String),
659    SendFrames(PlayKindUnitedPass3),
660}
661
662fn do_pass1(
663    pass1: Vec<StatementKindOwnedPass1>,
664    current_parent: &std::path::Path,
665) -> anyhow::Result<Vec<StatementKindOwned>> {
666    let mut out = vec![];
667
668    for stmt in pass1 {
669        match stmt {
670            StatementKindOwnedPass1::Rule(rule_owned) => {
671                out.push(StatementKindOwned::Rule(rule_owned));
672            }
673            StatementKindOwnedPass1::VariableDef(statement) => {
674                out.push(StatementKindOwned::VariableDef(statement));
675            }
676            StatementKindOwnedPass1::VariableNamespaceBlock { ns, stmts } => {
677                let v = stmts.into_iter().map(|f| *f).collect::<Vec<_>>();
678
679                let passed = do_pass1(v, current_parent)?;
680                out.extend(
681                    passed
682                        .into_iter()
683                        .map(|t| match t {
684                            StatementKindOwned::VariableDef(statement) => Ok(
685                                StatementKindOwned::VariableDef(statement.add_namespace(&ns)),
686                            ),
687                            _ => Err(anyhow!(
688                                "Only variable statements allowed inside a namespace block."
689                            )),
690                        })
691                        .try_fold(Vec::new(), |mut acc, res| match res {
692                            Ok(ok) => {
693                                acc.push(ok);
694                                Ok(acc)
695                            }
696                            Err(e) => Err(e),
697                        })?,
698                );
699            }
700            StatementKindOwnedPass1::Reset(rs) => {
701                out.push(StatementKindOwned::Reset(rs));
702            }
703            StatementKindOwnedPass1::SendFrames(kind) => {
704                out.push(StatementKindOwned::SendFrames(kind));
705            }
706            StatementKindOwnedPass1::Loop { count, stmts } => {
707                let v = stmts.into_iter().map(|f| *f).collect::<Vec<_>>();
708                let passed = do_pass1(v, current_parent)?;
709
710                // Repeat the statements `count` times
711                for _ in 0..count {
712                    out.extend(passed.clone());
713                }
714            }
715            StatementKindOwnedPass1::Include { namespace, path } => {
716                let to_parse = PathBuf::from_str(&path)?;
717                let to_parse = if to_parse.is_relative() {
718                    if to_parse.is_dir() {
719                        return Err(anyhow!("File is a directory: {}", to_parse.display()));
720                    } else {
721                        current_parent.join(path).to_owned()
722                    }
723                } else {
724                    to_parse
725                };
726                let nast = parse_to_ast(&to_parse)?;
727                let nast = ast_add_namespace(&namespace, nast);
728                out.extend(nast);
729            }
730        }
731    }
732
733    Ok(out)
734}
735
736fn parse_to_ast(path: &std::path::Path) -> anyhow::Result<Vec<StatementKindOwned>> {
737    let file = std::fs::read_to_string(path);
738    let file = match file {
739        Ok(file) => Ok(file),
740        Err(e) => match e.kind() {
741            std::io::ErrorKind::NotFound => Err(anyhow!("Could not find file: {}", path.display())),
742            std::io::ErrorKind::PermissionDenied => {
743                Err(anyhow!("No permission to read file: {}", path.display()))
744            }
745            std::io::ErrorKind::IsADirectory => {
746                Err(anyhow!("File is a directory: {}", path.display()))
747            }
748            _ => Err(anyhow!("Unexpected error for file: {}", path.display())),
749        },
750    }?;
751
752    // parse file to be included recursively
753    let token_iter = Token::lexer(&file).spanned().map(|(tok, span)| match tok {
754        Ok(tok) => (tok, span.into()),
755        Err(()) => (Token::Error, span.into()),
756    });
757    let token_stream =
758        Stream::from_iter(token_iter).map((0..file.len()).into(), |(t, s): (_, _)| (t, s));
759    match parser().parse(token_stream).into_result() {
760        Ok(sexpr) => {
761            let mut ast: Vec<StatementKindOwnedPass1> = Vec::new();
762            for expr in sexpr {
763                ast.push(expr.into());
764            }
765
766            let ast = do_pass1(
767                ast,
768                path.parent()
769                    .ok_or(anyhow!("Can not get parent directory of file."))?,
770            )?; // recursive call
771            return Ok(ast);
772        }
773        Err(errs) => {
774            for err in errs {
775                Report::build(ReportKind::Error, ((), err.span().into_range()))
776                    .with_code(3)
777                    .with_message(err.to_string())
778                    .with_label(
779                        Label::new(((), err.span().into_range()))
780                            .with_message(err.reason().to_string())
781                            .with_color(Color::Red),
782                    )
783                    .finish()
784                    .eprint(Source::from(&file))
785                    .unwrap();
786            }
787        }
788    }
789
790    Err(anyhow!("Could not parse ratslang code."))
791}
792
793impl<'a> From<StatementKindPass1<'a>> for StatementKindOwnedPass1 {
794    fn from(value: StatementKindPass1<'a>) -> Self {
795        match value {
796            StatementKindPass1::VariableNamespaceBlock { ns, stmts } => {
797                StatementKindOwnedPass1::VariableNamespaceBlock {
798                    ns: ns.into_iter().map(String::from).collect::<Vec<_>>(),
799                    stmts: stmts
800                        .into_iter()
801                        .map(|bstmt| Box::new(StatementKindOwnedPass1::from(*bstmt)))
802                        .collect::<Vec<_>>(),
803                }
804            }
805            StatementKindPass1::Rule(rule) => StatementKindOwnedPass1::Rule(RuleOwned::from(rule)),
806            StatementKindPass1::VariableDef(statement) => {
807                StatementKindOwnedPass1::VariableDef(statement)
808            }
809            StatementKindPass1::Reset(path) => StatementKindOwnedPass1::Reset(path),
810            StatementKindPass1::SendFrames(kind) => StatementKindOwnedPass1::SendFrames(kind),
811            StatementKindPass1::Include { namespace, path } => {
812                StatementKindOwnedPass1::Include { namespace, path }
813            }
814            StatementKindPass1::Loop { count, stmts } => StatementKindOwnedPass1::Loop {
815                count,
816                stmts: stmts
817                    .into_iter()
818                    .map(|bstmt| Box::new(StatementKindOwnedPass1::from(*bstmt)))
819                    .collect::<Vec<_>>(),
820            },
821        }
822    }
823}
824
825// --- Coordinator Rules ---
826#[derive(Debug, Clone)]
827pub struct RuleSexpr {
828    pub rules: Vec<RuleOwned>,
829}
830
831#[derive(Debug, Clone)]
832pub struct Rule<'a> {
833    pub variable: &'a str,
834    pub stmts: Vec<Statement>,
835}
836
837#[derive(Debug, Clone)]
838pub struct RuleOwned {
839    pub variable: String,
840    pub stmts: Vec<Statement>,
841}
842
843impl<'a> From<Rule<'a>> for RuleOwned {
844    fn from(value: Rule<'a>) -> Self {
845        Self {
846            variable: value.variable.to_owned(),
847            stmts: value.stmts,
848        }
849    }
850}
851
852#[derive(Debug, Clone)]
853pub enum StatementPass1 {
854    AssignLeft {
855        lhs: Vec<Var>,
856        rhs: Rhs,
857    },
858    AssignRight {
859        lhs: Rhs,
860        rhs: Vec<Var>,
861    },
862    Compare {
863        rhs: Vec<Var>,
864        lhs: Vec<Var>,
865    },
866    Include {
867        namespace: Vec<String>,
868        path: String,
869    },
870}
871
872#[derive(Debug, Clone)]
873pub enum Statement {
874    AssignLeft { lhs: Vec<Var>, rhs: Rhs },
875    AssignRight { lhs: Rhs, rhs: Vec<Var> },
876    Compare { rhs: Vec<Var>, lhs: Vec<Var> },
877}
878
879impl Statement {
880    fn add_namespace(self, ns: &[String]) -> Self {
881        match self {
882            Statement::AssignLeft { lhs, rhs } => {
883                let nlhs = lhs
884                    .into_iter()
885                    .map(|v| v.add_namespace(ns))
886                    .collect::<Vec<_>>();
887                Statement::AssignLeft { lhs: nlhs, rhs }
888            }
889            Statement::AssignRight { lhs, rhs } => {
890                let nrhs = rhs
891                    .into_iter()
892                    .map(|v| v.add_namespace(ns))
893                    .collect::<Vec<_>>();
894                Statement::AssignRight { lhs, rhs: nrhs }
895            }
896            Statement::Compare { rhs, lhs } => Statement::Compare { rhs, lhs },
897        }
898    }
899}
900
901fn ast_add_namespace(ns: &[String], ast: Vec<StatementKindOwned>) -> Vec<StatementKindOwned> {
902    ast.into_iter()
903        .map(|stmt| match stmt {
904            StatementKindOwned::VariableDef(statement) => {
905                StatementKindOwned::VariableDef(statement.add_namespace(ns))
906            }
907            _ => stmt,
908        })
909        .collect()
910}
911
912#[derive(Clone, Copy, Debug)]
913pub enum Operator {
914    Right,   // "->"
915    Left,    // "<-"
916    Compare, // "=="
917}
918
919fn parser<'a, I>()
920-> impl Parser<'a, I, Vec<StatementKindPass1<'a>>, extra::Err<Rich<'a, Token<'a>>>>
921where
922    I: ValueInput<'a, Token = Token<'a>, Span = SimpleSpan>,
923{
924    let time = select! {
925        Token::IntegerNumberMillisecond(ms) => NumVal::Integer(ms),
926        Token::FloatingNumberMillisecond(ms) => NumVal::Floating(ms).integerize_unit_val(),
927    }
928    .labelled("time");
929
930    let way = select! {
931        Token::IntegerNumberMillimeter(millis) => NumVal::Integer(millis),
932        Token::FloatingNumberMillimeter(millis) => NumVal::Floating(millis).integerize_unit_val(),
933    }
934    .labelled("way");
935
936    let timerange = time
937        .or_not()
938        .then_ignore(just(Token::OpRange))
939        .then(time)
940        .try_map(|(from, to), span| {
941            Ok(Rhs::Range {
942                from: {
943                    if let Some(from) = from {
944                        Some(Val::UnitedVal(UnitVal {
945                            val: {
946                                match from {
947                                    NumVal::Floating(_) => unreachable!("integerised before"),
948                                    NumVal::Integer(i) => {
949                                        if i < 0 {
950                                            return Err(Rich::custom(
951                                                span,
952                                                "Negative Integer Number for Timespan.",
953                                            ));
954                                        } else {
955                                            i as u64
956                                        }
957                                    }
958                                }
959                            },
960                            unit: Unit::TimeMilliseconds,
961                        }))
962                    } else {
963                        None
964                    }
965                },
966                to: Some(Val::UnitedVal(UnitVal {
967                    val: match to {
968                        NumVal::Floating(_) => unreachable!("integerised before"),
969                        NumVal::Integer(i) => {
970                            if i < 0 {
971                                return Err(Rich::custom(
972                                    span,
973                                    "Negative Integer Number for Timespan.",
974                                ));
975                            } else {
976                                i as u64
977                            }
978                        }
979                    },
980                    unit: Unit::TimeMilliseconds,
981                })),
982            })
983        })
984        .labelled("time range");
985
986    let timerange_open_upper = time
987        .then_ignore(just(Token::OpRange))
988        .then_ignore(time.not())
989        .try_map(|from, span| {
990            Ok(Rhs::Range {
991                from: Some(Val::UnitedVal(UnitVal {
992                    val: match from {
993                        NumVal::Floating(_) => unreachable!("integerised before"),
994                        NumVal::Integer(i) => {
995                            if i < 0 {
996                                return Err(Rich::custom(
997                                    span,
998                                    "Negative Integer Number for Timespan.",
999                                ));
1000                            } else {
1001                                i as u64
1002                            }
1003                        }
1004                    },
1005                    unit: Unit::TimeMilliseconds,
1006                })),
1007                to: None,
1008            })
1009        })
1010        .labelled("upper open time range");
1011
1012    let timerange_open = time
1013        .not()
1014        .then_ignore(just(Token::OpRange))
1015        .then_ignore(time.not())
1016        .map(|_| Rhs::Range {
1017            from: None,
1018            to: None,
1019        })
1020        .labelled("open not-time range");
1021
1022    let wayrange = way
1023        .then_ignore(just(Token::OpRange))
1024        .then(way)
1025        .try_map(|(from, to), span| {
1026            Ok(Rhs::Range {
1027                from: Some(Val::UnitedVal(UnitVal {
1028                    val: match from {
1029                        NumVal::Floating(_) => unreachable!("integerised before"),
1030                        NumVal::Integer(i) => {
1031                            if i < 0 {
1032                                return Err(Rich::custom(
1033                                    span,
1034                                    "Negative Integer Number for Wayspan.",
1035                                ));
1036                            } else {
1037                                i as u64
1038                            }
1039                        }
1040                    },
1041                    unit: Unit::WayMillimeter,
1042                })),
1043                to: Some(Val::UnitedVal(UnitVal {
1044                    val: match to {
1045                        NumVal::Floating(_) => unreachable!("integerised before"),
1046                        NumVal::Integer(i) => {
1047                            if i < 0 {
1048                                return Err(Rich::custom(
1049                                    span,
1050                                    "Negative Integer Number for Wayspan.",
1051                                ));
1052                            } else {
1053                                i as u64
1054                            }
1055                        }
1056                    },
1057                    unit: Unit::WayMillimeter,
1058                })),
1059            })
1060        })
1061        .labelled("way range");
1062
1063    let numvalue = select! {
1064            Token::IntegerNumber(i) => Rhs::Val(Val::NumVal(NumVal::Integer(i))),
1065            Token::FloatingNumber(f) => Rhs::Val(Val::NumVal(NumVal::Floating(f))),
1066    }
1067    .labelled("number value");
1068
1069    let value = select! {
1070            Token::IntegerNumber(i) => Rhs::Val(Val::NumVal(NumVal::Integer(i))),
1071            Token::FloatingNumber(f) => Rhs::Val(Val::NumVal(NumVal::Floating(f))),
1072            Token::String(s) => Rhs::Val(Val::StringVal(s.to_owned())),
1073            Token::True => Rhs::Val(Val::BoolVal(true)),
1074            Token::False => Rhs::Val(Val::BoolVal(false)),
1075    }
1076    .labelled("value");
1077
1078    let numberrange = numvalue
1079        .then_ignore(just(Token::OpRange))
1080        .then(value)
1081        .try_map(|(from, to), span| match (&from, &to) {
1082            (
1083                Rhs::Val(Val::NumVal(NumVal::Floating(_))),
1084                Rhs::Val(Val::NumVal(NumVal::Integer(_))),
1085            )
1086            | (
1087                Rhs::Val(Val::NumVal(NumVal::Integer(_))),
1088                Rhs::Val(Val::NumVal(NumVal::Floating(_))),
1089            ) => Err(Rich::custom(span, "Cannot span between float and integer.")),
1090            (_, _) => Ok((from, to)),
1091        })
1092        .map(|(from, to)| {
1093            let from = match from {
1094                Rhs::Val(Val::NumVal(nv)) => nv,
1095                _ => unreachable!(),
1096            };
1097            let to = match to {
1098                Rhs::Val(Val::NumVal(nv)) => nv,
1099                _ => unreachable!(),
1100            };
1101
1102            Rhs::Range {
1103                from: Some(Val::NumVal(from)),
1104                to: Some(Val::NumVal(to)),
1105            }
1106        })
1107        .labelled("number range");
1108
1109    let variable = select! {
1110            Token::VarNamespace(ns) => ns.to_owned(),
1111        }
1112        .repeated()
1113        .collect::<Vec<_>>()
1114        .then(select! {
1115                Token::Variable(var) => Rhs::Var(Var::User { name: var.to_owned(), namespace: vec![] }),
1116                Token::PredefVariable(var) => Rhs::Var(Var::Predef { name: var.to_owned(), namespace: vec![] }),
1117            })
1118        .map(|(ns, var)| {
1119                let var = match var {
1120                    Rhs::Var(var) => match var {
1121                        Var::User { name, namespace: _} => {
1122                            Var::User { name, namespace: ns }
1123                        },
1124                        Var::Predef { name, namespace: _ } => {
1125                            Var::Predef { name, namespace: ns }
1126                        },
1127                        _ => unreachable!(),
1128                    },
1129                    _ => unreachable!(),
1130                };
1131
1132                Rhs::Var(var)
1133            });
1134
1135    let term = select! {
1136        Token::KwLog => Rhs::Var(Var::Log), // TODO maybe not rhs that can be assigned
1137        Token::Path(p) => Rhs::Path(p.to_owned()),
1138    }
1139    .or(variable)
1140    .labelled("term");
1141
1142    let range = choice((numberrange, timerange.clone(), wayrange)).boxed();
1143
1144    let rhs_array = recursive(|rhs_array| {
1145        choice((term, range.clone(), value, rhs_array))
1146            .separated_by(just(Token::Comma).then_ignore(just(Token::NewLine).repeated()))
1147            .at_least(1)
1148            .collect::<Vec<_>>()
1149            .delimited_by(just(Token::LParen), just(Token::RParen))
1150            .map(|arr: Vec<Rhs>| Rhs::Array(arr.into_iter().map(Box::new).collect::<Vec<_>>()))
1151    })
1152    .boxed();
1153
1154    let rhs = choice((term, range, value, rhs_array)).boxed();
1155
1156    // parse a comma-separated list of terms (the left-hand side).
1157    let comma = just(Token::Comma).then_ignore(just(Token::NewLine).repeated());
1158    let multi_rhs = rhs
1159        .clone()
1160        .separated_by(comma)
1161        .at_least(1)
1162        .collect::<Vec<_>>()
1163        .labelled("rule term")
1164        .boxed();
1165
1166    let op = select! {
1167        Token::OpAssignToRight => Operator::Right,
1168        Token::OpAssignToLeft => Operator::Left,
1169        Token::OpCompare => Operator::Compare,
1170    }
1171    .labelled("operator");
1172
1173    // a statement is: lhs, then an operator, then a single term (the right-hand side).
1174    let statement = multi_rhs
1175        .clone()
1176        .then(op)
1177        .then(multi_rhs)
1178        .then_ignore(just(Token::NewLine).repeated())
1179        .try_map(|((lhs, op), rhs), span| {
1180            Ok(StatementKindPass1::VariableDef(match op {
1181                Operator::Right => {
1182                    if lhs.len() > 1 {
1183                        return Err(Rich::custom(
1184                            span,
1185                            "Can only assign one term but to multiple variables.",
1186                        ));
1187                    }
1188                    if let Some(lhs) = lhs.first() {
1189                        let mut vars: Vec<Var> = Vec::new();
1190                        for r in rhs.iter() {
1191                            match r {
1192                                Rhs::Var(var) => {
1193                                    vars.push(var.clone());
1194                                }
1195                                _ => {
1196                                    return Err(Rich::custom(
1197                                        span,
1198                                        "Can only assign to variables.",
1199                                    ));
1200                                }
1201                            }
1202                        }
1203
1204                        Statement::AssignRight {
1205                            lhs: lhs.clone(),
1206                            rhs: vars,
1207                        }
1208                    } else {
1209                        return Err(Rich::custom(span, "Missing left operand."));
1210                    }
1211                }
1212                Operator::Left => {
1213                    if rhs.len() > 1 {
1214                        return Err(Rich::custom(
1215                            span,
1216                            "Can only assign one term but to multiple variables.",
1217                        ));
1218                    }
1219                    if let Some(rhs) = rhs.first() {
1220                        let mut vars: Vec<Var> = Vec::new();
1221                        for l in lhs.iter() {
1222                            match l {
1223                                Rhs::Var(var) => {
1224                                    vars.push(var.clone());
1225                                }
1226                                _ => {
1227                                    return Err(Rich::custom(
1228                                        span,
1229                                        "Can only assign to variables.",
1230                                    ));
1231                                }
1232                            }
1233                        }
1234
1235                        Statement::AssignLeft {
1236                            lhs: vars,
1237                            rhs: rhs.clone(),
1238                        }
1239                    } else {
1240                        return Err(Rich::custom(span, "Missing right operand."));
1241                    }
1242                }
1243                Operator::Compare => {
1244                    let mut lvars: Vec<Var> = Vec::new();
1245                    for l in lhs.iter() {
1246                        match l {
1247                            Rhs::Var(var) => {
1248                                lvars.push(var.clone());
1249                            }
1250                            _ => {
1251                                return Err(Rich::custom(span, "Can only compare variables."));
1252                            }
1253                        }
1254                    }
1255                    let mut rvars: Vec<Var> = Vec::new();
1256                    for r in rhs.iter() {
1257                        match r {
1258                            Rhs::Var(var) => {
1259                                rvars.push(var.clone());
1260                            }
1261                            _ => {
1262                                return Err(Rich::custom(span, "Can only compare variables."));
1263                            }
1264                        }
1265                    }
1266
1267                    Statement::Compare {
1268                        rhs: rvars,
1269                        lhs: lvars,
1270                    }
1271                }
1272            }))
1273        })
1274        .labelled("statement")
1275        .boxed();
1276
1277    let rule_header = just(Token::FnRule)
1278        .ignore_then(just(Token::BracketOpen))
1279        .ignore_then(select! { Token::Variable(v) => v }.labelled("rule name"))
1280        .then_ignore(just(Token::NewLine).or_not())
1281        .labelled("rule header");
1282
1283    let rule = rule_header
1284        .then_ignore(just(Token::NewLine).repeated())
1285        .then(statement.clone().repeated().collect())
1286        .then_ignore(just(Token::NewLine).repeated())
1287        .then_ignore(just(Token::BracketClose))
1288        .map(|(variable, stmts): (&str, Vec<StatementKindPass1>)| {
1289            let stmts = stmts
1290                .into_iter()
1291                .map(|stmtk| match stmtk {
1292                    StatementKindPass1::VariableDef(var) => var,
1293                    _ => unreachable!(),
1294                })
1295                .collect::<Vec<_>>();
1296            StatementKindPass1::Rule(Rule { variable, stmts })
1297        })
1298        .labelled("rule")
1299        .boxed();
1300
1301    let wind_reset_fn = just(Token::FnReset)
1302        .ignore_then(
1303            select! {
1304                Token::Path(p) => p, // prefixed with /, resolve
1305                Token::Target(t) => t,
1306                Token::Variable(v) =>  v, // not prefixed, so implicit ./
1307                Token::String(s) => s, // exact local path or Marina dataset reference
1308            }
1309            .labelled("bagfile"),
1310        )
1311        .map(|expr| StatementKindPass1::Reset(expr.to_owned()))
1312        .labelled("reset")
1313        .boxed();
1314
1315    let str_only = select! {
1316            Token::String(s) => s.to_owned(),
1317    }
1318    .or(variable.try_map(|v, span| match v {
1319        Rhs::Var(Var::User {
1320            name,
1321            namespace: ns,
1322        }) => {
1323            if !ns.is_empty() {
1324                return Err(Rich::custom(span, "Found namespace in implicit string."));
1325            }
1326            Ok(name)
1327        }
1328        _ => Err(Rich::custom(span, "Expected implicit string.")),
1329    }))
1330    .boxed();
1331    let str_array = str_only
1332        .clone()
1333        .separated_by(just(Token::Comma).then_ignore(just(Token::NewLine).repeated()))
1334        .at_least(1)
1335        .collect::<Vec<_>>()
1336        .delimited_by(just(Token::LParen), just(Token::RParen))
1337        .boxed();
1338
1339    let str_only_as_vec = str_only.map(|single| vec![single]).labelled("string");
1340    let one_or_more_str = choice((str_only_as_vec, str_array))
1341        .labelled("at least one string")
1342        .boxed();
1343    let playfn_with_conditions = just(Token::FnPlayFrames)
1344        .labelled("play_frames")
1345        .ignore_then(one_or_more_str.clone())
1346        .then((just(Token::Comma).ignore_then(one_or_more_str)).or_not())
1347        .map(
1348            |(play_sensors, stop_sensors): (Vec<String>, Option<Vec<String>>)| match stop_sensors {
1349                Some(stop_sensors) => PlayType::UntilSensorCount {
1350                    sending: play_sensors
1351                        .into_iter()
1352                        .map(|el| el.to_owned())
1353                        .collect::<Vec<_>>(),
1354                    until_sensors: stop_sensors
1355                        .into_iter()
1356                        .map(|el| el.to_owned())
1357                        .collect::<Vec<_>>(),
1358                },
1359                None => PlayType::SensorCount {
1360                    sensors: play_sensors
1361                        .into_iter()
1362                        .map(|el| el.to_owned())
1363                        .collect::<Vec<_>>(),
1364                },
1365            },
1366        )
1367        .boxed();
1368
1369    let wind_play_frames_fn = playfn_with_conditions
1370        .boxed()
1371        .then(
1372            choice((
1373                timerange_open,
1374                timerange_open_upper,
1375                timerange.clone(),
1376                time.map(|t| {
1377                    Rhs::Val(Val::UnitedVal(UnitVal {
1378                        val: match t {
1379                            NumVal::Integer(i) => i as u64,
1380                            _ => unreachable!(),
1381                        },
1382                        unit: Unit::TimeMilliseconds,
1383                    }))
1384                }),
1385                select! {
1386                    Token::IntegerNumber(i) => Rhs::Val(Val::NumVal(NumVal::Integer(i))), // (until) number of frames
1387                },
1388            ))
1389            .labelled("int number for count, relative time from now or absolute timespan")
1390            .boxed(),
1391        )
1392        .then(
1393            choice((
1394                variable.try_map(|v, span| match v {
1395                    Rhs::Var(var) => match var {
1396                        Var::Log => Err(Rich::custom(span, "Can not trigger on Log.")),
1397                        Var::Predef {
1398                            name: _,
1399                            namespace: _,
1400                        } => Err(Rich::custom(
1401                            span,
1402                            "Did not expect a predef variable as a variable name.",
1403                        )),
1404                        Var::User { name, namespace } => {
1405                            if !namespace.is_empty() {
1406                                return Err(Rich::custom(
1407                                    span,
1408                                    "Rat names should not have a namespace.",
1409                                )); // TODO needs fix when using topics with namespaces
1410                            }
1411
1412                            Ok(Rhs::Var(Var::User {
1413                                name,
1414                                namespace: vec![],
1415                            }))
1416                        }
1417                    },
1418                    _ => unreachable!(),
1419                }),
1420                time.map(|t| {
1421                    Rhs::Val(Val::UnitedVal(UnitVal {
1422                        val: match t {
1423                            NumVal::Integer(i) => i as u64,
1424                            _ => unreachable!(),
1425                        },
1426                        unit: Unit::TimeMilliseconds,
1427                    }))
1428                }),
1429                select! {
1430                    Token::FloatingNumber(f) => Rhs::Val(Val::NumVal(NumVal::Floating(f))),
1431                },
1432            ))
1433            .boxed()
1434            .or_not()
1435            .labelled("trigger"),
1436        )
1437        .then(
1438            variable
1439                .try_map(|v, span| {
1440                    let errmsg = "Only f or d allowed. f for fixed, d for dynamic.";
1441                    match v {
1442                        Rhs::Var(var) => match var {
1443                            Var::Log => Err(Rich::custom(span, errmsg)),
1444                            Var::Predef { name, namespace } => {
1445                                if !namespace.is_empty() {
1446                                    Err(Rich::custom(span, errmsg))
1447                                } else {
1448                                    if name.as_str() != "f" && name.as_str() != "d" {
1449                                        return Err(Rich::custom(span, errmsg));
1450                                    }
1451
1452                                    Ok(name)
1453                                }
1454                            }
1455                            Var::User { name, namespace } => {
1456                                if !namespace.is_empty() {
1457                                    Err(Rich::custom(span, errmsg))
1458                                } else {
1459                                    if name.as_str() != "f" && name.as_str() != "d" {
1460                                        return Err(Rich::custom(span, errmsg));
1461                                    }
1462
1463                                    Ok(name)
1464                                }
1465                            }
1466                        },
1467                        _ => unreachable!(),
1468                    }
1469                })
1470                .labelled("play mode [f|d]. f = fixed, d = dynamic")
1471                .or_not(),
1472        )
1473        .map(
1474            #[allow(clippy::type_complexity)]
1475            |(((pt, arg), trigger), mode): (((PlayType, Rhs), Option<Rhs>), Option<String>)| {
1476                let trigger = trigger.map(|trigger| match trigger {
1477                    Rhs::Val(Val::UnitedVal(UnitVal {
1478                        val,
1479                        unit: Unit::TimeMilliseconds,
1480                    })) => PlayTrigger::DurationMs(val),
1481                    Rhs::Var(Var::User { name, namespace: _ }) => PlayTrigger::Variable(name),
1482                    Rhs::Val(Val::NumVal(NumVal::Floating(f))) => PlayTrigger::DurationRelFactor(f),
1483                    _ => unreachable!(),
1484                });
1485
1486                let play_mode = mode.map(|mode| match mode.as_str() {
1487                    "f" => PlayMode::Fix,
1488                    "d" => PlayMode::Dynamic,
1489                    _ => unreachable!(),
1490                });
1491                let default_play_mode = match trigger.as_ref() {
1492                    Some(PlayTrigger::Variable(_)) => PlayMode::Dynamic,
1493                    _ => PlayMode::Fix,
1494                };
1495                let play_mode = play_mode.unwrap_or(default_play_mode);
1496
1497                let pku = match pt {
1498                    PlayType::SensorCount { sensors } => match arg {
1499                        Rhs::Range {
1500                            from:
1501                                Some(Val::UnitedVal(UnitVal {
1502                                    val: from_val,
1503                                    unit: Unit::TimeMilliseconds,
1504                                })),
1505                            to:
1506                                Some(Val::UnitedVal(UnitVal {
1507                                    val: to_val,
1508                                    unit: Unit::TimeMilliseconds,
1509                                })),
1510                        } => PlayKindUnited::SensorCount {
1511                            sensors,
1512                            count: PlayCount::TimeRangeMs(AbsTimeRange::Closed((from_val, to_val))),
1513                            trigger,
1514                            play_mode,
1515                        },
1516                        Rhs::Range {
1517                            from: None,
1518                            to:
1519                                Some(Val::UnitedVal(UnitVal {
1520                                    val: to_val,
1521                                    unit: Unit::TimeMilliseconds,
1522                                })),
1523                        } => PlayKindUnited::SensorCount {
1524                            sensors,
1525                            count: PlayCount::TimeRangeMs(AbsTimeRange::LowerOpen(to_val)),
1526                            trigger,
1527                            play_mode,
1528                        },
1529                        Rhs::Range {
1530                            from:
1531                                Some(Val::UnitedVal(UnitVal {
1532                                    val: from_val,
1533                                    unit: Unit::TimeMilliseconds,
1534                                })),
1535                            to: None,
1536                        } => PlayKindUnited::SensorCount {
1537                            sensors,
1538                            count: PlayCount::TimeRangeMs(AbsTimeRange::UpperOpen(from_val)),
1539                            trigger,
1540                            play_mode,
1541                        },
1542                        Rhs::Range {
1543                            from: None,
1544                            to: None,
1545                        } => PlayKindUnited::SensorCount {
1546                            sensors,
1547                            count: PlayCount::TimeRangeMs(AbsTimeRange::Open),
1548                            trigger,
1549                            play_mode,
1550                        },
1551                        Rhs::Val(Val::NumVal(NumVal::Integer(i))) => PlayKindUnited::SensorCount {
1552                            sensors,
1553                            count: PlayCount::Amount(i as u64),
1554                            trigger,
1555                            play_mode,
1556                        },
1557                        Rhs::Val(Val::UnitedVal(UnitVal {
1558                            val: ms,
1559                            unit: Unit::TimeMilliseconds,
1560                        })) => PlayKindUnited::SensorCount {
1561                            sensors,
1562                            count: PlayCount::TimeRelativeMs(ms),
1563                            trigger,
1564                            play_mode,
1565                        },
1566                        _ => {
1567                            unreachable!()
1568                        }
1569                    },
1570                    PlayType::UntilSensorCount {
1571                        sending,
1572                        until_sensors,
1573                    } => match arg {
1574                        Rhs::Range {
1575                            from:
1576                                Some(Val::UnitedVal(UnitVal {
1577                                    val: from_val,
1578                                    unit: Unit::TimeMilliseconds,
1579                                })),
1580                            to:
1581                                Some(Val::UnitedVal(UnitVal {
1582                                    val: to_val,
1583                                    unit: Unit::TimeMilliseconds,
1584                                })),
1585                        } => PlayKindUnited::UntilSensorCount {
1586                            sending,
1587                            until_sensors,
1588                            until_count: PlayCount::TimeRangeMs(AbsTimeRange::Closed((
1589                                from_val, to_val,
1590                            ))),
1591                            trigger,
1592                            play_mode,
1593                        },
1594                        Rhs::Range {
1595                            from: None,
1596                            to:
1597                                Some(Val::UnitedVal(UnitVal {
1598                                    val: to_val,
1599                                    unit: Unit::TimeMilliseconds,
1600                                })),
1601                        } => PlayKindUnited::UntilSensorCount {
1602                            sending,
1603                            until_sensors,
1604                            until_count: PlayCount::TimeRangeMs(AbsTimeRange::LowerOpen(to_val)),
1605                            trigger,
1606                            play_mode,
1607                        },
1608                        Rhs::Range {
1609                            from:
1610                                Some(Val::UnitedVal(UnitVal {
1611                                    val: from_val,
1612                                    unit: Unit::TimeMilliseconds,
1613                                })),
1614                            to: None,
1615                        } => PlayKindUnited::UntilSensorCount {
1616                            sending,
1617                            until_sensors,
1618                            until_count: PlayCount::TimeRangeMs(AbsTimeRange::UpperOpen(from_val)),
1619                            trigger,
1620                            play_mode,
1621                        },
1622                        Rhs::Val(Val::NumVal(NumVal::Integer(i))) => {
1623                            PlayKindUnited::UntilSensorCount {
1624                                sending,
1625                                until_sensors,
1626                                until_count: PlayCount::Amount(i as u64),
1627                                trigger,
1628                                play_mode,
1629                            }
1630                        }
1631                        Rhs::Val(Val::UnitedVal(UnitVal {
1632                            val: ms,
1633                            unit: Unit::TimeMilliseconds,
1634                        })) => PlayKindUnited::UntilSensorCount {
1635                            sending,
1636                            until_sensors,
1637                            until_count: PlayCount::TimeRelativeMs(ms),
1638                            trigger,
1639                            play_mode,
1640                        },
1641                        _ => {
1642                            unreachable!()
1643                        }
1644                    },
1645                };
1646
1647                StatementKindPass1::SendFrames(pku)
1648            },
1649        )
1650        .labelled("play_frames")
1651        .boxed();
1652
1653    let include = just(Token::OpAssignToLeft)
1654        .ignore_then(select! {
1655            Token::Path(p) => p.to_owned(),
1656        })
1657        .then_ignore(just(Token::NewLine))
1658        .map(|path| StatementKindPass1::Include {
1659            namespace: vec![],
1660            path,
1661        })
1662        .boxed();
1663
1664    let namespace_block = recursive(|nsb| {
1665        select! {
1666            Token::VarNamespace(ns) => ns,
1667        }
1668        .repeated()
1669        .at_least(1)
1670        .collect()
1671        .then(
1672            choice((statement.clone(), include.clone(), nsb))
1673                .repeated()
1674                .collect::<Vec<_>>()
1675                .delimited_by(
1676                    just(Token::BlockStart).then_ignore(just(Token::NewLine).repeated()),
1677                    just(Token::BlockEnd).then_ignore(just(Token::NewLine).repeated()),
1678                ),
1679        )
1680        .map(|(ns, stmts): (Vec<&'_ str>, Vec<StatementKindPass1>)| {
1681            StatementKindPass1::VariableNamespaceBlock {
1682                ns,
1683                stmts: stmts.into_iter().map(Box::new).collect::<Vec<_>>(),
1684            }
1685        })
1686    })
1687    .boxed();
1688
1689    let loop_stmt = recursive(|loop_stmt_rec| {
1690        just(Token::KwLoop)
1691            .ignore_then(select! {
1692                Token::IntegerNumber(n) => n as usize,
1693            })
1694            .then(
1695                choice((
1696                    statement.clone(),
1697                    wind_play_frames_fn.clone(),
1698                    wind_reset_fn.clone(),
1699                    rule.clone(),
1700                    namespace_block.clone(),
1701                    include.clone(),
1702                    loop_stmt_rec,
1703                ))
1704                .then_ignore(just(Token::NewLine).repeated())
1705                .repeated()
1706                .collect::<Vec<_>>()
1707                .delimited_by(
1708                    just(Token::BlockStart).then_ignore(just(Token::NewLine).repeated()),
1709                    just(Token::BlockEnd).then_ignore(just(Token::NewLine).repeated()),
1710                ),
1711            )
1712            .map(
1713                |(count, stmts): (usize, Vec<StatementKindPass1>)| StatementKindPass1::Loop {
1714                    count,
1715                    stmts: stmts.into_iter().map(Box::new).collect::<Vec<_>>(),
1716                },
1717            )
1718    })
1719    .boxed();
1720
1721    let one_of_wind_fns = choice((
1722        statement,
1723        wind_play_frames_fn,
1724        wind_reset_fn,
1725        rule,
1726        namespace_block,
1727        loop_stmt,
1728        include,
1729    ))
1730    .boxed();
1731    let newlines = just(Token::NewLine).repeated();
1732
1733    newlines
1734        .clone()
1735        .ignore_then((one_of_wind_fns.then_ignore(newlines)).repeated().collect())
1736        .then_ignore(end())
1737}
1738
1739impl RuleSexpr {
1740    fn eval(&self) -> anyhow::Result<Rules> {
1741        let mut rules = Rules::new();
1742        for rule in self.rules.iter() {
1743            for stmt in rule.stmts.iter() {
1744                match &stmt {
1745                    Statement::AssignLeft { lhs, rhs } => {
1746                        let plan = ActionPlan::Shoot {
1747                            target: lhs
1748                                .iter()
1749                                .map(|part| match part {
1750                                    Var::User { name, namespace: _ } => name.clone(),
1751                                    Var::Log => COMPARE_NODE_NAME.to_owned(),
1752                                    Var::Predef {
1753                                        name: _,
1754                                        namespace: _,
1755                                    } => unreachable!(),
1756                                })
1757                                .collect(),
1758                            id: rules.new_id(),
1759                        };
1760
1761                        let ship = match rhs {
1762                            Rhs::Var(var) => match var {
1763                                Var::User { name, namespace: _ } => name.clone(),
1764                                Var::Log => COMPARE_NODE_NAME.to_owned(),
1765                                Var::Predef {
1766                                    name: _,
1767                                    namespace: _,
1768                                } => unreachable!(),
1769                            },
1770                            _ => continue,
1771                        };
1772                        let varh = VariableHuman {
1773                            ship,
1774                            strategy: Some(plan.clone()),
1775                        };
1776                        rules.insert(rule.variable.to_owned(), vec![varh]);
1777                    }
1778                    Statement::AssignRight { lhs, rhs } => {
1779                        let plan = ActionPlan::Shoot {
1780                            target: rhs
1781                                .iter()
1782                                .map(|part| match part {
1783                                    Var::User { name, namespace: _ } => name.clone(),
1784                                    Var::Log => COMPARE_NODE_NAME.to_owned(),
1785                                    Var::Predef {
1786                                        name: _,
1787                                        namespace: _,
1788                                    } => unreachable!(),
1789                                })
1790                                .collect(),
1791                            id: rules.new_id(),
1792                        };
1793
1794                        let ship = match lhs {
1795                            Rhs::Var(var) => match var {
1796                                Var::User { name, namespace: _ } => name.clone(),
1797                                Var::Log => COMPARE_NODE_NAME.to_owned(),
1798                                Var::Predef {
1799                                    name: _,
1800                                    namespace: _,
1801                                } => unreachable!(),
1802                            },
1803                            _ => continue,
1804                        };
1805                        let varh = VariableHuman {
1806                            ship,
1807                            strategy: Some(plan.clone()),
1808                        };
1809                        rules.insert(rule.variable.to_owned(), vec![varh]);
1810                    }
1811                    Statement::Compare { rhs, lhs } => {
1812                        let plan = ActionPlan::Shoot {
1813                            target: vec![COMPARE_NODE_NAME.to_owned()],
1814                            id: rules.new_id(),
1815                        };
1816
1817                        let mut merged: Vec<String> = rhs
1818                            .iter()
1819                            .map(|var| match var {
1820                                Var::User { name, namespace: _ } => name.clone(),
1821                                Var::Log => COMPARE_NODE_NAME.to_owned(),
1822                                _ => unreachable!(),
1823                            })
1824                            .collect();
1825
1826                        merged.extend(lhs.iter().map(|var| match var {
1827                            Var::User { name, namespace: _ } => name.clone(),
1828                            Var::Log => COMPARE_NODE_NAME.to_owned(),
1829                            _ => unreachable!(),
1830                        }));
1831
1832                        merged.iter().for_each(|ex| {
1833                            let varh = VariableHuman {
1834                                ship: ex.clone(),
1835                                strategy: Some(plan.clone()),
1836                            };
1837                            rules.insert(rule.variable.to_owned(), vec![varh]);
1838                        });
1839                    }
1840                };
1841            }
1842        }
1843        Ok(rules)
1844    }
1845}
1846
1847pub fn compile_file(
1848    path: &std::path::Path,
1849    start_line: Option<usize>,
1850    end_line: Option<usize>,
1851) -> anyhow::Result<Evaluated> {
1852    compile_file_with_state(path, start_line, end_line, None, std::io::stderr(), true)
1853}
1854
1855pub fn compile_file_with_state(
1856    path: &std::path::Path,
1857    start_line: Option<usize>,
1858    end_line: Option<usize>,
1859    var_state: Option<HashMap<Var, Rhs>>,
1860    out: impl std::io::Write,
1861    rich_out: bool,
1862) -> anyhow::Result<Evaluated> {
1863    let file = std::fs::read_to_string(path);
1864    let file = match file {
1865        Ok(file) => Ok(file),
1866        Err(e) => match e.kind() {
1867            std::io::ErrorKind::NotFound => Err(anyhow!("Could not find file: {}", path.display())),
1868            std::io::ErrorKind::PermissionDenied => {
1869                Err(anyhow!("No permission to read file: {}", path.display()))
1870            }
1871            std::io::ErrorKind::IsADirectory => {
1872                Err(anyhow!("File is a directory: {}", path.display()))
1873            }
1874            _ => Err(anyhow!("Unexpected error for file: {}", path.display())),
1875        },
1876    }?;
1877    let start_line = start_line.map(|l| l.saturating_sub(1)).unwrap_or_default();
1878    let lines = file.lines();
1879    let end_line = end_line.unwrap_or(lines.clone().count()).saturating_sub(1);
1880    let selected_lines = lines
1881        .skip(start_line)
1882        .take(end_line + 1 - start_line)
1883        .collect::<Vec<_>>()
1884        .join("\n")
1885        + "\n"; // append newline as funny hack to fix one-line problems
1886
1887    let dir = path.parent().ok_or(anyhow!(
1888        "Could not get parent directory of source code file."
1889    ))?;
1890    compile_code_with_state(&selected_lines, dir, var_state, out, rich_out)
1891}
1892
1893#[derive(Debug)]
1894pub struct VariableHistory {
1895    ast: Vec<StatementKindOwned>,
1896    pub var_cache: HashMap<Var, Rhs>,
1897}
1898
1899fn is_sub_namespace(sub: &[String], super_namespace: &[String]) -> bool {
1900    if sub.len() > super_namespace.len() {
1901        return false;
1902    }
1903
1904    if sub.is_empty() {
1905        return false; // Empty is not a sub-namespace
1906    }
1907
1908    if super_namespace.is_empty() {
1909        return false;
1910    }
1911
1912    for i in 0..sub.len() {
1913        if sub[i] != super_namespace[i] {
1914            return false;
1915        }
1916    }
1917
1918    true
1919}
1920
1921fn remove_prefix_from_target(prefix_definer: &[String], target: &[String]) -> Vec<String> {
1922    let prefix_len = prefix_definer.len();
1923    let target_len = target.len();
1924    let compare_len = std::cmp::min(prefix_len, target_len);
1925
1926    let mut common_prefix_len = 0;
1927    for i in 0..compare_len {
1928        if prefix_definer[i] == target[i] {
1929            common_prefix_len += 1;
1930        } else {
1931            break;
1932        }
1933    }
1934
1935    target[common_prefix_len..].to_vec()
1936}
1937
1938fn truncate_namespace_var(ns: &[String], var: &Var) -> Var {
1939    match var {
1940        Var::User { name, namespace } => Var::User {
1941            name: name.clone(),
1942            namespace: { remove_prefix_from_target(ns, namespace) },
1943        },
1944        Var::Log => Var::Log,
1945        Var::Predef { name, namespace } => Var::Predef {
1946            name: name.clone(),
1947            namespace: { remove_prefix_from_target(ns, namespace) },
1948        },
1949    }
1950}
1951
1952fn truncate_namespace_rhs(ns: &[String], rhs: &Rhs) -> Rhs {
1953    match rhs {
1954        Rhs::Array(items) => Rhs::Array(
1955            items
1956                .iter()
1957                .map(|arr_item| Box::new(truncate_namespace_rhs(ns, arr_item)))
1958                .collect::<Vec<_>>(),
1959        ),
1960        Rhs::Range { from: _, to: _ } => rhs.clone(),
1961        Rhs::Var(var) => Rhs::Var(truncate_namespace_var(ns, var)),
1962        Rhs::Path(_) => rhs.clone(),
1963        Rhs::Val(_) => rhs.clone(),
1964    }
1965}
1966
1967fn truncate_namespace_stmt(ns: &[String], stmt: &Statement) -> Statement {
1968    match stmt {
1969        Statement::AssignLeft { lhs, rhs } => {
1970            let l = lhs
1971                .iter()
1972                .filter(|v| match v {
1973                    Var::Log => false,
1974                    Var::Predef {
1975                        name: _,
1976                        namespace: var_ns,
1977                    } => is_sub_namespace(ns, var_ns),
1978                    Var::User {
1979                        name: _,
1980                        namespace: var_ns,
1981                    } => is_sub_namespace(ns, var_ns),
1982                })
1983                .map(|l| truncate_namespace_var(ns, l))
1984                .collect::<Vec<_>>();
1985            let r = truncate_namespace_rhs(ns, rhs);
1986
1987            Statement::AssignLeft { lhs: l, rhs: r }
1988        }
1989        Statement::AssignRight { lhs, rhs } => {
1990            let r = rhs
1991                .iter()
1992                .filter(|v| match v {
1993                    Var::Log => false,
1994                    Var::Predef {
1995                        name: _,
1996                        namespace: var_ns,
1997                    } => is_sub_namespace(ns, var_ns),
1998                    Var::User {
1999                        name: _,
2000                        namespace: var_ns,
2001                    } => is_sub_namespace(ns, var_ns),
2002                })
2003                .map(|l| truncate_namespace_var(ns, l))
2004                .collect::<Vec<_>>();
2005            let l = truncate_namespace_rhs(ns, lhs);
2006
2007            Statement::AssignRight { lhs: l, rhs: r }
2008        }
2009        Statement::Compare { rhs, lhs } => Statement::Compare {
2010            rhs: rhs.to_vec(),
2011            lhs: lhs.to_vec(),
2012        },
2013    }
2014}
2015
2016fn truncate_namespace_rule(ns: &[String], rule: &RuleOwned) -> RuleOwned {
2017    let stmts = rule
2018        .stmts
2019        .iter()
2020        .map(|stmt| truncate_namespace_stmt(ns, stmt))
2021        .collect::<Vec<_>>();
2022    RuleOwned {
2023        variable: rule.variable.clone(),
2024        stmts,
2025    }
2026}
2027
2028fn truncate_namespace(ns: &[String], stmt: &StatementKindOwned) -> StatementKindOwned {
2029    match stmt {
2030        StatementKindOwned::Rule(rule_owned) => {
2031            StatementKindOwned::Rule(truncate_namespace_rule(ns, rule_owned))
2032        }
2033        StatementKindOwned::VariableDef(statement) => {
2034            StatementKindOwned::VariableDef(truncate_namespace_stmt(ns, statement))
2035        }
2036        StatementKindOwned::Reset(path) => StatementKindOwned::Reset(path.clone()),
2037        StatementKindOwned::SendFrames(kind) => StatementKindOwned::SendFrames(kind.clone()),
2038    }
2039}
2040
2041fn stmt_in_ns(namespace: &[String], stmt: &Statement) -> bool {
2042    match stmt {
2043        Statement::AssignLeft { lhs, rhs: _ } => lhs.iter().any(|r| match r {
2044            Var::Log => false,
2045            Var::Predef {
2046                name: _,
2047                namespace: var_ns,
2048            } => is_sub_namespace(namespace, var_ns),
2049            Var::User {
2050                name: _,
2051                namespace: var_ns,
2052            } => is_sub_namespace(namespace, var_ns),
2053        }),
2054        Statement::AssignRight { lhs: _, rhs } => rhs.iter().any(|r| match r {
2055            Var::Log => false,
2056            Var::Predef {
2057                name: _,
2058                namespace: var_ns,
2059            } => is_sub_namespace(namespace, var_ns),
2060            Var::User {
2061                name: _,
2062                namespace: var_ns,
2063            } => is_sub_namespace(namespace, var_ns),
2064        }),
2065
2066        Statement::Compare { rhs: _, lhs: _ } => false,
2067    }
2068}
2069
2070impl VariableHistory {
2071    pub fn new(ast: Vec<StatementKindOwned>) -> Self {
2072        VariableHistory {
2073            ast,
2074            var_cache: HashMap::new(),
2075        }
2076    }
2077
2078    pub fn with_state(mut self, state: HashMap<Var, Rhs>) -> Self {
2079        self.var_cache = state;
2080        self
2081    }
2082
2083    pub fn populate_cache(&mut self) {
2084        self.ast.iter().for_each(|f| {
2085            if let StatementKindOwned::VariableDef(statement) = f {
2086                match statement {
2087                    Statement::AssignLeft { lhs, rhs } => {
2088                        for l in lhs {
2089                            self.var_cache.insert(l.clone(), rhs.clone());
2090                        }
2091                    }
2092                    Statement::AssignRight { lhs, rhs } => {
2093                        for r in rhs {
2094                            self.var_cache.insert(r.clone(), lhs.clone());
2095                        }
2096                    }
2097                    Statement::Compare { rhs: _, lhs: _ } => {}
2098                }
2099            }
2100        });
2101    }
2102
2103    fn filter_by_namespace(
2104        &self,
2105        namespace: &[String],
2106        up_to: Option<usize>,
2107        trunc_ns: bool,
2108    ) -> Vec<StatementKindOwned> {
2109        let mut vars_in_ns = vec![];
2110
2111        // use previous cached vars as well
2112        for (var, rhs) in self.var_cache.iter() {
2113            let mut wvar = var.clone();
2114            if is_sub_namespace(
2115                namespace,
2116                match var {
2117                    Var::Log => unreachable!(),
2118                    Var::Predef { name: _, namespace } => namespace,
2119                    Var::User { name: _, namespace } => namespace,
2120                },
2121            ) {
2122                if trunc_ns {
2123                    wvar = truncate_namespace_var(namespace, &wvar);
2124                }
2125
2126                vars_in_ns.push(StatementKindOwned::VariableDef(Statement::AssignLeft {
2127                    lhs: vec![wvar],
2128                    rhs: rhs.clone(),
2129                }));
2130            }
2131        }
2132
2133        for stmt in self.ast.iter().take(up_to.unwrap_or(usize::MAX)) {
2134            match &stmt {
2135                StatementKindOwned::Rule(rule_owned) => {
2136                    let filtered_rules = rule_owned
2137                        .stmts
2138                        .iter()
2139                        .filter(|stmt| stmt_in_ns(namespace, stmt))
2140                        .map(|s| {
2141                            if trunc_ns {
2142                                truncate_namespace_stmt(namespace, s)
2143                            } else {
2144                                s.clone()
2145                            }
2146                        })
2147                        .collect::<Vec<_>>();
2148
2149                    if !filtered_rules.is_empty() {
2150                        let rule = RuleOwned {
2151                            variable: rule_owned.variable.clone(),
2152                            stmts: filtered_rules,
2153                        };
2154                        vars_in_ns.push(StatementKindOwned::Rule(rule));
2155                    }
2156                }
2157                StatementKindOwned::VariableDef(rstmt) => {
2158                    if stmt_in_ns(namespace, rstmt) {
2159                        let rhs = if trunc_ns {
2160                            truncate_namespace(namespace, stmt)
2161                        } else {
2162                            stmt.clone()
2163                        };
2164                        vars_in_ns.push(rhs);
2165                    }
2166                }
2167                StatementKindOwned::Reset(_) => {}
2168                StatementKindOwned::SendFrames(_) => {}
2169            }
2170        }
2171
2172        vars_in_ns
2173    }
2174
2175    fn resolve_recursive(&self, var: &Var, up_to: Option<usize>) -> anyhow::Result<Option<Rhs>> {
2176        // use previous state if already resolved there
2177        if let Some(cache_hit) = self.var_cache.get(var) {
2178            return Ok(Some(cache_hit.clone()));
2179        }
2180
2181        let mut val = None;
2182        for (i, stmt) in self
2183            .ast
2184            .iter()
2185            .enumerate()
2186            .take(up_to.unwrap_or(usize::MAX))
2187        {
2188            match stmt {
2189                StatementKindOwned::Rule(rule) => {
2190                    for rstmt in rule.stmts.iter() {
2191                        match rstmt {
2192                            Statement::AssignLeft { lhs, rhs } => {
2193                                if lhs.contains(var) {
2194                                    val = Some(match rhs {
2195                                        Rhs::Var(var) => {
2196                                            match self.resolve_recursive(var, Some(i))? {
2197                                                None => Rhs::Val(Val::StringVal(match var {
2198                                                    Var::User { name, namespace: _ } => {
2199                                                        name.clone()
2200                                                    }
2201                                                    Var::Log => {
2202                                                        return Err(anyhow!(
2203                                                            "Log can not be assigned."
2204                                                        ));
2205                                                    }
2206                                                    Var::Predef {
2207                                                        name: _,
2208                                                        namespace: _,
2209                                                    } => {
2210                                                        return Err(anyhow!(
2211                                                            "Predef variables can not be assigned."
2212                                                        ));
2213                                                    }
2214                                                })),
2215                                                Some(rhs) => rhs,
2216                                            }
2217                                        }
2218                                        _ => rhs.clone(),
2219                                    });
2220                                }
2221                            }
2222                            Statement::AssignRight { lhs, rhs } => {
2223                                if rhs.contains(var) {
2224                                    val = Some(match lhs {
2225                                        Rhs::Var(var) => {
2226                                            match self.resolve_recursive(var, Some(i))? {
2227                                                None => Rhs::Val(Val::StringVal(match var {
2228                                                    Var::User { name, namespace: _ } => {
2229                                                        name.clone()
2230                                                    }
2231                                                    Var::Log => {
2232                                                        return Err(anyhow!(
2233                                                            "Log can not be assigned."
2234                                                        ));
2235                                                    }
2236                                                    Var::Predef {
2237                                                        name: _,
2238                                                        namespace: _,
2239                                                    } => {
2240                                                        return Err(anyhow!(
2241                                                            "Predef variables can not be assigned."
2242                                                        ));
2243                                                    }
2244                                                })),
2245                                                Some(lhs) => lhs,
2246                                            }
2247                                        }
2248                                        _ => lhs.clone(),
2249                                    });
2250                                }
2251                            }
2252                            Statement::Compare { rhs: _, lhs: _ } => {}
2253                        }
2254                    }
2255                }
2256                StatementKindOwned::VariableDef(statement) => match statement {
2257                    Statement::AssignLeft { lhs, rhs } => {
2258                        if lhs.contains(var) {
2259                            val = Some(match rhs {
2260                                Rhs::Var(var) => match self.resolve_recursive(var, Some(i))? {
2261                                    None => Rhs::Val(Val::StringVal(match var {
2262                                        Var::User { name, namespace: _ } => name.clone(),
2263                                        Var::Log => {
2264                                            return Err(anyhow!("Log can not be assigned."));
2265                                        }
2266                                        Var::Predef {
2267                                            name: _,
2268                                            namespace: _,
2269                                        } => {
2270                                            return Err(anyhow!(
2271                                                "Predef variables can not be assigned."
2272                                            ));
2273                                        }
2274                                    })),
2275                                    Some(rhs) => rhs,
2276                                },
2277                                _ => rhs.clone(),
2278                            });
2279                        }
2280                    }
2281                    Statement::AssignRight { lhs, rhs } => {
2282                        if rhs.contains(var) {
2283                            val = Some(match lhs {
2284                                Rhs::Var(var) => match self.resolve_recursive(var, Some(i))? {
2285                                    None => Rhs::Val(Val::StringVal(match var {
2286                                        Var::User { name, namespace: _ } => name.clone(),
2287                                        Var::Log => {
2288                                            return Err(anyhow!("Log can not be assigned."));
2289                                        }
2290                                        Var::Predef {
2291                                            name: _,
2292                                            namespace: _,
2293                                        } => {
2294                                            return Err(anyhow!(
2295                                                "Predef variables can not be assigned."
2296                                            ));
2297                                        }
2298                                    })),
2299                                    Some(lhs) => lhs,
2300                                },
2301                                _ => lhs.clone(),
2302                            });
2303                        }
2304                    }
2305                    Statement::Compare { rhs: _, lhs: _ } => {}
2306                },
2307                StatementKindOwned::Reset(_) => {}
2308                StatementKindOwned::SendFrames(_) => {}
2309            }
2310        }
2311        Ok(val)
2312    }
2313
2314    fn prepend_ns(var: &Var, ns: &[String]) -> Var {
2315        match var {
2316            Var::Log => Var::Log,
2317            Var::Predef {
2318                name,
2319                namespace: var_ns,
2320            } => {
2321                let v = vec_prepend(ns, var_ns);
2322
2323                Var::Predef {
2324                    name: name.clone(),
2325                    namespace: v,
2326                }
2327            }
2328            Var::User {
2329                name,
2330                namespace: var_ns,
2331            } => {
2332                let v = vec_prepend(ns, var_ns);
2333
2334                Var::User {
2335                    name: name.clone(),
2336                    namespace: v,
2337                }
2338            }
2339        }
2340    }
2341
2342    pub fn resolve_ns(&self, namespace: &[&str]) -> Vec<(Var, Rhs)> {
2343        let owned_ns = namespace
2344            .iter()
2345            .map(|s| (*s).to_owned())
2346            .collect::<Vec<_>>();
2347        self.filter_by_namespace(&owned_ns, None, true)
2348            .iter()
2349            .flat_map(|stmt| match stmt {
2350                StatementKindOwned::Rule(rule_owned) => rule_owned
2351                    .stmts
2352                    .iter()
2353                    .flat_map(|st| match st {
2354                        Statement::AssignLeft { lhs, rhs: _ } => Some(
2355                            lhs.iter()
2356                                .map(|lh| {
2357                                    (
2358                                        lh,
2359                                        self.resolve_var(&Self::prepend_ns(lh, &owned_ns))
2360                                            .expect("Should have failed in Pass 2"),
2361                                    )
2362                                })
2363                                .collect::<Vec<_>>(),
2364                        ),
2365                        Statement::AssignRight { lhs: _, rhs } => Some(
2366                            rhs.iter()
2367                                .map(|lh| {
2368                                    (
2369                                        lh,
2370                                        self.resolve_var(&Self::prepend_ns(lh, &owned_ns))
2371                                            .expect("Should have failed in Pass 2"),
2372                                    )
2373                                })
2374                                .collect::<Vec<_>>(),
2375                        ),
2376                        Statement::Compare { rhs: _, lhs: _ } => None,
2377                    })
2378                    .flatten()
2379                    .collect::<Vec<_>>(),
2380                StatementKindOwned::VariableDef(statement) => match statement {
2381                    Statement::AssignLeft { lhs, rhs: _ } => lhs
2382                        .iter()
2383                        .map(|lh| {
2384                            (
2385                                lh,
2386                                self.resolve_var(&Self::prepend_ns(lh, &owned_ns))
2387                                    .expect("Should have failed in Pass 2"),
2388                            )
2389                        })
2390                        .collect::<Vec<_>>(),
2391
2392                    Statement::AssignRight { lhs: _, rhs } => rhs
2393                        .iter()
2394                        .map(|lh| {
2395                            (
2396                                lh,
2397                                self.resolve_var(&Self::prepend_ns(lh, &owned_ns))
2398                                    .expect("Should have failed in Pass 2"),
2399                            )
2400                        })
2401                        .collect::<Vec<_>>(),
2402
2403                    Statement::Compare { rhs: _, lhs: _ } => vec![],
2404                },
2405                StatementKindOwned::Reset(_) => vec![],
2406                StatementKindOwned::SendFrames(_) => vec![],
2407            })
2408            .fold(Vec::new(), |mut acc, res| match res {
2409                (var, Some(rhs)) => {
2410                    acc.push((truncate_namespace_var(&owned_ns, var), rhs));
2411                    acc
2412                }
2413                (_, None) => acc, // skip if not set to anything
2414            })
2415    }
2416
2417    pub fn filter_ns(&self, namespace: &[&str]) -> Self {
2418        let owned_ns = namespace
2419            .iter()
2420            .map(|s| (*s).to_owned())
2421            .collect::<Vec<_>>();
2422        let filtered = self.filter_by_namespace(&owned_ns, None, true);
2423        Self::new(filtered)
2424    }
2425
2426    pub fn resolve(&self, var: &str) -> anyhow::Result<Option<Rhs>> {
2427        self.resolve_var(&Var::from_str(var)?)
2428    }
2429
2430    fn resolve_var(&self, var: &Var) -> anyhow::Result<Option<Rhs>> {
2431        self.resolve_recursive(var, None)
2432    }
2433}
2434
2435fn resolve_rhs_recursive(
2436    rhs: &mut Rhs,
2437    var_history: &VariableHistory,
2438    i: usize,
2439) -> anyhow::Result<()> {
2440    match rhs {
2441        Rhs::Array(items) => {
2442            for rhs_item in items.iter_mut() {
2443                resolve_rhs_recursive(&mut *rhs_item, var_history, i)?;
2444            }
2445        }
2446        Rhs::Var(var) => {
2447            // implicit strings when mentioned but not found in context earlier
2448            *rhs = match var_history.resolve_recursive(var, Some(i))? {
2449                None => Rhs::Val(Val::StringVal(match var {
2450                    Var::User { name, namespace: _ } => name.clone(),
2451                    Var::Log => {
2452                        return Err(anyhow!("Log can not be assigned."));
2453                    }
2454                    Var::Predef {
2455                        name: _,
2456                        namespace: _,
2457                    } => {
2458                        return Err(anyhow!("Predef variables can not be assigned."));
2459                    }
2460                })),
2461                Some(rhs) => rhs,
2462            };
2463        }
2464        _ => {}
2465    };
2466
2467    Ok(())
2468}
2469
2470fn resolve_stmt(
2471    stmt: &mut Statement,
2472    var_history: &VariableHistory,
2473    i: usize,
2474) -> anyhow::Result<()> {
2475    match stmt {
2476        Statement::AssignLeft { lhs: _, rhs } => {
2477            resolve_rhs_recursive(rhs, var_history, i)?;
2478        }
2479        Statement::AssignRight { lhs, rhs: _ } => {
2480            resolve_rhs_recursive(lhs, var_history, i)?;
2481        }
2482        Statement::Compare { rhs: _, lhs: _ } => {} // keep compare since only applicable to rules that are parsed as variables
2483    }
2484
2485    Ok(())
2486}
2487
2488pub fn compile_code(source_code_raw: &str) -> anyhow::Result<Evaluated> {
2489    let currdir = std::env::current_dir()?;
2490    compile_code_with_state(
2491        &(source_code_raw.to_owned() + "\n"), // hack to fix one-line token problems
2492        &currdir,
2493        None,
2494        std::io::stderr(),
2495        true,
2496    )
2497}
2498
2499fn resolve_struct_in_ns(user_ns: &[(Var, Rhs)], var: &str) -> Option<AnySensor> {
2500    // var is the first namespace for the vars, so gather all and find _name, _type and _short in them.
2501    let name = var.to_owned();
2502    let mut short = None;
2503    let mut topic: Option<String> = None;
2504    let mut msg_type = None;
2505    let mut short_lookup: HashMap<String, String> = HashMap::new();
2506
2507    for (v, rhs) in user_ns.iter() {
2508        if let Var::Predef { name, namespace } = v {
2509            if (*name).as_str() == "short" {
2510                let val = match rhs {
2511                    Rhs::Val(Val::StringVal(s)) => s.clone(),
2512                    _ => {
2513                        return None;
2514                    }
2515                };
2516                short_lookup.insert(val, namespace.first()?.clone());
2517            }
2518        }
2519    }
2520    for (v, rhs) in user_ns.iter() {
2521        match v {
2522            Var::Log => {}
2523            Var::Predef {
2524                name: predef_var_name,
2525                namespace,
2526            } => {
2527                let found_by_name = namespace
2528                    .first()
2529                    .map(|s| {
2530                        let long_name = (*s).as_str() == var;
2531                        if long_name {
2532                            return true;
2533                        }
2534                        let found_by_short = short_lookup.get(var);
2535                        if let Some(short_name) = found_by_short {
2536                            (*short_name).as_str() == (*s).as_str()
2537                        } else {
2538                            false
2539                        }
2540                    })
2541                    .unwrap_or_default();
2542
2543                if !found_by_name {
2544                    continue;
2545                }
2546
2547                match predef_var_name.as_str() {
2548                    "short" => match rhs {
2549                        Rhs::Val(Val::StringVal(s)) => {
2550                            short = Some((*s).clone());
2551                        }
2552                        _ => {
2553                            return None;
2554                        }
2555                    },
2556                    "topic" => match rhs {
2557                        Rhs::Val(Val::StringVal(s)) | Rhs::Path(s) => {
2558                            topic = Some((*s).clone());
2559                        }
2560                        _ => {
2561                            return None;
2562                        }
2563                    },
2564                    "type" => match rhs {
2565                        Rhs::Val(Val::StringVal(s)) => {
2566                            let typed = SensorType::from_str(s.as_str())
2567                                .expect("No error in impl, falls back to any");
2568                            msg_type = Some(typed);
2569                        }
2570                        _ => {
2571                            return None;
2572                        }
2573                    },
2574                    _ => {}
2575                }
2576            }
2577            Var::User {
2578                name: _,
2579                namespace: _,
2580            } => {}
2581        }
2582    }
2583
2584    let id = match (topic, msg_type) {
2585        (Some(t), None) => SensorIdentification::Topic(t),
2586        (None, Some(t)) => SensorIdentification::Type(t),
2587        (Some(topic), Some(msg_type)) => SensorIdentification::TopicAndType { topic, msg_type },
2588        _ => {
2589            return None;
2590        }
2591    };
2592
2593    Some(AnySensor { name, id, short })
2594}
2595
2596fn resolve_sensors(user_ns: &[(Var, Rhs)], sensors: &[String]) -> anyhow::Result<Vec<AnySensor>> {
2597    let mut mapped = vec![];
2598    for sensor in sensors {
2599        let any = resolve_struct_in_ns(user_ns, sensor)
2600            .ok_or(anyhow!("Could not find sensor: {}", &sensor))?;
2601        mapped.push(any);
2602    }
2603    Ok(mapped)
2604}
2605
2606pub fn compile_code_with_state(
2607    source_code_raw: &str,
2608    source_code_parent_dir: &std::path::Path,
2609    var_state: Option<HashMap<Var, Rhs>>,
2610    mut out: impl std::io::Write,
2611    rich_out: bool,
2612) -> anyhow::Result<Evaluated> {
2613    let token_iter = Token::lexer(source_code_raw)
2614        .spanned()
2615        // Convert logos errors into tokens. We want parsing to be recoverable and not fail at the lexing stage, so
2616        // we have a dedicated `Token::Error` variant that represents a token error that was previously encountered
2617        .map(|(tok, span)| match tok {
2618            // Turn the `Range<usize>` spans logos gives us into chumsky's `SimpleSpan` via `Into`, because it's easier
2619            // to work with
2620            Ok(tok) => (tok, span.into()),
2621            Err(()) => (Token::Error, span.into()),
2622        });
2623
2624    // Turn the token iterator into a stream that chumsky can use for things like backtracking
2625    let token_stream = Stream::from_iter(token_iter)
2626        // Tell chumsky to split the (Token, SimpleSpan) stream into its parts so that it can handle the spans for us
2627        // This involves giving chumsky an 'end of input' span: we just use a zero-width span at the end of the string
2628        .map((0..source_code_raw.len()).into(), |(t, s): (_, _)| (t, s));
2629
2630    // Parse the token stream with our chumsky parser
2631    match parser().parse(token_stream).into_result() {
2632        Ok(sexpr) => {
2633            let owned = sexpr
2634                .into_iter()
2635                .map(|kind| kind.into())
2636                .collect::<Vec<StatementKindOwnedPass1>>();
2637
2638            // Pass 1 -- parsing included files and expanding namespaces
2639            let mut ast = do_pass1(owned, source_code_parent_dir)?; // could print parse errors from included files
2640
2641            let mut rules = Vec::new();
2642            let mut winds = Vec::new();
2643            // let mut ast: Vec<StatementKindOwnedPass1> = Vec::new();
2644            for expr in &ast {
2645                // clone for ease of use, but normally just use AST
2646                match expr {
2647                    StatementKindOwned::Rule(rule) => {
2648                        rules.push(rule.clone());
2649                    }
2650                    StatementKindOwned::Reset(_) => winds.push(expr.clone()),
2651                    StatementKindOwned::SendFrames(_) => winds.push(expr.clone()),
2652                    StatementKindOwned::VariableDef(_) => {}
2653                }
2654                // ast.push(expr.into());
2655            }
2656            let rules = RuleSexpr { rules };
2657            let rules = rules.eval()?;
2658
2659            // Pass 2 -- needs entire ast for resolving. TODO could still be combined to Pass 1 with a subset of the ast to t-1.
2660            // Resolve all variables here, else implicit strings in nested assigns are handled as variables.
2661            // Use the repl state in case the user already run some variables from before which we want to build upon
2662            let var_history =
2663                VariableHistory::new(ast.clone()).with_state(var_state.clone().unwrap_or_default());
2664            for (i, node) in ast.iter_mut().enumerate() {
2665                match node {
2666                    StatementKindOwned::Rule(rule_owned) => {
2667                        for stmt in rule_owned.stmts.iter_mut() {
2668                            resolve_stmt(stmt, &var_history, i)?;
2669                        }
2670                    }
2671                    StatementKindOwned::VariableDef(statement) => {
2672                        resolve_stmt(statement, &var_history, i)?;
2673                    }
2674                    StatementKindOwned::Reset(_) => {}
2675                    StatementKindOwned::SendFrames(_) => {}
2676                }
2677            }
2678
2679            // Ext. Pass 3 -- resolve the wind fns to anysensor to check if short or long form etc.
2680            let vars = VariableHistory::new(ast.clone()).with_state(var_state.unwrap_or_default());
2681            let bag_ns = vars.resolve_ns(&["_bag"]);
2682            let mut wind = Vec::new();
2683            for node in ast.into_iter() {
2684                match node {
2685                    StatementKindOwned::SendFrames(sf) => match sf {
2686                        PlayKindUnited::SensorCount {
2687                            sensors,
2688                            count,
2689                            trigger,
2690                            play_mode,
2691                        } => {
2692                            let sensors = resolve_sensors(&bag_ns, &sensors)?;
2693                            wind.push(WindFunction::SendFrames(PlayKindUnitedPass3::SensorCount {
2694                                sensors,
2695                                count,
2696                                trigger,
2697                                play_mode,
2698                            }));
2699                        }
2700                        PlayKindUnited::UntilSensorCount {
2701                            sending,
2702                            until_sensors,
2703                            until_count,
2704                            trigger,
2705                            play_mode,
2706                        } => {
2707                            let until_sensors = resolve_sensors(&bag_ns, &until_sensors)?;
2708                            let sending = resolve_sensors(&bag_ns, &sending)?;
2709                            wind.push(WindFunction::SendFrames(
2710                                PlayKindUnitedPass3::UntilSensorCount {
2711                                    sending,
2712                                    until_sensors,
2713                                    until_count,
2714                                    trigger,
2715                                    play_mode,
2716                                },
2717                            ));
2718                        }
2719                    },
2720                    StatementKindOwned::Reset(p) => {
2721                        wind.push(WindFunction::Reset(p));
2722                    }
2723                    _ => {}
2724                };
2725            }
2726
2727            return Ok(Evaluated { rules, wind, vars });
2728        }
2729        Err(errs) => {
2730            let src = Source::from(source_code_raw);
2731            for err in errs {
2732                if rich_out {
2733                    let e = Report::build(ReportKind::Error, ((), err.span().into_range()))
2734                        .with_code(3)
2735                        .with_message(err.to_string())
2736                        .with_label(
2737                            Label::new(((), err.span().into_range()))
2738                                .with_message(err.reason().to_string())
2739                                .with_color(Color::Red),
2740                        )
2741                        .finish();
2742
2743                    e.write(src.clone(), &mut out).unwrap();
2744                } else {
2745                    let msg = format!(
2746                        "<{}-{}>  {}",
2747                        err.span().start,
2748                        err.span().end,
2749                        err.reason(),
2750                    );
2751                    out.write_all(msg.as_bytes()).unwrap();
2752                }
2753            }
2754        }
2755    }
2756
2757    Err(anyhow!("Could not parse ratslang code."))
2758}
2759
2760#[cfg(test)]
2761mod tests {
2762    use super::*;
2763
2764    #[test]
2765    fn minimal_wind() {
2766        const SRC: &str = r#"
2767        reset! ./bag_file_name
2768
2769        _bag.{
2770            lidar.{
2771                _short = l
2772                _type = Pointcloud2
2773            }
2774            imu.{
2775                _short = i
2776                _type = Imu
2777            }
2778        }
2779
2780        pf! l 10s var1
2781        pf! i, l 5 var1
2782        pf! l 10 var1
2783
2784        rule!(var1
2785            testRat1 -> testRat2
2786        )
2787        pf! l 10s var1
2788        "#;
2789
2790        let eval = compile_code(SRC);
2791        assert!(eval.is_ok());
2792        let eval = eval.unwrap();
2793        assert!(!eval.rules.raw().is_empty());
2794        assert!(!eval.wind.is_empty());
2795    }
2796
2797    #[test]
2798    fn reset_accepts_a_quoted_marina_reference() {
2799        let eval = compile_code(r#"reset! "wachsbleiche/loop_2:hunter""#).unwrap();
2800        assert!(matches!(
2801            eval.wind.as_slice(),
2802            [WindFunction::Reset(target)] if target == "wachsbleiche/loop_2:hunter"
2803        ));
2804    }
2805
2806    #[test]
2807    fn reset_accepts_an_unquoted_marina_reference_like_the_cli() {
2808        let eval = compile_code(r#"reset! wachsbleiche/loop_2:hunter"#).unwrap();
2809        assert!(matches!(
2810            eval.wind.as_slice(),
2811            [WindFunction::Reset(target)] if target == "wachsbleiche/loop_2:hunter"
2812        ));
2813    }
2814
2815    #[test]
2816    fn single_line_rule() {
2817        const SRC: &str = r"
2818        rule!(var1 testRat1 -> testRat2)
2819        ";
2820
2821        let eval = compile_code(SRC);
2822        assert!(eval.is_ok());
2823        let eval = eval.unwrap();
2824        assert!(!eval.rules.raw().is_empty());
2825    }
2826
2827    #[test]
2828    fn comments() {
2829        const SRC: &str = r"
2830        # bla,.
2831        # ups /// \masd
2832        a = 1 # yo
2833        ";
2834
2835        let eval = compile_code(SRC);
2836        assert!(eval.is_ok());
2837        let eval = eval.unwrap();
2838        assert!(eval.rules.raw().is_empty());
2839        assert!(eval.wind.is_empty());
2840    }
2841
2842    #[test]
2843    fn var_declare() {
2844        const SRC: &str = r"
2845         a <- 7
2846         b <- a
2847         a <- 6
2848         _l <- /cloud
2849        ";
2850
2851        // let mut a = Token::lexer(SRC);
2852        // let b = a.next();
2853        // dbg!(b);
2854
2855        let eval = compile_code(SRC);
2856        assert!(eval.is_ok());
2857        let eval = eval.unwrap();
2858
2859        let res = eval.vars.resolve("_l");
2860        assert!(res.is_ok());
2861        let res = res.unwrap();
2862        assert!(res.is_some());
2863        let res = res.unwrap();
2864        assert_eq!(res, Rhs::Path("/cloud".to_owned()));
2865
2866        let res = eval.vars.resolve("a");
2867        assert!(res.is_ok());
2868        let res = res.unwrap();
2869        assert!(res.is_some());
2870        let res = res.unwrap();
2871        assert_eq!(res, Rhs::Val(Val::NumVal(NumVal::Integer(6))));
2872
2873        let res = eval.vars.resolve("b");
2874        assert!(res.is_ok());
2875        let res = res.unwrap();
2876        assert!(res.is_some());
2877        let res = res.unwrap();
2878        assert_eq!(res, Rhs::Val(Val::NumVal(NumVal::Integer(7))));
2879    }
2880
2881    #[test]
2882    fn var_declare_nested() {
2883        const SRC: &str = r"
2884         a.b.c = 7
2885         a.b = a.b.c
2886         a.b.c = 6
2887         wind._l = /cloud
2888        ";
2889
2890        // let mut a = Token::lexer(SRC);
2891        // let b = a.next();
2892        // dbg!(b);
2893
2894        let eval = compile_code(SRC);
2895        assert!(eval.is_ok());
2896        let eval = eval.unwrap();
2897
2898        let res = eval.vars.resolve("wind._l");
2899        assert!(res.is_ok());
2900        let res = res.unwrap();
2901        assert!(res.is_some());
2902        let res = res.unwrap();
2903        assert_eq!(res, Rhs::Path("/cloud".to_owned()));
2904
2905        let res = eval.vars.resolve("a.b.c");
2906        assert!(res.is_ok());
2907        let res = res.unwrap();
2908        assert!(res.is_some());
2909        let res = res.unwrap();
2910        assert_eq!(res, Rhs::Val(Val::NumVal(NumVal::Integer(6))));
2911
2912        let res = eval.vars.resolve("a.b");
2913        assert!(res.is_ok());
2914        let res = res.unwrap();
2915        assert!(res.is_some());
2916        let res = res.unwrap();
2917        assert_eq!(res, Rhs::Val(Val::NumVal(NumVal::Integer(7))));
2918    }
2919
2920    #[test]
2921    fn include() {
2922        const SRC: &str = r"
2923        # like assigning a file to the current namespace
2924        <- ./../mt/test.mt
2925
2926        # including in namespace blocks will prepend the namespaces to the included AST
2927        # (excluding rules, they are always global)
2928        c.{
2929            <- ./../mt/test.mt
2930        }
2931        ";
2932
2933        let eval = compile_code(SRC);
2934        assert!(eval.is_ok());
2935        let eval = eval.unwrap();
2936
2937        let res = eval.vars.resolve("test");
2938        assert!(res.is_ok());
2939        let res = res.unwrap();
2940        assert!(res.is_some());
2941        let res = res.unwrap();
2942        assert_eq!(res, Rhs::Val(Val::NumVal(NumVal::Integer(4))));
2943
2944        let res = eval.vars.resolve("c.test");
2945        assert!(res.is_ok());
2946        let res = res.unwrap();
2947        assert!(res.is_some());
2948        let res = res.unwrap();
2949        assert_eq!(res, Rhs::Val(Val::NumVal(NumVal::Integer(4))));
2950    }
2951
2952    #[test]
2953    fn var_declare_blocks() {
2954        const SRC: &str = r"
2955        a.{
2956            b = 7
2957        }
2958
2959        c.{
2960            t = 5
2961
2962            d.{
2963                1 -> o
2964            }
2965            i = 95
2966        }
2967        ";
2968
2969        let eval = compile_code(SRC);
2970        assert!(eval.is_ok());
2971        let eval = eval.unwrap();
2972
2973        let res = eval.vars.resolve("a.b");
2974        assert!(res.is_ok());
2975        let res = res.unwrap();
2976        assert!(res.is_some());
2977        let res = res.unwrap();
2978        assert_eq!(res, Rhs::Val(Val::NumVal(NumVal::Integer(7))));
2979
2980        let res = eval.vars.resolve("c.t");
2981        assert!(res.is_ok());
2982        let res = res.unwrap();
2983        assert!(res.is_some());
2984        let res = res.unwrap();
2985        assert_eq!(res, Rhs::Val(Val::NumVal(NumVal::Integer(5))));
2986
2987        let res = eval.vars.resolve("c.d.o");
2988        assert!(res.is_ok());
2989        let res = res.unwrap();
2990        assert!(res.is_some());
2991        let res = res.unwrap();
2992        assert_eq!(res, Rhs::Val(Val::NumVal(NumVal::Integer(1))));
2993
2994        let res = eval.vars.resolve("c.i");
2995        assert!(res.is_ok());
2996        let res = res.unwrap();
2997        assert!(res.is_some());
2998        let res = res.unwrap();
2999        assert_eq!(res, Rhs::Val(Val::NumVal(NumVal::Integer(95))));
3000    }
3001
3002    #[test]
3003    fn in_ns() {
3004        // other, me
3005        let res = is_sub_namespace(&["a".to_owned()], &["a".to_owned()]); // true
3006        assert!(res);
3007        let res = is_sub_namespace(&["a".to_owned(), "b".to_owned()], &["a".to_owned()]); // a.b is deeper than a, so a.b can not be a sub namespace. false
3008        assert!(!res);
3009        let res = is_sub_namespace(&["a".to_owned()], &["a".to_owned(), "b".to_owned()]); // a is in a.b, true
3010        assert!(res);
3011        let res = is_sub_namespace(&[], &["a".to_owned()]); // empty is not in a.b, false
3012        assert!(!res);
3013    }
3014
3015    #[test]
3016    fn resolve_ns() {
3017        const SRC: &str = r"
3018        rule! (var1
3019            testRat1 -> testRat2
3020            testRat1 -> testRat2, a.c
3021            a.b <- 5
3022        )
3023
3024        _bag.{
3025            lidar.{
3026                short = l
3027                type = Pointcloud2
3028            }
3029            imu.{
3030                _short = i
3031                _type = Imu
3032            }
3033        }
3034        ";
3035
3036        let eval = compile_code(SRC);
3037        assert!(eval.is_ok());
3038        let eval = eval.unwrap();
3039        let e = eval.vars.resolve_ns(&["a"]);
3040        assert_eq!(e.len(), 2);
3041        let (var, rhs) = &e[1];
3042        assert_eq!(*var, Var::from_str("b").unwrap());
3043        assert_eq!(*rhs, Rhs::Val(Val::NumVal(NumVal::Integer(5))));
3044
3045        let e = eval.vars.resolve_ns(&["_bag"]);
3046        assert_eq!(e.len(), 4);
3047    }
3048
3049    #[test]
3050    fn strings() {
3051        const SRC: &str = r#"
3052        a = "bla with space"
3053        b = Blub
3054        c = Lidar::Ouster
3055            
3056        "#;
3057
3058        let eval = compile_code(SRC);
3059        assert!(eval.is_ok());
3060        let eval = eval.unwrap();
3061
3062        let e = eval.vars.resolve("a");
3063        assert!(e.is_ok());
3064        let e = e.unwrap();
3065        assert!(e.is_some());
3066        let rhs = e.unwrap();
3067        assert_eq!(rhs, Rhs::Val(Val::StringVal("bla with space".to_owned())));
3068
3069        let e = eval.vars.resolve("b");
3070        assert!(e.is_ok());
3071        let e = e.unwrap();
3072        assert!(e.is_some());
3073        let rhs = e.unwrap();
3074        assert_eq!(rhs, Rhs::Val(Val::StringVal("Blub".to_owned())));
3075
3076        let e = eval.vars.resolve("c");
3077        assert!(e.is_ok());
3078        let e = e.unwrap();
3079        assert!(e.is_some());
3080        let rhs = e.unwrap();
3081        assert_eq!(rhs, Rhs::Val(Val::StringVal("Lidar::Ouster".to_owned())));
3082    }
3083
3084    #[test]
3085    fn arrays() {
3086        const SRC: &str = r#"
3087        a = [ "bla with space", Blub ]
3088        "#;
3089
3090        let eval = compile_code(SRC);
3091        assert!(eval.is_ok());
3092        let eval = eval.unwrap();
3093
3094        let e = eval.vars.resolve("a");
3095        assert!(e.is_ok());
3096        let e = e.unwrap();
3097        assert!(e.is_some());
3098        let rhs = e.unwrap();
3099        assert_eq!(
3100            rhs,
3101            Rhs::Array(vec![
3102                Box::new(Rhs::Val(Val::StringVal("bla with space".to_owned()))),
3103                Box::new(Rhs::Val(Val::StringVal("Blub".to_owned()))),
3104            ])
3105        );
3106    }
3107
3108    // #[test]
3109    // fn enums() {
3110    //     // in your code
3111    //     #[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
3112    //     enum Lidar {
3113    //         Ouster,
3114    //         Sick,
3115    //     }
3116
3117    //     #[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
3118    //     enum Sensor {
3119    //         Lidar(Lidar),
3120    //         Imu,
3121    //     }
3122
3123    //     // for rl
3124    //     #[derive(Debug)]
3125    //     enum Enums {
3126    //         Sensor(Sensor),
3127    //     }
3128    //     let a = Enums::Sensor(Sensor::Lidar(Lidar::Ouster));
3129    //     let b = format!("{:?}", a);
3130    //     let r = convert_to_path(&b);
3131    //     println!("{:?}", r);
3132    //     const SRC: &str = "a = Sensor::Lidar";
3133
3134    // TODO Give Enum to parser function that has all possible variants as trait. so fn variants(self--impl display) -> [impl FromStr]. Then call that in parser and pass type through to AST. If parser finds Sensor type, that has the same name as one of the enums in display. so it calls the parse function on that variant.
3135    #[test]
3136    fn vec_mat_vals() {
3137        const SRC: &str = r"
3138        vec = [3, 2, 4]
3139
3140        mat = [ [3, 1, 1],
3141                [3, 2, 4] ]
3142        ";
3143
3144        let eval = compile_code(SRC);
3145        assert!(eval.is_ok());
3146        let eval = eval.unwrap();
3147        let vec = eval.vars.resolve("vec").unwrap().unwrap();
3148        assert_eq!(
3149            vec,
3150            Rhs::Array(vec![
3151                Box::new(Rhs::Val(Val::NumVal(NumVal::Integer(3)))),
3152                Box::new(Rhs::Val(Val::NumVal(NumVal::Integer(2)))),
3153                Box::new(Rhs::Val(Val::NumVal(NumVal::Integer(4)))),
3154            ])
3155        );
3156        let mat = eval.vars.resolve("mat").unwrap().unwrap();
3157        assert_eq!(
3158            mat,
3159            Rhs::Array(vec![
3160                Box::new(Rhs::Array(vec![
3161                    Box::new(Rhs::Val(Val::NumVal(NumVal::Integer(3)))),
3162                    Box::new(Rhs::Val(Val::NumVal(NumVal::Integer(1)))),
3163                    Box::new(Rhs::Val(Val::NumVal(NumVal::Integer(1)))),
3164                ])),
3165                Box::new(Rhs::Array(vec![
3166                    Box::new(Rhs::Val(Val::NumVal(NumVal::Integer(3)))),
3167                    Box::new(Rhs::Val(Val::NumVal(NumVal::Integer(2)))),
3168                    Box::new(Rhs::Val(Val::NumVal(NumVal::Integer(4)))),
3169                ])),
3170            ])
3171        );
3172    }
3173
3174    //     #[test]
3175    //     fn resolve_struct() {
3176    //         const SRC: &str = r"
3177    // _bag.{
3178    // 	lidar.{
3179    // 		_short = l
3180    // 		_topic = /ouster/points
3181    // 		_type = Pointcloud2
3182    // 	}
3183    // }
3184
3185    //         ";
3186
3187    //         let eval = compile_code(SRC);
3188    //         assert!(eval.is_ok());
3189    //         let eval = eval.unwrap();
3190
3191    //         resolve_struct_in_ns(user_ns, var)
3192
3193    //     }
3194    #[test]
3195    fn advanced_wind() {
3196        const SRC: &str = r"
3197        reset! ./bag_file_name
3198
3199        _bag.{
3200            lidar.{
3201                _short = l
3202                _type = Pointcloud2
3203            }
3204            imu.{
3205                _short = i
3206                _type = Imu
3207            }
3208        }
3209
3210        # send all lidar frames between the absolute 10s and 20s of the bagfile immediately
3211        pf! l 10s..20s
3212
3213        # send all lidar frames between the absolute 10s and 20s of the bagfile when reaching var1
3214        pf! l 10s..20s var1
3215
3216        # send all lidar frames between the absolute 10s and 20s of the bagfile but slow down time so it sends it over 1 minute
3217        pf! l 10s..20s 2mins
3218
3219        # send imu frames until 2 lidar frames are encountered
3220        pf! i,l 2
3221
3222        # send imu frames until 2 lidar frames are encountered but spread over 8s real time
3223        pf! i,l 2 8s
3224
3225        # send 10 lidar frames but spread them out over 20s
3226        pf! l 10 20s
3227
3228        # send the next(!) 10 seconds of lidar frames every time it reaches var1
3229        pf! l 10s var1
3230
3231        # fixed var
3232        pf! l 10s..20s var1 f
3233
3234        # dynamic var
3235        pf! l 10s..20s var1 d
3236
3237        # implicit dynamic var
3238        pf! l 10s..20s var1
3239
3240        # relative play time
3241        pf! l 10s..20s 1.
3242
3243        pf! l, i 2 1.
3244        ";
3245
3246        let eval = compile_code(SRC);
3247        assert!(eval.is_ok());
3248        let eval = eval.unwrap();
3249        assert!(!eval.wind.is_empty());
3250    }
3251
3252    #[test]
3253    fn test_loop_basic() {
3254        const SRC: &str = r"
3255        loop 3 {
3256            x = 1
3257            y = 2
3258        }
3259        ";
3260
3261        let eval = compile_code(SRC);
3262        assert!(eval.is_ok());
3263        let eval = eval.unwrap();
3264
3265        // The loop should expand to 3 copies of x=1 and y=2
3266        // So we should have x=1 defined 3 times (last one wins)
3267        let x = eval.vars.resolve("x").unwrap().unwrap();
3268        assert_eq!(x, Rhs::Val(Val::NumVal(NumVal::Integer(1))));
3269        let y = eval.vars.resolve("y").unwrap().unwrap();
3270        assert_eq!(y, Rhs::Val(Val::NumVal(NumVal::Integer(2))));
3271    }
3272
3273    #[test]
3274    fn test_loop_nested() {
3275        const SRC: &str = r"
3276        loop 2 {
3277            a = 10
3278            loop 2 {
3279                b = 20
3280            }
3281        }
3282        ";
3283
3284        let eval = compile_code(SRC);
3285        assert!(eval.is_ok());
3286        let eval = eval.unwrap();
3287
3288        let a = eval.vars.resolve("a").unwrap().unwrap();
3289        assert_eq!(a, Rhs::Val(Val::NumVal(NumVal::Integer(10))));
3290        let b = eval.vars.resolve("b").unwrap().unwrap();
3291        assert_eq!(b, Rhs::Val(Val::NumVal(NumVal::Integer(20))));
3292    }
3293
3294    #[test]
3295    fn test_loop_token() {
3296        // Test that "loop" is recognized as a keyword token, not a variable
3297        let mut lex = Token::lexer("loop 2");
3298        assert_eq!(lex.next(), Some(Ok(Token::KwLoop)));
3299        assert_eq!(lex.next(), Some(Ok(Token::IntegerNumber(2))));
3300    }
3301}