datex_core/compiler/
ast_parser.rs

1use crate::compiler::lexer::Token;
2use crate::global::binary_codes::InstructionCode;
3use crate::global::protocol_structures::instructions::Instruction;
4use crate::values::core_values::array::Array;
5use crate::values::core_values::decimal::decimal::Decimal;
6use crate::values::core_values::integer::integer::Integer;
7use crate::values::core_values::object::Object;
8use crate::values::value::Value;
9use crate::values::value_container::ValueContainer;
10use crate::{
11    compiler::ast_parser::extra::Err, values::core_values::endpoint::Endpoint,
12};
13use chumsky::prelude::*;
14use logos::Logos;
15use std::str::FromStr;
16use std::{collections::HashMap, ops::Range};
17
18#[derive(Clone, Debug, PartialEq)]
19pub enum TupleEntry {
20    KeyValue(DatexExpression, DatexExpression),
21    Value(DatexExpression),
22}
23
24#[derive(Clone, Debug, PartialEq, Copy)]
25pub enum BinaryOperator {
26    Add,
27    Subtract,
28    Multiply,
29    Divide,
30    Modulo,
31    Power,
32    And,
33    Or,
34    CompositeAnd,
35    CompositeOr,
36    StructuralEqual,
37    NotStructuralEqual,
38    Equal,
39    NotEqual,
40    Is,
41    LessThan,
42    GreaterThan,
43    LessThanOrEqual,
44    GreaterThanOrEqual,
45}
46
47impl From<&BinaryOperator> for InstructionCode {
48    fn from(op: &BinaryOperator) -> Self {
49        match op {
50            BinaryOperator::Add => InstructionCode::ADD,
51            BinaryOperator::Subtract => InstructionCode::SUBTRACT,
52            BinaryOperator::Multiply => InstructionCode::MULTIPLY,
53            BinaryOperator::Divide => InstructionCode::DIVIDE,
54            BinaryOperator::Modulo => InstructionCode::MODULO,
55            BinaryOperator::Power => InstructionCode::POWER,
56            BinaryOperator::And => InstructionCode::AND,
57            BinaryOperator::Or => InstructionCode::OR,
58            BinaryOperator::StructuralEqual => {
59                InstructionCode::STRUCTURAL_EQUAL
60            }
61            BinaryOperator::Equal => InstructionCode::EQUAL,
62            BinaryOperator::NotStructuralEqual => {
63                InstructionCode::NOT_STRUCTURAL_EQUAL
64            }
65            BinaryOperator::NotEqual => InstructionCode::NOT_EQUAL,
66            BinaryOperator::Is => InstructionCode::IS,
67            operator => todo!(
68                "Binary operator {:?} not implemented for InstructionCode",
69                operator
70            ),
71        }
72    }
73}
74
75impl From<BinaryOperator> for InstructionCode {
76    fn from(op: BinaryOperator) -> Self {
77        InstructionCode::from(&op)
78    }
79}
80
81impl From<&InstructionCode> for BinaryOperator {
82    fn from(code: &InstructionCode) -> Self {
83        match code {
84            InstructionCode::ADD => BinaryOperator::Add,
85            InstructionCode::SUBTRACT => BinaryOperator::Subtract,
86            InstructionCode::MULTIPLY => BinaryOperator::Multiply,
87            InstructionCode::DIVIDE => BinaryOperator::Divide,
88            InstructionCode::MODULO => BinaryOperator::Modulo,
89            InstructionCode::POWER => BinaryOperator::Power,
90            InstructionCode::AND => BinaryOperator::And,
91            InstructionCode::OR => BinaryOperator::Or,
92            InstructionCode::STRUCTURAL_EQUAL => {
93                BinaryOperator::StructuralEqual
94            }
95            InstructionCode::EQUAL => BinaryOperator::Equal,
96            InstructionCode::NOT_STRUCTURAL_EQUAL => {
97                BinaryOperator::NotStructuralEqual
98            }
99            InstructionCode::NOT_EQUAL => BinaryOperator::NotEqual,
100            InstructionCode::IS => BinaryOperator::Is,
101            _ => todo!("#154 Binary operator for {:?} not implemented", code),
102        }
103    }
104}
105
106impl From<InstructionCode> for BinaryOperator {
107    fn from(code: InstructionCode) -> Self {
108        BinaryOperator::from(&code)
109    }
110}
111
112impl From<&Instruction> for BinaryOperator {
113    fn from(instruction: &Instruction) -> Self {
114        match instruction {
115            Instruction::Add => BinaryOperator::Add,
116            Instruction::Subtract => BinaryOperator::Subtract,
117            Instruction::Multiply => BinaryOperator::Multiply,
118            Instruction::Divide => BinaryOperator::Divide,
119            Instruction::StructuralEqual => BinaryOperator::StructuralEqual,
120            Instruction::Equal => BinaryOperator::Equal,
121            Instruction::NotStructuralEqual => {
122                BinaryOperator::NotStructuralEqual
123            }
124            Instruction::NotEqual => BinaryOperator::NotEqual,
125            Instruction::Is => BinaryOperator::Is,
126            _ => {
127                todo!("#155 Binary operator for instruction {:?} not implemented", instruction);
128            }
129        }
130    }
131}
132
133impl From<Instruction> for BinaryOperator {
134    fn from(instruction: Instruction) -> Self {
135        BinaryOperator::from(&instruction)
136    }
137}
138
139#[derive(Clone, Debug, PartialEq, Copy)]
140pub enum UnaryOperator {
141    Negate,
142    CreateRef,
143}
144
145#[derive(Clone, Debug, PartialEq)]
146pub struct Statement {
147    pub expression: DatexExpression,
148    pub is_terminated: bool,
149}
150
151#[derive(Clone, Debug, PartialEq)]
152pub enum Apply {
153    /// Apply a function to an argument
154    FunctionCall(DatexExpression),
155    /// Apply a property access to an argument
156    PropertyAccess(DatexExpression),
157}
158
159#[derive(Clone, Copy, Debug, PartialEq)]
160pub enum VariableType {
161    Const,
162    Var,
163}
164
165#[derive(Clone, Copy, Debug, PartialEq)]
166pub enum VariableMutType {
167    Mutable,
168    Immutable,
169}
170
171#[derive(Clone, Debug, PartialEq)]
172pub enum Slot {
173    Addressed(u32),
174    Named(String),
175}
176
177pub type VariableId = usize;
178
179#[derive(Clone, Debug, PartialEq)]
180pub enum DatexExpression {
181    /// Invalid expression, e.g. syntax error
182    Invalid,
183
184    /// null
185    Null,
186    /// Boolean (true or false)
187    Boolean(bool),
188    /// Text, e.g "Hello, world!"
189    Text(String),
190    /// Decimal, e.g 123.456789123456
191    Decimal(Decimal),
192    /// Integer, e.g 123456789123456789
193    Integer(Integer),
194    /// Endpoint, e.g. @test_a or @test_b
195    Endpoint(Endpoint),
196    /// Array, e.g  `[1, 2, 3, "text"]`
197    Array(Vec<DatexExpression>),
198    /// Object, e.g {"key": "value", key2: 2}
199    Object(Vec<(DatexExpression, DatexExpression)>),
200    /// Tuple, e.g (1: 2, 3: 4, "xy") or without brackets: 1,2,a:3
201    Tuple(Vec<TupleEntry>),
202    /// One or more statements, e.g (1; 2; 3)
203    Statements(Vec<Statement>),
204    /// Identifier, e.g. a variable name. VariableId is always set to 0 by the ast parser.
205    Variable(Option<VariableId>, String),
206    /// Variable declaration, e.g. const x = 1, const mut x = 1, or var y = 2. VariableId is always set to 0 by the ast parser.
207    VariableDeclaration(Option<VariableId>, VariableType, VariableMutType, String, Box<DatexExpression>),
208    /// Variable assignment, e.g. x = 1. VariableId is always set to 0 by the ast parser.
209    VariableAssignment(Option<VariableId>, String, Box<DatexExpression>),
210
211    /// Slot, e.g. #1, #endpoint
212    Slot(Slot),
213    /// Slot assignment
214    SlotAssignment(Slot, Box<DatexExpression>),
215
216    BinaryOperation(BinaryOperator, Box<DatexExpression>, Box<DatexExpression>),
217    UnaryOperation(UnaryOperator, Box<DatexExpression>),
218
219    // apply (e.g. x (1)) or property access
220    ApplyChain(Box<DatexExpression>, Vec<Apply>),
221    // ?
222    Placeholder,
223    // @xy :: z
224    RemoteExecution(Box<DatexExpression>, Box<DatexExpression>),
225}
226
227// directly convert DatexExpression to a ValueContainer
228impl TryFrom<DatexExpression> for ValueContainer {
229    type Error = ();
230
231    fn try_from(expr: DatexExpression) -> Result<Self, Self::Error> {
232        Ok(match expr {
233            DatexExpression::Null => ValueContainer::Value(Value::null()),
234            DatexExpression::Boolean(b) => ValueContainer::from(b),
235            DatexExpression::Text(s) => ValueContainer::from(s),
236            DatexExpression::Decimal(d) => ValueContainer::from(d),
237            DatexExpression::Integer(i) => ValueContainer::from(i),
238            DatexExpression::Endpoint(e) => ValueContainer::from(e),
239            DatexExpression::Array(arr) => {
240                let entries = arr
241                    .into_iter()
242                    .map(ValueContainer::try_from)
243                    .collect::<Result<Vec<ValueContainer>, ()>>()?;
244                ValueContainer::from(Array::from(entries))
245            }
246            DatexExpression::Object(obj) => {
247                let entries = obj
248                    .into_iter()
249                    .map(|(k, v)| {
250                        let key = match k {
251                            DatexExpression::Text(s) => s,
252                            _ => Err(())?,
253                        };
254                        let value = ValueContainer::try_from(v)?;
255                        Ok((key, value))
256                    })
257                    .collect::<Result<HashMap<String, ValueContainer>, ()>>()?;
258                ValueContainer::from(Object::from(entries))
259            }
260            _ => Err(())?,
261        })
262    }
263}
264
265pub type DatexScriptParser<'a> =
266    Boxed<'a, 'a, TokenInput<'a>, DatexExpression, Err<Rich<'a, Token>>>;
267
268fn decode_json_unicode_escapes(input: &str) -> String {
269    let mut output = String::new();
270    let mut chars = input.chars().peekable();
271
272    while let Some(ch) = chars.next() {
273        if ch == '\\' && chars.peek() == Some(&'u') {
274            chars.next(); // skip 'u'
275
276            let mut code_unit = String::new();
277            for _ in 0..4 {
278                if let Some(c) = chars.next() {
279                    code_unit.push(c);
280                } else {
281                    output.push_str("\\u");
282                    output.push_str(&code_unit);
283                    break;
284                }
285            }
286
287            if let Ok(first_unit) = u16::from_str_radix(&code_unit, 16) {
288                if (0xD800..=0xDBFF).contains(&first_unit) {
289                    // High surrogate — look for low surrogate
290                    if chars.next() == Some('\\') && chars.next() == Some('u') {
291                        let mut low_code = String::new();
292                        for _ in 0..4 {
293                            if let Some(c) = chars.next() {
294                                low_code.push(c);
295                            } else {
296                                output.push_str(&format!(
297                                    "\\u{first_unit:04X}\\u{low_code}"
298                                ));
299                                break;
300                            }
301                        }
302
303                        if let Ok(second_unit) =
304                            u16::from_str_radix(&low_code, 16)
305                            && (0xDC00..=0xDFFF).contains(&second_unit)
306                        {
307                            let combined = 0x10000
308                                + (((first_unit - 0xD800) as u32) << 10)
309                                + ((second_unit - 0xDC00) as u32);
310                            if let Some(c) = char::from_u32(combined) {
311                                output.push(c);
312                                continue;
313                            }
314                        }
315
316                        // Invalid surrogate fallback
317                        output.push_str(&format!(
318                            "\\u{first_unit:04X}\\u{low_code}"
319                        ));
320                    } else {
321                        // Unpaired high surrogate
322                        output.push_str(&format!("\\u{first_unit:04X}"));
323                    }
324                } else {
325                    // Normal scalar value
326                    if let Some(c) = char::from_u32(first_unit as u32) {
327                        output.push(c);
328                    } else {
329                        output.push_str(&format!("\\u{first_unit:04X}"));
330                    }
331                }
332            } else {
333                output.push_str(&format!("\\u{code_unit}"));
334            }
335        } else {
336            output.push(ch);
337        }
338    }
339
340    output
341}
342
343/// Takes a literal text string input, e.g. ""Hello, world!"" or "'Hello, world!' or ""x\"""
344/// and returns the unescaped text, e.g. "Hello, world!" or 'Hello, world!' or "x\""
345fn unescape_text(text: &str) -> String {
346    // remove first and last quote (double or single)
347    let escaped = text[1..text.len() - 1]
348        // Replace escape sequences with actual characters
349        .replace(r#"\""#, "\"") // Replace \" with "
350        .replace(r#"\'"#, "'") // Replace \' with '
351        .replace(r#"\n"#, "\n") // Replace \n with newline
352        .replace(r#"\r"#, "\r") // Replace \r with carriage return
353        .replace(r#"\t"#, "\t") // Replace \t with tab
354        .replace(r#"\b"#, "\x08") // Replace \b with backspace
355        .replace(r#"\f"#, "\x0C") // Replace \f with form feed
356        .replace(r#"\\"#, "\\") // Replace \\ with \
357        // TODO #156 remove all other backslashes before any other character
358        .to_string();
359    // Decode unicode escapes, e.g. \u1234 or \uD800\uDC00
360    decode_json_unicode_escapes(&escaped)
361}
362
363fn binary_op(
364    op: BinaryOperator,
365) -> impl Fn(Box<DatexExpression>, Box<DatexExpression>) -> DatexExpression + Clone
366{
367    move |lhs, rhs| DatexExpression::BinaryOperation(op, lhs, rhs)
368}
369
370pub struct DatexParseResult {
371    pub expression: DatexExpression,
372    pub is_static_value: bool,
373}
374
375pub fn create_parser<'a, I>()
376-> impl Parser<'a, TokenInput<'a>, DatexExpression, Err<Cheap>>
377// where
378//     I: SliceInput<'a, Token = Token, Span = SimpleSpan>,
379{
380    // an expression
381    let mut expression = Recursive::declare();
382    let mut expression_without_tuple = Recursive::declare();
383
384    let whitespace = just(Token::Whitespace).repeated().ignored();
385
386    // a sequence of expressions, separated by semicolons, optionally terminated with a semicolon
387    let statements = expression
388        .clone()
389        .then_ignore(
390            just(Token::Semicolon)
391                .padded_by(whitespace.clone())
392                .repeated()
393                .at_least(1),
394        )
395        .repeated()
396        .collect::<Vec<_>>()
397        .then(
398            expression
399                .clone()
400                .then(
401                    just(Token::Semicolon)
402                        .padded_by(whitespace.clone())
403                        .or_not(),
404                )
405                .or_not(), // Final expression with optional semicolon
406        )
407        .map(|(exprs, last)| {
408            // Convert expressions with mandatory semicolon
409            let mut statements: Vec<Statement> = exprs
410                .into_iter()
411                .map(|expr| Statement {
412                    expression: expr,
413                    is_terminated: true,
414                })
415                .collect();
416
417            if let Some((last_expr, last_semi)) = last {
418                // If there's a last expression, add it as a statement
419                statements.push(Statement {
420                    expression: last_expr,
421                    is_terminated: last_semi.is_some(),
422                });
423            }
424            // if single statement without semicolon, treat it as a single expression
425            if statements.len() == 1 && !statements[0].is_terminated {
426                statements.remove(0).expression
427            } else {
428                DatexExpression::Statements(statements)
429            }
430        })
431        .boxed();
432
433    // primitive values (e.g. 1, "text", true, null)
434    let integer = select! {
435        Token::IntegerLiteral(s) => DatexExpression::Integer(Integer::from_string(&s).unwrap()),
436        Token::BinaryIntegerLiteral(s) => DatexExpression::Integer(Integer::from_string_radix(&s[2..], 2).unwrap()),
437        Token::HexadecimalIntegerLiteral(s) => DatexExpression::Integer(Integer::from_string_radix(&s[2..], 16).unwrap()),
438        Token::OctalIntegerLiteral(s) => DatexExpression::Integer(Integer::from_string_radix(&s[2..], 8).unwrap()),
439    };
440    let decimal = select! {
441        Token::DecimalLiteral(s) => DatexExpression::Decimal(Decimal::from_string(&s)),
442        Token::NanLiteral => DatexExpression::Decimal(Decimal::NaN),
443        Token::InfinityLiteral(s) => DatexExpression::Decimal(
444            if s.starts_with('-') {
445                Decimal::NegInfinity
446            } else {
447                Decimal::Infinity
448            }
449        ),
450        Token::FractionLiteral(s) => DatexExpression::Decimal(Decimal::from_string(&s)),
451    };
452    let text = select! {
453        Token::StringLiteral(s) => DatexExpression::Text(unescape_text(&s))
454    };
455    let endpoint = select! {
456        Token::Endpoint(s) =>
457            match Endpoint::from_str(s.as_str()) {
458                Err(_) => DatexExpression::Invalid,
459                Ok(endpoint) => DatexExpression::Endpoint(endpoint)
460        }
461    };
462    let literal = select! {
463        Token::TrueKW => DatexExpression::Boolean(true),
464        Token::FalseKW => DatexExpression::Boolean(false),
465        Token::NullKW => DatexExpression::Null,
466        Token::Identifier(s) => DatexExpression::Variable(None, s),
467        Token::NamedSlot(s) => DatexExpression::Slot(Slot::Named(s[1..].to_string())),
468        Token::Slot(s) => DatexExpression::Slot(Slot::Addressed(
469            // replace first char (#) and convert to u32
470            s[1..].parse::<u32>().unwrap()
471        )),
472        Token::PlaceholderKW => DatexExpression::Placeholder,
473    };
474    // expression wrapped in parentheses
475    let wrapped_expression = statements
476        .clone()
477        .delimited_by(just(Token::LeftParen), just(Token::RightParen));
478
479    // a valid object/tuple key
480    // (1: value), "key", 1, (("x"+"y"): 123)
481    let key = choice((
482        text,
483        decimal,
484        integer,
485        endpoint,
486        // any valid identifiers (equivalent to variable names), mapped to a text
487        select! {
488            Token::Identifier(s) => DatexExpression::Text(s)
489        },
490        // dynamic key
491        wrapped_expression.clone(),
492    ));
493
494    // array
495    // 1,2,3
496    // [1,2,3,4,13434,(1),4,5,7,8]
497    let array = expression_without_tuple
498        .clone()
499        .separated_by(just(Token::Comma).padded_by(whitespace.clone()))
500        .at_least(0)
501        .allow_trailing()
502        .collect()
503        .padded_by(whitespace.clone())
504        .delimited_by(just(Token::LeftBracket), just(Token::RightBracket))
505        .map(DatexExpression::Array);
506
507    // object
508    let object = key
509        .clone()
510        .then_ignore(just(Token::Colon).padded_by(whitespace.clone()))
511        .then(expression_without_tuple.clone())
512        .separated_by(just(Token::Comma).padded_by(whitespace.clone()))
513        .at_least(0)
514        .allow_trailing()
515        .collect()
516        .padded_by(whitespace.clone())
517        .delimited_by(just(Token::LeftCurly), just(Token::RightCurly))
518        .map(DatexExpression::Object);
519
520    // tuple
521    // Key-value pair
522    let tuple_key_value_pair = key
523        .clone()
524        .then_ignore(just(Token::Colon).padded_by(whitespace.clone()))
525        .then(expression_without_tuple.clone())
526        .map(|(key, value)| TupleEntry::KeyValue(key, value));
527
528    // tuple (either key:value entries or just values)
529    let tuple_entry = choice((
530        // Key-value pair
531        tuple_key_value_pair.clone(),
532        // Just a value with no key
533        expression_without_tuple.clone().map(TupleEntry::Value),
534    ))
535    .boxed();
536
537    let tuple = tuple_entry
538        .clone()
539        .separated_by(just(Token::Comma).padded_by(whitespace.clone()))
540        .at_least(2)
541        .collect::<Vec<_>>()
542        .map(DatexExpression::Tuple);
543
544    // e.g. x,
545    let single_value_tuple = tuple_entry
546        .clone()
547        .then_ignore(just(Token::Comma))
548        .map(|value| vec![value])
549        .map(DatexExpression::Tuple);
550
551    // e.g. (a:1)
552    let single_keyed_tuple_entry = tuple_key_value_pair
553        .clone()
554        .map(|value| vec![value])
555        .map(DatexExpression::Tuple);
556
557    let tuple = choice((tuple, single_value_tuple, single_keyed_tuple_entry));
558
559    // atomic expression (e.g. 1, "text", (1 + 2), (1;2))
560    let atom = choice((
561        array.clone(),
562        object.clone(),
563        literal,
564        decimal,
565        integer,
566        text,
567        endpoint,
568        wrapped_expression.clone(),
569    ))
570    .boxed();
571
572    // operations on atoms
573    let op = |c| {
574        just(Token::Whitespace)
575            .repeated()
576            .at_least(1)
577            .ignore_then(just(c))
578            .then_ignore(just(Token::Whitespace).repeated().at_least(1))
579    };
580
581    // apply chain: two expressions following each other directly, optionally separated with "." (property access)
582    let apply_or_property_access = atom
583        .clone()
584        .then(
585            choice((
586                // apply #1: a wrapped expression, array, or object - no whitespace required before
587                // x () x [] x {}
588                choice((
589                    wrapped_expression.clone(),
590                    array.clone(),
591                    object.clone(),
592                ))
593                .clone()
594                .padded_by(whitespace.clone())
595                .map(Apply::FunctionCall),
596                // apply #2: an atomic value (e.g. "text") - whitespace or newline required before
597                // print "sdf"
598                just(Token::Whitespace)
599                    .repeated()
600                    .at_least(1)
601                    .ignore_then(atom.clone().padded_by(whitespace.clone()))
602                    .map(Apply::FunctionCall),
603                // property access
604                just(Token::Dot)
605                    .padded_by(whitespace.clone())
606                    .ignore_then(key.clone())
607                    .map(Apply::PropertyAccess),
608            ))
609            .repeated()
610            .collect::<Vec<_>>(),
611        )
612        .map(|(val, args)| {
613            // if only single value, return it directly
614            if args.is_empty() {
615                val
616            } else {
617                DatexExpression::ApplyChain(Box::new(val), args)
618            }
619        });
620
621    let product = apply_or_property_access.clone().foldl(
622        choice((
623            op(Token::Star).to(binary_op(BinaryOperator::Multiply)),
624            op(Token::Slash).to(binary_op(BinaryOperator::Divide)),
625        ))
626        .then(apply_or_property_access)
627        .repeated(),
628        |lhs, (op, rhs)| op(Box::new(lhs), Box::new(rhs)),
629    );
630
631    let sum = product.clone().foldl(
632        choice((
633            op(Token::Plus).to(binary_op(BinaryOperator::Add)),
634            op(Token::Minus).to(binary_op(BinaryOperator::Subtract)),
635        ))
636        .then(product)
637        .repeated(),
638        |lhs, (op, rhs)| op(Box::new(lhs), Box::new(rhs)),
639    );
640
641    // equality
642    let equality = sum.clone().foldl(
643        choice((
644            op(Token::StructuralEqual) //  ==
645                .to(binary_op(BinaryOperator::StructuralEqual)),
646            op(Token::Equal) //  ===
647                .to(binary_op(BinaryOperator::Equal)),
648            op(Token::NotStructuralEqual) //  !=
649                .to(binary_op(BinaryOperator::NotStructuralEqual)),
650            op(Token::NotEqual) //  !==
651                .to(binary_op(BinaryOperator::NotEqual)),
652            op(Token::Is) //  is
653                .to(binary_op(BinaryOperator::Is)),
654            // op(Token::LessThan) //  <
655            //     .to(binary_op(BinaryOperator::LessThan)),
656            // op(Token::GreaterThan) //  >
657            //     .to(binary_op(BinaryOperator::GreaterThan)),
658            // op(Token::LessThanOrEqual) //  <=
659            //     .to(binary_op(BinaryOperator::LessThanOrEqual)),
660            // op(Token::GreaterThanOrEqual) //  >=
661            //     .to(binary_op(BinaryOperator::GreaterThanOrEqual)),
662        ))
663        .then(sum)
664        .repeated(), // allows chaining like a == b == c
665        |lhs, (op, rhs)| op(Box::new(lhs), Box::new(rhs)),
666    );
667
668    // variable declarations or assignments
669    let variable_assignment = just(Token::ConstKW)
670        .or(just(Token::VarKW))
671        .or_not()
672        .padded_by(whitespace.clone())
673        // optional MutKW
674        .then(just(Token::MutKW).or_not().padded_by(whitespace.clone()))
675        .then(select! {
676            Token::Identifier(s) => s
677        })
678        .then_ignore(just(Token::Assign).padded_by(whitespace.clone()))
679        .then(equality.clone())
680        .map(|(((var_type, mut_type), var_name), expr)| {
681            if let Some(var_type) = var_type {
682                DatexExpression::VariableDeclaration(
683                    None,
684                    if var_type == Token::ConstKW {
685                        VariableType::Const
686                    } else {
687                        VariableType::Var
688                    },
689                    if mut_type.is_some() {
690                        VariableMutType::Mutable
691                    } else {
692                        VariableMutType::Immutable
693                    },
694                    var_name.to_string(),
695                    Box::new(expr),
696                )
697            } else {
698                DatexExpression::VariableAssignment(
699                    None,
700                    var_name.to_string(),
701                    Box::new(expr),
702                )
703            }
704        });
705
706    expression_without_tuple
707        .define(choice((variable_assignment, equality.clone())));
708
709    // expression :: expression
710    let remote_execution = expression_without_tuple
711        .clone()
712        .then_ignore(just(Token::DoubleColon).padded_by(whitespace.clone()))
713        .then(expression_without_tuple.clone())
714        .map(|(endpoint, expr)| {
715            DatexExpression::RemoteExecution(Box::new(endpoint), Box::new(expr))
716        });
717
718    expression.define(
719        choice((
720            remote_execution,
721            tuple.clone(),
722            expression_without_tuple.clone(),
723        ))
724        .padded_by(whitespace.clone()),
725    );
726
727    choice((
728        // empty script (0-n semicolons)
729        just(Token::Semicolon)
730            .repeated()
731            .at_least(1)
732            .padded_by(whitespace.clone())
733            .map(|_| DatexExpression::Statements(vec![])),
734        // statements
735        statements,
736    ))
737}
738
739type TokenInput<'a> = &'a [Token];
740
741#[derive(Debug)]
742pub enum ParserError {
743    UnexpectedToken(Range<usize>),
744    InvalidToken(Range<usize>),
745}
746
747impl From<Range<usize>> for ParserError {
748    fn from(range: Range<usize>) -> Self {
749        ParserError::InvalidToken(range)
750    }
751}
752
753pub fn parse(mut src: &str) -> Result<DatexExpression, Vec<ParserError>> {
754    // strip shebang at beginning of the source code
755    if src.starts_with("#!") {
756        let end_of_line = src.find('\n').unwrap_or(src.len());
757        src = &src[end_of_line + 1..];
758    }
759
760    let tokens = Token::lexer(src);
761    let tokens:Vec<Token> = tokens.into_iter().collect::<Result<Vec<Token>, Range<usize>>>().map_err(|e|
762        vec![ParserError::InvalidToken(e)]
763    )?;
764
765    let parser = create_parser::<'_, TokenInput>();
766
767    parser.parse(&tokens).into_result().map_err(|err| {
768        err.into_iter()
769            .map(|e| ParserError::UnexpectedToken(e.span().into_range()))
770            .collect()
771    })
772}
773
774// TODO #157: implement correctly - have fun with lifetimes :()
775// mainly relevant for IDE language support
776// pub fn parse_with_context(src: &str, parser) -> (DatexExpression, Vec<ParserError>) {
777//     let lexer = Token::lexer(src);
778//     let tokens = lexer.spanned().map(|(tok, span)| match tok {
779//         Ok(tok) => (tok, span.into()),
780//         Err(_) => (Token::Error, span.into()),
781//     });
782//     let tokens = Stream::from_iter(tokens)
783//         .map((0..src.len()).into(), |(t, s): (_, _)| (t, s));
784
785//     let result = parser.parse(tokens).into_result().map_err(|err| {
786//         err.into_iter()
787//             .map(|e| ParserError::UnexpectedToken(e.span().into_range()))
788//             .collect()
789//     });
790//     result
791// }
792
793#[cfg(test)]
794mod tests {
795
796    use super::*;
797
798    use std::assert_matches::assert_matches;
799
800    fn print_report(errs: Vec<ParserError>, src: &str) {
801        // FIXME #158
802        eprintln!("{errs:?}");
803        // errs.into_iter().for_each(|e| {
804        //     Report::build(ReportKind::Error, ((), e.span().into_range()))
805        //         .with_config(
806        //             ariadne::Config::new()
807        //                 .with_index_type(ariadne::IndexType::Byte),
808        //         )
809        //         .with_message(e.to_string())
810        //         .with_label(
811        //             Label::new(((), e.span().into_range()))
812        //                 .with_color(Color::Red),
813        //         )
814        //         .finish()
815        //         .eprint(Source::from(&src))
816        //         .unwrap()
817        // });
818    }
819
820    fn parse_unwrap(src: &str) -> DatexExpression {
821        let res = parse(src);
822        if res.is_err() {
823            print_report(res.unwrap_err(), src);
824            panic!("Parsing errors found");
825        }
826        res.unwrap()
827    }
828
829    fn try_parse_to_value_container(src: &str) -> ValueContainer {
830        let expr = parse_unwrap(src);
831        ValueContainer::try_from(expr).unwrap_or_else(|_| {
832            panic!("Failed to convert expression to ValueContainer")
833        })
834    }
835
836    #[test]
837    fn test_json() {
838        let src = r#"
839            {
840                "name": "Test",
841                "value": 42,
842                "active": true,
843                "items": [1, 2, 3, 0.5],
844                "nested": {
845                    "key": "value"
846                }
847            }
848        "#;
849
850        let json = parse_unwrap(src);
851
852        assert_eq!(
853            json,
854            DatexExpression::Object(vec![
855                (
856                    DatexExpression::Text("name".to_string()),
857                    DatexExpression::Text("Test".to_string())
858                ),
859                (
860                    DatexExpression::Text("value".to_string()),
861                    DatexExpression::Integer(Integer::from(42))
862                ),
863                (
864                    DatexExpression::Text("active".to_string()),
865                    DatexExpression::Boolean(true)
866                ),
867                (
868                    DatexExpression::Text("items".to_string()),
869                    DatexExpression::Array(vec![
870                        DatexExpression::Integer(Integer::from(1)),
871                        DatexExpression::Integer(Integer::from(2)),
872                        DatexExpression::Integer(Integer::from(3)),
873                        DatexExpression::Decimal(Decimal::from_string("0.5"))
874                    ])
875                ),
876                (
877                    DatexExpression::Text("nested".to_string()),
878                    DatexExpression::Object(
879                        vec![(
880                            DatexExpression::Text("key".to_string()),
881                            DatexExpression::Text("value".to_string())
882                        )]
883                        .into_iter()
884                        .collect()
885                    )
886                ),
887            ])
888        );
889    }
890
891    #[test]
892    fn test_equal_operators() {
893        let src = "3 == 1 + 2";
894        let val = parse_unwrap(src);
895        assert_eq!(
896            val,
897            DatexExpression::BinaryOperation(
898                BinaryOperator::StructuralEqual,
899                Box::new(DatexExpression::Integer(Integer::from(3))),
900                Box::new(DatexExpression::BinaryOperation(
901                    BinaryOperator::Add,
902                    Box::new(DatexExpression::Integer(Integer::from(1))),
903                    Box::new(DatexExpression::Integer(Integer::from(2)))
904                ))
905            )
906        );
907
908        let src = "3 === 1 + 2";
909        let val = parse_unwrap(src);
910        assert_eq!(
911            val,
912            DatexExpression::BinaryOperation(
913                BinaryOperator::Equal,
914                Box::new(DatexExpression::Integer(Integer::from(3))),
915                Box::new(DatexExpression::BinaryOperation(
916                    BinaryOperator::Add,
917                    Box::new(DatexExpression::Integer(Integer::from(1))),
918                    Box::new(DatexExpression::Integer(Integer::from(2)))
919                ))
920            )
921        );
922
923        let src = "5 != 1 + 2";
924        let val = parse_unwrap(src);
925        assert_eq!(
926            val,
927            DatexExpression::BinaryOperation(
928                BinaryOperator::NotStructuralEqual,
929                Box::new(DatexExpression::Integer(Integer::from(5))),
930                Box::new(DatexExpression::BinaryOperation(
931                    BinaryOperator::Add,
932                    Box::new(DatexExpression::Integer(Integer::from(1))),
933                    Box::new(DatexExpression::Integer(Integer::from(2)))
934                ))
935            )
936        );
937        let src = "5 !== 1 + 2";
938        let val = parse_unwrap(src);
939        assert_eq!(
940            val,
941            DatexExpression::BinaryOperation(
942                BinaryOperator::NotEqual,
943                Box::new(DatexExpression::Integer(Integer::from(5))),
944                Box::new(DatexExpression::BinaryOperation(
945                    BinaryOperator::Add,
946                    Box::new(DatexExpression::Integer(Integer::from(1))),
947                    Box::new(DatexExpression::Integer(Integer::from(2)))
948                ))
949            )
950        );
951
952        let src = "5 is 1 + 2";
953        let val = parse_unwrap(src);
954        assert_eq!(
955            val,
956            DatexExpression::BinaryOperation(
957                BinaryOperator::Is,
958                Box::new(DatexExpression::Integer(Integer::from(5))),
959                Box::new(DatexExpression::BinaryOperation(
960                    BinaryOperator::Add,
961                    Box::new(DatexExpression::Integer(Integer::from(1))),
962                    Box::new(DatexExpression::Integer(Integer::from(2)))
963                ))
964            )
965        );
966    }
967
968    #[test]
969    fn test_null() {
970        let src = "null";
971        let val = parse_unwrap(src);
972        assert_eq!(val, DatexExpression::Null);
973    }
974
975    #[test]
976    fn test_boolean() {
977        let src_true = "true";
978        let val_true = parse_unwrap(src_true);
979        assert_eq!(val_true, DatexExpression::Boolean(true));
980
981        let src_false = "false";
982        let val_false = parse_unwrap(src_false);
983        assert_eq!(val_false, DatexExpression::Boolean(false));
984    }
985
986    #[test]
987    fn test_integer() {
988        let src = "123456789123456789";
989        let num = parse_unwrap(src);
990        assert_eq!(
991            num,
992            DatexExpression::Integer(
993                Integer::from_string("123456789123456789").unwrap()
994            )
995        );
996    }
997
998    #[test]
999    fn test_negative_integer() {
1000        let src = "-123456789123456789";
1001        let num = parse_unwrap(src);
1002        assert_eq!(
1003            num,
1004            DatexExpression::Integer(
1005                Integer::from_string("-123456789123456789").unwrap()
1006            )
1007        );
1008    }
1009
1010    #[test]
1011    fn test_integer_with_underscores() {
1012        let src = "123_456";
1013        let num = parse_unwrap(src);
1014        assert_eq!(
1015            num,
1016            DatexExpression::Integer(Integer::from_string("123456").unwrap())
1017        );
1018    }
1019
1020    #[test]
1021    fn test_hex_integer() {
1022        let src = "0x1A2B3C4D5E6F";
1023        let num = parse_unwrap(src);
1024        assert_eq!(
1025            num,
1026            DatexExpression::Integer(
1027                Integer::from_string_radix("1A2B3C4D5E6F", 16).unwrap()
1028            )
1029        );
1030    }
1031
1032    #[test]
1033    fn test_octal_integer() {
1034        let src = "0o755";
1035        let num = parse_unwrap(src);
1036        assert_eq!(
1037            num,
1038            DatexExpression::Integer(
1039                Integer::from_string_radix("755", 8).unwrap()
1040            )
1041        );
1042    }
1043
1044    #[test]
1045    fn test_binary_integer() {
1046        let src = "0b101010";
1047        let num = parse_unwrap(src);
1048        assert_eq!(
1049            num,
1050            DatexExpression::Integer(
1051                Integer::from_string_radix("101010", 2).unwrap()
1052            )
1053        );
1054    }
1055
1056    #[test]
1057    fn test_integer_with_exponent() {
1058        let src = "2e10";
1059        let num = parse_unwrap(src);
1060        assert_eq!(
1061            num,
1062            DatexExpression::Decimal(Decimal::from_string("20000000000"))
1063        );
1064    }
1065
1066    #[test]
1067    fn test_decimal() {
1068        let src = "123.456789123456";
1069        let num = parse_unwrap(src);
1070        assert_eq!(
1071            num,
1072            DatexExpression::Decimal(Decimal::from_string("123.456789123456"))
1073        );
1074    }
1075
1076    #[test]
1077    fn test_decimal_with_separator() {
1078        let cases = [
1079            ("123_45_6.789", "123456.789"),
1080            ("123.443_3434", "123.4433434"),
1081            ("1_000.000_001", "1000.000001"),
1082            ("3.14_15e+1_0", "31415000000.0"),
1083            ("0.0_0_1", "0.001"),
1084            ("+1_000.0", "1000.0"),
1085        ];
1086
1087        for (src, expected_str) in cases {
1088            let num = parse_unwrap(src);
1089            assert_eq!(
1090                num,
1091                DatexExpression::Decimal(Decimal::from_string(expected_str)),
1092                "Failed to parse: {src}"
1093            );
1094        }
1095    }
1096
1097    #[test]
1098    fn test_negative_decimal() {
1099        let src = "-123.4";
1100        let num = parse_unwrap(src);
1101        assert_eq!(
1102            num,
1103            DatexExpression::Decimal(Decimal::from_string("-123.4"))
1104        );
1105    }
1106
1107    #[test]
1108    fn test_decimal_with_exponent() {
1109        let src = "1.23456789123456e2";
1110        let num = parse_unwrap(src);
1111        assert_eq!(
1112            num,
1113            DatexExpression::Decimal(Decimal::from_string("123.456789123456"))
1114        );
1115    }
1116
1117    #[test]
1118    fn test_decimal_with_negative_exponent() {
1119        let src = "1.23456789123456e-2";
1120        let num = parse_unwrap(src);
1121        assert_eq!(
1122            num,
1123            DatexExpression::Decimal(Decimal::from_string(
1124                "0.0123456789123456"
1125            ))
1126        );
1127    }
1128
1129    #[test]
1130    fn test_decimal_with_positive_exponent() {
1131        let src = "1.23456789123456E+2";
1132        let num = parse_unwrap(src);
1133        assert_eq!(
1134            num,
1135            DatexExpression::Decimal(Decimal::from_string("123.456789123456"))
1136        );
1137    }
1138
1139    #[test]
1140    fn test_decimal_with_trailing_point() {
1141        let src = "123.";
1142        let num = parse_unwrap(src);
1143        assert_eq!(
1144            num,
1145            DatexExpression::Decimal(Decimal::from_string("123.0"))
1146        );
1147    }
1148
1149    #[test]
1150    fn test_decimal_with_leading_point() {
1151        let src = ".456789123456";
1152        let num = parse_unwrap(src);
1153        assert_eq!(
1154            num,
1155            DatexExpression::Decimal(Decimal::from_string("0.456789123456"))
1156        );
1157
1158        let src = ".423e-2";
1159        let num = parse_unwrap(src);
1160        assert_eq!(
1161            num,
1162            DatexExpression::Decimal(Decimal::from_string("0.00423"))
1163        );
1164    }
1165
1166    #[test]
1167    fn test_text_double_quotes() {
1168        let src = r#""Hello, world!""#;
1169        let text = parse_unwrap(src);
1170        assert_eq!(text, DatexExpression::Text("Hello, world!".to_string()));
1171    }
1172
1173    #[test]
1174    fn test_text_single_quotes() {
1175        let src = r#"'Hello, world!'"#;
1176        let text = parse_unwrap(src);
1177        assert_eq!(text, DatexExpression::Text("Hello, world!".to_string()));
1178    }
1179
1180    #[test]
1181    fn test_text_escape_sequences() {
1182        let src =
1183            r#""Hello, \"world\"! \n New line \t tab \uD83D\uDE00 \u2764""#;
1184        let text = parse_unwrap(src);
1185
1186        assert_eq!(
1187            text,
1188            DatexExpression::Text(
1189                "Hello, \"world\"! \n New line \t tab 😀 ❤".to_string()
1190            )
1191        );
1192    }
1193
1194    #[test]
1195    fn test_text_escape_sequences_2() {
1196        let src =
1197            r#""\u0048\u0065\u006C\u006C\u006F, \u2764\uFE0F, \uD83D\uDE00""#;
1198        let text = parse_unwrap(src);
1199        assert_eq!(text, DatexExpression::Text("Hello, ❤️, 😀".to_string()));
1200    }
1201
1202    #[test]
1203    fn test_text_nested_escape_sequences() {
1204        let src = r#""\\\\""#;
1205        let text = parse_unwrap(src);
1206        assert_eq!(text, DatexExpression::Text("\\\\".to_string()));
1207    }
1208
1209    #[test]
1210    fn test_text_nested_escape_sequences_2() {
1211        let src = r#""\\\"""#;
1212        let text = parse_unwrap(src);
1213        assert_eq!(text, DatexExpression::Text("\\\"".to_string()));
1214    }
1215
1216    #[test]
1217    fn test_empty_array() {
1218        let src = "[]";
1219        let arr = parse_unwrap(src);
1220        assert_eq!(arr, DatexExpression::Array(vec![]));
1221    }
1222
1223    #[test]
1224    fn test_array_with_values() {
1225        let src = "[1, 2, 3, 4.5, \"text\"]";
1226        let arr = parse_unwrap(src);
1227
1228        assert_eq!(
1229            arr,
1230            DatexExpression::Array(vec![
1231                DatexExpression::Integer(Integer::from(1)),
1232                DatexExpression::Integer(Integer::from(2)),
1233                DatexExpression::Integer(Integer::from(3)),
1234                DatexExpression::Decimal(Decimal::from_string("4.5")),
1235                DatexExpression::Text("text".to_string()),
1236            ])
1237        );
1238    }
1239
1240    #[test]
1241    fn test_empty_object() {
1242        let src = "{}";
1243        let obj = parse_unwrap(src);
1244
1245        assert_eq!(obj, DatexExpression::Object(vec![]));
1246    }
1247
1248    #[test]
1249    fn test_tuple() {
1250        let src = "1,2";
1251        let tuple = parse_unwrap(src);
1252
1253        assert_eq!(
1254            tuple,
1255            DatexExpression::Tuple(vec![
1256                TupleEntry::Value(DatexExpression::Integer(Integer::from(1))),
1257                TupleEntry::Value(DatexExpression::Integer(Integer::from(2))),
1258            ])
1259        );
1260    }
1261
1262    #[test]
1263    fn test_scoped_tuple() {
1264        let src = "(1, 2)";
1265        let tuple = parse_unwrap(src);
1266
1267        assert_eq!(
1268            tuple,
1269            DatexExpression::Tuple(vec![
1270                TupleEntry::Value(DatexExpression::Integer(Integer::from(1))),
1271                TupleEntry::Value(DatexExpression::Integer(Integer::from(2))),
1272            ])
1273        );
1274    }
1275
1276    #[test]
1277    fn test_keyed_tuple() {
1278        let src = "1: 2, 3: 4, xy:2, 'a b c': 'd'";
1279        let tuple = parse_unwrap(src);
1280
1281        assert_eq!(
1282            tuple,
1283            DatexExpression::Tuple(vec![
1284                TupleEntry::KeyValue(
1285                    DatexExpression::Integer(Integer::from(1)),
1286                    DatexExpression::Integer(Integer::from(2))
1287                ),
1288                TupleEntry::KeyValue(
1289                    DatexExpression::Integer(Integer::from(3)),
1290                    DatexExpression::Integer(Integer::from(4))
1291                ),
1292                TupleEntry::KeyValue(
1293                    DatexExpression::Text("xy".to_string()),
1294                    DatexExpression::Integer(Integer::from(2))
1295                ),
1296                TupleEntry::KeyValue(
1297                    DatexExpression::Text("a b c".to_string()),
1298                    DatexExpression::Text("d".to_string())
1299                ),
1300            ])
1301        );
1302    }
1303
1304    #[test]
1305    fn test_tuple_array() {
1306        let src = "[(1,2),3,(4,)]";
1307        let arr = parse_unwrap(src);
1308
1309        assert_eq!(
1310            arr,
1311            DatexExpression::Array(vec![
1312                DatexExpression::Tuple(vec![
1313                    TupleEntry::Value(DatexExpression::Integer(Integer::from(
1314                        1
1315                    ))),
1316                    TupleEntry::Value(DatexExpression::Integer(Integer::from(
1317                        2
1318                    ))),
1319                ]),
1320                DatexExpression::Integer(Integer::from(3)),
1321                DatexExpression::Tuple(vec![TupleEntry::Value(
1322                    DatexExpression::Integer(Integer::from(4))
1323                ),]),
1324            ])
1325        );
1326    }
1327
1328    #[test]
1329    fn test_single_value_tuple() {
1330        let src = "1,";
1331        let tuple = parse_unwrap(src);
1332
1333        assert_eq!(
1334            tuple,
1335            DatexExpression::Tuple(vec![TupleEntry::Value(
1336                DatexExpression::Integer(Integer::from(1))
1337            ),])
1338        );
1339    }
1340
1341    #[test]
1342    fn test_single_key_value_tuple() {
1343        let src = "x: 1";
1344        let tuple = parse_unwrap(src);
1345        assert_eq!(
1346            tuple,
1347            DatexExpression::Tuple(vec![TupleEntry::KeyValue(
1348                DatexExpression::Text("x".to_string()),
1349                DatexExpression::Integer(Integer::from(1))
1350            ),])
1351        );
1352    }
1353
1354    #[test]
1355    fn test_scoped_atom() {
1356        let src = "(1)";
1357        let atom = parse_unwrap(src);
1358        assert_eq!(atom, DatexExpression::Integer(Integer::from(1)));
1359    }
1360
1361    #[test]
1362    fn test_scoped_array() {
1363        let src = "(([1, 2, 3]))";
1364        let arr = parse_unwrap(src);
1365
1366        assert_eq!(
1367            arr,
1368            DatexExpression::Array(vec![
1369                DatexExpression::Integer(Integer::from(1)),
1370                DatexExpression::Integer(Integer::from(2)),
1371                DatexExpression::Integer(Integer::from(3)),
1372            ])
1373        );
1374    }
1375
1376    #[test]
1377    fn test_object_with_key_value_pairs() {
1378        let src = r#"{"key1": "value1", "key2": 42, "key3": true}"#;
1379        let obj = parse_unwrap(src);
1380
1381        assert_eq!(
1382            obj,
1383            DatexExpression::Object(vec![
1384                (
1385                    DatexExpression::Text("key1".to_string()),
1386                    DatexExpression::Text("value1".to_string())
1387                ),
1388                (
1389                    DatexExpression::Text("key2".to_string()),
1390                    DatexExpression::Integer(Integer::from(42))
1391                ),
1392                (
1393                    DatexExpression::Text("key3".to_string()),
1394                    DatexExpression::Boolean(true)
1395                ),
1396            ])
1397        );
1398    }
1399
1400    #[test]
1401    fn test_dynamic_object_keys() {
1402        let src = r#"{(1): "value1", (2): 42, (3): true}"#;
1403        let obj = parse_unwrap(src);
1404        assert_eq!(
1405            obj,
1406            DatexExpression::Object(vec![
1407                (
1408                    DatexExpression::Integer(Integer::from(1)),
1409                    DatexExpression::Text("value1".to_string())
1410                ),
1411                (
1412                    DatexExpression::Integer(Integer::from(2)),
1413                    DatexExpression::Integer(Integer::from(42))
1414                ),
1415                (
1416                    DatexExpression::Integer(Integer::from(3)),
1417                    DatexExpression::Boolean(true)
1418                ),
1419            ])
1420        );
1421    }
1422
1423    #[test]
1424    fn test_dynamic_tuple_keys() {
1425        let src = "(1): 1, ([]): 2";
1426        let tuple = parse_unwrap(src);
1427
1428        assert_eq!(
1429            tuple,
1430            DatexExpression::Tuple(vec![
1431                TupleEntry::KeyValue(
1432                    DatexExpression::Integer(Integer::from(1)),
1433                    DatexExpression::Integer(Integer::from(1))
1434                ),
1435                TupleEntry::KeyValue(
1436                    DatexExpression::Array(vec![]),
1437                    DatexExpression::Integer(Integer::from(2))
1438                ),
1439            ])
1440        );
1441    }
1442
1443    #[test]
1444    fn test_add() {
1445        // Test with escaped characters in text
1446        let src = "1 + 2";
1447        let expr = parse_unwrap(src);
1448        assert_eq!(
1449            expr,
1450            DatexExpression::BinaryOperation(
1451                BinaryOperator::Add,
1452                Box::new(DatexExpression::Integer(Integer::from(1))),
1453                Box::new(DatexExpression::Integer(Integer::from(2))),
1454            )
1455        );
1456    }
1457
1458    #[test]
1459    fn test_add_complex_values() {
1460        // Test with escaped characters in text
1461        let src = "[] + x + (1 + 2)";
1462        let expr = parse_unwrap(src);
1463        assert_eq!(
1464            expr,
1465            DatexExpression::BinaryOperation(
1466                BinaryOperator::Add,
1467                Box::new(DatexExpression::BinaryOperation(
1468                    BinaryOperator::Add,
1469                    Box::new(DatexExpression::Array(vec![])),
1470                    Box::new(DatexExpression::Variable(None, "x".to_string())),
1471                )),
1472                Box::new(DatexExpression::BinaryOperation(
1473                    BinaryOperator::Add,
1474                    Box::new(DatexExpression::Integer(Integer::from(1))),
1475                    Box::new(DatexExpression::Integer(Integer::from(2))),
1476                )),
1477            )
1478        );
1479    }
1480
1481    #[test]
1482    fn test_subtract() {
1483        let src = "5 - 3";
1484        let expr = parse_unwrap(src);
1485        assert_eq!(
1486            expr,
1487            DatexExpression::BinaryOperation(
1488                BinaryOperator::Subtract,
1489                Box::new(DatexExpression::Integer(Integer::from(5))),
1490                Box::new(DatexExpression::Integer(Integer::from(3))),
1491            )
1492        );
1493    }
1494
1495    #[test]
1496    fn test_multiply() {
1497        let src = "4 * 2";
1498        let expr = parse_unwrap(src);
1499        assert_eq!(
1500            expr,
1501            DatexExpression::BinaryOperation(
1502                BinaryOperator::Multiply,
1503                Box::new(DatexExpression::Integer(Integer::from(4))),
1504                Box::new(DatexExpression::Integer(Integer::from(2))),
1505            )
1506        );
1507    }
1508
1509    #[test]
1510    fn test_divide() {
1511        let src = "8 / 2";
1512        let expr = parse_unwrap(src);
1513        assert_eq!(
1514            expr,
1515            DatexExpression::BinaryOperation(
1516                BinaryOperator::Divide,
1517                Box::new(DatexExpression::Integer(Integer::from(8))),
1518                Box::new(DatexExpression::Integer(Integer::from(2))),
1519            )
1520        );
1521    }
1522
1523    #[test]
1524    fn test_complex_calculation() {
1525        let src = "1 + 2 * 3 + 4";
1526        let expr = parse_unwrap(src);
1527        assert_eq!(
1528            expr,
1529            DatexExpression::BinaryOperation(
1530                BinaryOperator::Add,
1531                Box::new(DatexExpression::BinaryOperation(
1532                    BinaryOperator::Add,
1533                    Box::new(DatexExpression::Integer(Integer::from(1))),
1534                    Box::new(DatexExpression::BinaryOperation(
1535                        BinaryOperator::Multiply,
1536                        Box::new(DatexExpression::Integer(Integer::from(2))),
1537                        Box::new(DatexExpression::Integer(Integer::from(3))),
1538                    )),
1539                )),
1540                Box::new(DatexExpression::Integer(Integer::from(4))),
1541            )
1542        );
1543    }
1544
1545    #[test]
1546    fn test_nested_addition() {
1547        let src = "1 + (2 + 3)";
1548        let expr = parse_unwrap(src);
1549        assert_eq!(
1550            expr,
1551            DatexExpression::BinaryOperation(
1552                BinaryOperator::Add,
1553                Box::new(DatexExpression::Integer(Integer::from(1))),
1554                Box::new(DatexExpression::BinaryOperation(
1555                    BinaryOperator::Add,
1556                    Box::new(DatexExpression::Integer(Integer::from(2))),
1557                    Box::new(DatexExpression::Integer(Integer::from(3))),
1558                )),
1559            )
1560        );
1561    }
1562
1563    #[test]
1564    fn test_add_statements_1() {
1565        // Test with escaped characters in text
1566        let src = "1 + (2;3)";
1567        let expr = parse_unwrap(src);
1568        assert_eq!(
1569            expr,
1570            DatexExpression::BinaryOperation(
1571                BinaryOperator::Add,
1572                Box::new(DatexExpression::Integer(Integer::from(1))),
1573                Box::new(DatexExpression::Statements(vec![
1574                    Statement {
1575                        expression: DatexExpression::Integer(Integer::from(2)),
1576                        is_terminated: true,
1577                    },
1578                    Statement {
1579                        expression: DatexExpression::Integer(Integer::from(3)),
1580                        is_terminated: false,
1581                    },
1582                ])),
1583            )
1584        );
1585    }
1586
1587    #[test]
1588    fn test_add_statements_2() {
1589        // Test with escaped characters in text
1590        let src = "(1;2) + 3";
1591        let expr = parse_unwrap(src);
1592        assert_eq!(
1593            expr,
1594            DatexExpression::BinaryOperation(
1595                BinaryOperator::Add,
1596                Box::new(DatexExpression::Statements(vec![
1597                    Statement {
1598                        expression: DatexExpression::Integer(Integer::from(1)),
1599                        is_terminated: true,
1600                    },
1601                    Statement {
1602                        expression: DatexExpression::Integer(Integer::from(2)),
1603                        is_terminated: false,
1604                    },
1605                ])),
1606                Box::new(DatexExpression::Integer(Integer::from(3))),
1607            )
1608        );
1609    }
1610
1611    #[test]
1612    fn test_nested_expressions() {
1613        let src = "[1 + 2]";
1614        let expr = parse_unwrap(src);
1615        assert_eq!(
1616            expr,
1617            DatexExpression::Array(vec![DatexExpression::BinaryOperation(
1618                BinaryOperator::Add,
1619                Box::new(DatexExpression::Integer(Integer::from(1))),
1620                Box::new(DatexExpression::Integer(Integer::from(2))),
1621            ),])
1622        );
1623    }
1624
1625    #[test]
1626    fn multi_statement_expression() {
1627        let src = "1;2";
1628        let expr = parse_unwrap(src);
1629        assert_eq!(
1630            expr,
1631            DatexExpression::Statements(vec![
1632                Statement {
1633                    expression: DatexExpression::Integer(Integer::from(1)),
1634                    is_terminated: true,
1635                },
1636                Statement {
1637                    expression: DatexExpression::Integer(Integer::from(2)),
1638                    is_terminated: false,
1639                },
1640            ])
1641        );
1642    }
1643
1644    #[test]
1645    fn nested_scope_statements() {
1646        let src = "(1; 2; 3)";
1647        let expr = parse_unwrap(src);
1648        assert_eq!(
1649            expr,
1650            DatexExpression::Statements(vec![
1651                Statement {
1652                    expression: DatexExpression::Integer(Integer::from(1)),
1653                    is_terminated: true,
1654                },
1655                Statement {
1656                    expression: DatexExpression::Integer(Integer::from(2)),
1657                    is_terminated: true,
1658                },
1659                Statement {
1660                    expression: DatexExpression::Integer(Integer::from(3)),
1661                    is_terminated: false,
1662                },
1663            ])
1664        );
1665    }
1666    #[test]
1667    fn nested_scope_statements_closed() {
1668        let src = "(1; 2; 3;)";
1669        let expr = parse_unwrap(src);
1670        assert_eq!(
1671            expr,
1672            DatexExpression::Statements(vec![
1673                Statement {
1674                    expression: DatexExpression::Integer(Integer::from(1)),
1675                    is_terminated: true,
1676                },
1677                Statement {
1678                    expression: DatexExpression::Integer(Integer::from(2)),
1679                    is_terminated: true,
1680                },
1681                Statement {
1682                    expression: DatexExpression::Integer(Integer::from(3)),
1683                    is_terminated: true,
1684                },
1685            ])
1686        );
1687    }
1688
1689    #[test]
1690    fn nested_statements_in_object() {
1691        let src = r#"{"key": (1; 2; 3)}"#;
1692        let expr = parse_unwrap(src);
1693        assert_eq!(
1694            expr,
1695            DatexExpression::Object(vec![(
1696                DatexExpression::Text("key".to_string()),
1697                DatexExpression::Statements(vec![
1698                    Statement {
1699                        expression: DatexExpression::Integer(Integer::from(1)),
1700                        is_terminated: true,
1701                    },
1702                    Statement {
1703                        expression: DatexExpression::Integer(Integer::from(2)),
1704                        is_terminated: true,
1705                    },
1706                    Statement {
1707                        expression: DatexExpression::Integer(Integer::from(3)),
1708                        is_terminated: false,
1709                    },
1710                ])
1711            ),])
1712        );
1713    }
1714
1715    #[test]
1716    fn test_single_statement() {
1717        let src = "1;";
1718        let expr = parse_unwrap(src);
1719        assert_eq!(
1720            expr,
1721            DatexExpression::Statements(vec![Statement {
1722                expression: DatexExpression::Integer(Integer::from(1)),
1723                is_terminated: true,
1724            },])
1725        );
1726    }
1727
1728    #[test]
1729    fn test_empty_statement() {
1730        let src = ";";
1731        let expr = parse_unwrap(src);
1732        assert_eq!(expr, DatexExpression::Statements(vec![]));
1733    }
1734
1735    #[test]
1736    fn test_empty_statement_multiple() {
1737        let src = ";;;";
1738        let expr = parse_unwrap(src);
1739        assert_eq!(expr, DatexExpression::Statements(vec![]));
1740    }
1741
1742    #[test]
1743    fn test_variable_expression() {
1744        let src = "myVar";
1745        let expr = parse_unwrap(src);
1746        assert_eq!(expr, DatexExpression::Variable(None, "myVar".to_string()));
1747    }
1748
1749    #[test]
1750    fn test_variable_expression_with_operations() {
1751        let src = "myVar + 1";
1752        let expr = parse_unwrap(src);
1753        assert_eq!(
1754            expr,
1755            DatexExpression::BinaryOperation(
1756                BinaryOperator::Add,
1757                Box::new(DatexExpression::Variable(None, "myVar".to_string())),
1758                Box::new(DatexExpression::Integer(Integer::from(1))),
1759            )
1760        );
1761    }
1762
1763    #[test]
1764    fn test_apply_expression() {
1765        let src = "myFunc(1, 2, 3)";
1766        let expr = parse_unwrap(src);
1767        assert_eq!(
1768            expr,
1769            DatexExpression::ApplyChain(
1770                Box::new(DatexExpression::Variable(None, "myFunc".to_string())),
1771                vec![Apply::FunctionCall(DatexExpression::Tuple(vec![
1772                    TupleEntry::Value(DatexExpression::Integer(Integer::from(
1773                        1
1774                    ))),
1775                    TupleEntry::Value(DatexExpression::Integer(Integer::from(
1776                        2
1777                    ))),
1778                    TupleEntry::Value(DatexExpression::Integer(Integer::from(
1779                        3
1780                    ))),
1781                ]),)],
1782            )
1783        );
1784    }
1785
1786    #[test]
1787    fn test_apply_empty() {
1788        let src = "myFunc()";
1789        let expr = parse_unwrap(src);
1790        assert_eq!(
1791            expr,
1792            DatexExpression::ApplyChain(
1793                Box::new(DatexExpression::Variable(None, "myFunc".to_string())),
1794                vec![Apply::FunctionCall(DatexExpression::Statements(vec![]))],
1795            )
1796        );
1797    }
1798
1799    #[test]
1800    fn test_apply_multiple() {
1801        let src = "myFunc(1)(2, 3)";
1802        let expr = parse_unwrap(src);
1803        assert_eq!(
1804            expr,
1805            DatexExpression::ApplyChain(
1806                Box::new(DatexExpression::Variable(None, "myFunc".to_string())),
1807                vec![
1808                    Apply::FunctionCall(DatexExpression::Integer(
1809                        Integer::from(1)
1810                    ),),
1811                    Apply::FunctionCall(DatexExpression::Tuple(vec![
1812                        TupleEntry::Value(DatexExpression::Integer(
1813                            Integer::from(2)
1814                        )),
1815                        TupleEntry::Value(DatexExpression::Integer(
1816                            Integer::from(3)
1817                        )),
1818                    ]))
1819                ],
1820            )
1821        );
1822    }
1823
1824    #[test]
1825    fn test_apply_atom() {
1826        let src = "print 'test'";
1827        let expr = parse_unwrap(src);
1828        assert_eq!(
1829            expr,
1830            DatexExpression::ApplyChain(
1831                Box::new(DatexExpression::Variable(None, "print".to_string())),
1832                vec![Apply::FunctionCall(DatexExpression::Text(
1833                    "test".to_string()
1834                ))],
1835            )
1836        );
1837    }
1838
1839    #[test]
1840    fn test_property_access() {
1841        let src = "myObj.myProp";
1842        let expr = parse_unwrap(src);
1843        assert_eq!(
1844            expr,
1845            DatexExpression::ApplyChain(
1846                Box::new(DatexExpression::Variable(None, "myObj".to_string())),
1847                vec![Apply::PropertyAccess(DatexExpression::Text(
1848                    "myProp".to_string()
1849                ))],
1850            )
1851        );
1852    }
1853
1854    #[test]
1855    fn test_property_access_scoped() {
1856        let src = "myObj.(1)";
1857        let expr = parse_unwrap(src);
1858        assert_eq!(
1859            expr,
1860            DatexExpression::ApplyChain(
1861                Box::new(DatexExpression::Variable(None, "myObj".to_string())),
1862                vec![Apply::PropertyAccess(DatexExpression::Integer(
1863                    Integer::from(1)
1864                ))],
1865            )
1866        );
1867    }
1868
1869    #[test]
1870    fn test_property_access_multiple() {
1871        let src = "myObj.myProp.anotherProp.(1 + 2).(x;y)";
1872        let expr = parse_unwrap(src);
1873        assert_eq!(
1874            expr,
1875            DatexExpression::ApplyChain(
1876                Box::new(DatexExpression::Variable(None, "myObj".to_string())),
1877                vec![
1878                    Apply::PropertyAccess(DatexExpression::Text(
1879                        "myProp".to_string()
1880                    )),
1881                    Apply::PropertyAccess(DatexExpression::Text(
1882                        "anotherProp".to_string()
1883                    )),
1884                    Apply::PropertyAccess(DatexExpression::BinaryOperation(
1885                        BinaryOperator::Add,
1886                        Box::new(DatexExpression::Integer(Integer::from(1))),
1887                        Box::new(DatexExpression::Integer(Integer::from(2))),
1888                    )),
1889                    Apply::PropertyAccess(DatexExpression::Statements(vec![
1890                        Statement {
1891                            expression: DatexExpression::Variable(
1892                                None,
1893                                "x".to_string()
1894                            ),
1895                            is_terminated: true,
1896                        },
1897                        Statement {
1898                            expression: DatexExpression::Variable(
1899                                None,
1900                                "y".to_string()
1901                            ),
1902                            is_terminated: false,
1903                        },
1904                    ])),
1905                ],
1906            )
1907        );
1908    }
1909
1910    #[test]
1911    fn test_property_access_and_apply() {
1912        let src = "myObj.myProp(1, 2)";
1913        let expr = parse_unwrap(src);
1914        assert_eq!(
1915            expr,
1916            DatexExpression::ApplyChain(
1917                Box::new(DatexExpression::Variable(None, "myObj".to_string())),
1918                vec![
1919                    Apply::PropertyAccess(DatexExpression::Text(
1920                        "myProp".to_string()
1921                    )),
1922                    Apply::FunctionCall(DatexExpression::Tuple(vec![
1923                        TupleEntry::Value(DatexExpression::Integer(
1924                            Integer::from(1)
1925                        )),
1926                        TupleEntry::Value(DatexExpression::Integer(
1927                            Integer::from(2)
1928                        )),
1929                    ])),
1930                ],
1931            )
1932        );
1933    }
1934
1935    #[test]
1936    fn test_apply_and_property_access() {
1937        let src = "myFunc(1).myProp";
1938        let expr = parse_unwrap(src);
1939        assert_eq!(
1940            expr,
1941            DatexExpression::ApplyChain(
1942                Box::new(DatexExpression::Variable(None, "myFunc".to_string())),
1943                vec![
1944                    Apply::FunctionCall(DatexExpression::Integer(
1945                        Integer::from(1)
1946                    )),
1947                    Apply::PropertyAccess(DatexExpression::Text(
1948                        "myProp".to_string()
1949                    )),
1950                ],
1951            )
1952        );
1953    }
1954
1955    #[test]
1956    fn nested_apply_and_property_access() {
1957        let src = "((x(1)).y).z";
1958        let expr = parse_unwrap(src);
1959        assert_eq!(
1960            expr,
1961            DatexExpression::ApplyChain(
1962                Box::new(DatexExpression::ApplyChain(
1963                    Box::new(DatexExpression::ApplyChain(
1964                        Box::new(DatexExpression::Variable(None, "x".to_string())),
1965                        vec![Apply::FunctionCall(DatexExpression::Integer(
1966                            Integer::from(1)
1967                        ))],
1968                    )),
1969                    vec![Apply::PropertyAccess(DatexExpression::Text(
1970                        "y".to_string()
1971                    ))],
1972                )),
1973                vec![Apply::PropertyAccess(DatexExpression::Text(
1974                    "z".to_string()
1975                ))],
1976            )
1977        );
1978    }
1979
1980    #[test]
1981    fn variable_declaration() {
1982        let src = "const x = 42";
1983        let expr = parse_unwrap(src);
1984        assert_eq!(
1985            expr,
1986            DatexExpression::VariableDeclaration(
1987                None,
1988                VariableType::Const,
1989                VariableMutType::Immutable,
1990                "x".to_string(),
1991                Box::new(DatexExpression::Integer(Integer::from(42))),
1992            )
1993        );
1994    }
1995
1996    #[test]
1997    fn variable_declaration_statement() {
1998        let src = "const x = 42;";
1999        let expr = parse_unwrap(src);
2000        assert_eq!(
2001            expr,
2002            DatexExpression::Statements(vec![Statement {
2003                expression: DatexExpression::VariableDeclaration(
2004                    None,
2005                    VariableType::Const,
2006                    VariableMutType::Immutable,
2007                    "x".to_string(),
2008                    Box::new(DatexExpression::Integer(Integer::from(42))),
2009                ),
2010                is_terminated: true,
2011            },])
2012        );
2013    }
2014
2015    #[test]
2016    fn variable_declaration_with_expression() {
2017        let src = "var x = 1 + 2";
2018        let expr = parse_unwrap(src);
2019        assert_eq!(
2020            expr,
2021            DatexExpression::VariableDeclaration(
2022                None,
2023                VariableType::Var,
2024                VariableMutType::Immutable,
2025                "x".to_string(),
2026                Box::new(DatexExpression::BinaryOperation(
2027                    BinaryOperator::Add,
2028                    Box::new(DatexExpression::Integer(Integer::from(1))),
2029                    Box::new(DatexExpression::Integer(Integer::from(2))),
2030                )),
2031            )
2032        );
2033    }
2034
2035    #[test]
2036    fn variable_assignment() {
2037        let src = "x = 42";
2038        let expr = parse_unwrap(src);
2039        assert_eq!(
2040            expr,
2041            DatexExpression::VariableAssignment(
2042                None,
2043                "x".to_string(),
2044                Box::new(DatexExpression::Integer(Integer::from(42))),
2045            )
2046        );
2047    }
2048
2049    #[test]
2050    fn variable_assignment_expression() {
2051        let src = "x = (y = 1)";
2052        let expr = parse_unwrap(src);
2053        assert_eq!(
2054            expr,
2055            DatexExpression::VariableAssignment(
2056                None,
2057                "x".to_string(),
2058                Box::new(DatexExpression::VariableAssignment(
2059                    None,
2060                    "y".to_string(),
2061                    Box::new(DatexExpression::Integer(Integer::from(1))),
2062                )),
2063            )
2064        );
2065    }
2066
2067    #[test]
2068    fn variable_assignment_expression_in_array() {
2069        let src = "[x = 1]";
2070        let expr = parse_unwrap(src);
2071        assert_eq!(
2072            expr,
2073            DatexExpression::Array(vec![DatexExpression::VariableAssignment(
2074                None,
2075                "x".to_string(),
2076                Box::new(DatexExpression::Integer(Integer::from(1))),
2077            ),])
2078        );
2079    }
2080
2081    #[test]
2082    fn apply_in_array() {
2083        let src = "[myFunc(1)]";
2084        let expr = parse_unwrap(src);
2085        assert_eq!(
2086            expr,
2087            DatexExpression::Array(vec![DatexExpression::ApplyChain(
2088                Box::new(DatexExpression::Variable(None, "myFunc".to_string())),
2089                vec![Apply::FunctionCall(DatexExpression::Integer(
2090                    Integer::from(1)
2091                ))]
2092            ),])
2093        );
2094    }
2095
2096    #[test]
2097    fn test_fraction() {
2098        let src = "1/3";
2099        let val = try_parse_to_value_container(src);
2100        assert_eq!(val, ValueContainer::from(Decimal::from_string("1/3")));
2101
2102        let res = parse("42.4/3");
2103        assert!(res.is_err());
2104        let res = parse("42 /3");
2105        assert!(res.is_err());
2106        let res = parse("42/ 3");
2107        assert!(res.is_err());
2108    }
2109
2110    #[test]
2111    fn test_endpoint() {
2112        let src = "@jonas";
2113        let val = try_parse_to_value_container(src);
2114        assert_eq!(
2115            val,
2116            ValueContainer::from(Endpoint::from_str("@jonas").unwrap())
2117        );
2118    }
2119
2120    // TODO #159:
2121    // #[test]
2122    // fn variable_assignment_multiple() {
2123    //     let src = "x = y = 42";
2124    //     let expr = parse_unwrap(src);
2125    //     assert_eq!(
2126    //         expr,
2127    //         DatexExpression::VariableAssignment(
2128    //             "x".to_string(),
2129    //             Box::new(DatexExpression::VariableAssignment(
2130    //                 "y".to_string(),
2131    //                 Box::new(DatexExpression::Integer(Integer::from(42))),
2132    //             )),
2133    //         )
2134    //     );
2135    // }
2136
2137    #[test]
2138    fn variable_declaration_and_assignment() {
2139        let src = "var x = 42; x = 100 * 10;";
2140        let expr = parse_unwrap(src);
2141        assert_eq!(
2142            expr,
2143            DatexExpression::Statements(vec![
2144                Statement {
2145                    expression: DatexExpression::VariableDeclaration(
2146                        None,
2147                        VariableType::Var,
2148                        VariableMutType::Immutable,
2149                        "x".to_string(),
2150                        Box::new(DatexExpression::Integer(Integer::from(42))),
2151                    ),
2152                    is_terminated: true,
2153                },
2154                Statement {
2155                    expression: DatexExpression::VariableAssignment(
2156                        None,
2157                        "x".to_string(),
2158                        Box::new(DatexExpression::BinaryOperation(
2159                            BinaryOperator::Multiply,
2160                            Box::new(DatexExpression::Integer(Integer::from(
2161                                100
2162                            ))),
2163                            Box::new(DatexExpression::Integer(Integer::from(
2164                                10
2165                            ))),
2166                        )),
2167                    ),
2168                    is_terminated: true,
2169                },
2170            ])
2171        );
2172    }
2173
2174    #[test]
2175    fn test_placeholder() {
2176        let src = "?";
2177        let expr = parse_unwrap(src);
2178        assert_eq!(expr, DatexExpression::Placeholder);
2179    }
2180
2181    #[test]
2182    fn test_integer_to_value_container() {
2183        let src = "123456789123456789";
2184        let val = try_parse_to_value_container(src);
2185        assert_eq!(
2186            val,
2187            ValueContainer::from(
2188                Integer::from_string("123456789123456789").unwrap()
2189            )
2190        );
2191    }
2192
2193    #[test]
2194    fn test_decimal_to_value_container() {
2195        let src = "123.456789123456";
2196        let val = try_parse_to_value_container(src);
2197        assert_eq!(
2198            val,
2199            ValueContainer::from(Decimal::from_string("123.456789123456"))
2200        );
2201    }
2202
2203    #[test]
2204    fn test_text_to_value_container() {
2205        let src = r#""Hello, world!""#;
2206        let val = try_parse_to_value_container(src);
2207        assert_eq!(val, ValueContainer::from("Hello, world!".to_string()));
2208    }
2209
2210    #[test]
2211    fn test_array_to_value_container() {
2212        let src = "[1, 2, 3, 4.5, \"text\"]";
2213        let val = try_parse_to_value_container(src);
2214        let value_container_array: Vec<ValueContainer> = vec![
2215            Integer::from(1).into(),
2216            Integer::from(2).into(),
2217            Integer::from(3).into(),
2218            Decimal::from_string("4.5").into(),
2219            "text".to_string().into(),
2220        ];
2221        assert_eq!(val, ValueContainer::from(value_container_array));
2222    }
2223
2224    #[test]
2225    fn test_json_to_value_container() {
2226        let src = r#"
2227            {
2228                "name": "Test",
2229                "value": 42,
2230                "active": true,
2231                "items": [1, 2, 3, 0.5],
2232                "nested": {
2233                    "key": "value"
2234                }
2235            }
2236        "#;
2237
2238        let val = try_parse_to_value_container(src);
2239        let value_container_array: Vec<ValueContainer> = vec![
2240            Integer::from(1).into(),
2241            Integer::from(2).into(),
2242            Integer::from(3).into(),
2243            Decimal::from_string("0.5").into(),
2244        ];
2245        let value_container_inner_object: ValueContainer =
2246            ValueContainer::from(Object::from(
2247                vec![("key".to_string(), "value".to_string().into())]
2248                    .into_iter()
2249                    .collect::<HashMap<String, ValueContainer>>(),
2250            ));
2251        let value_container_object: ValueContainer =
2252            ValueContainer::from(Object::from(
2253                vec![
2254                    ("name".to_string(), "Test".to_string().into()),
2255                    ("value".to_string(), Integer::from(42).into()),
2256                    ("active".to_string(), true.into()),
2257                    ("items".to_string(), value_container_array.into()),
2258                    ("nested".to_string(), value_container_inner_object),
2259                ]
2260                .into_iter()
2261                .collect::<HashMap<String, ValueContainer>>(),
2262            ));
2263        assert_eq!(val, value_container_object);
2264    }
2265    #[test]
2266    fn test_invalid_value_containers() {
2267        let src = "1 + 2";
2268        let expr = parse_unwrap(src);
2269        assert!(
2270            ValueContainer::try_from(expr).is_err(),
2271            "Expected error when converting expression to ValueContainer"
2272        );
2273
2274        let src = "xy";
2275        let expr = parse_unwrap(src);
2276        assert!(
2277            ValueContainer::try_from(expr).is_err(),
2278            "Expected error when converting expression to ValueContainer"
2279        );
2280
2281        let src = "x()";
2282        let expr = parse_unwrap(src);
2283        assert!(
2284            ValueContainer::try_from(expr).is_err(),
2285            "Expected error when converting expression to ValueContainer"
2286        );
2287    }
2288
2289    #[test]
2290    fn test_invalid_add() {
2291        let src = "1+2";
2292        let res = parse(src);
2293        println!("res: {res:?}");
2294        assert!(
2295            res.unwrap_err().len() == 1,
2296            "Expected error when parsing expression"
2297        );
2298    }
2299
2300    #[test]
2301    fn test_decimal_nan() {
2302        let src = "NaN";
2303        let num = parse_unwrap(src);
2304        assert_matches!(num, DatexExpression::Decimal(Decimal::NaN));
2305
2306        let src = "nan";
2307        let num = parse_unwrap(src);
2308        assert_matches!(num, DatexExpression::Decimal(Decimal::NaN));
2309    }
2310
2311    #[test]
2312    fn test_decimal_infinity() {
2313        let src = "Infinity";
2314        let num = parse_unwrap(src);
2315        assert_eq!(num, DatexExpression::Decimal(Decimal::Infinity));
2316
2317        let src = "-Infinity";
2318        let num = parse_unwrap(src);
2319        assert_eq!(num, DatexExpression::Decimal(Decimal::NegInfinity));
2320
2321        let src = "infinity";
2322        let num = parse_unwrap(src);
2323        assert_eq!(num, DatexExpression::Decimal(Decimal::Infinity));
2324
2325        let src = "-infinity";
2326        let num = parse_unwrap(src);
2327        assert_eq!(num, DatexExpression::Decimal(Decimal::NegInfinity));
2328    }
2329
2330    #[test]
2331    fn test_comment() {
2332        let src = "// This is a comment\n1 + 2";
2333        let expr = parse_unwrap(src);
2334        assert_eq!(
2335            expr,
2336            DatexExpression::BinaryOperation(
2337                BinaryOperator::Add,
2338                Box::new(DatexExpression::Integer(Integer::from(1))),
2339                Box::new(DatexExpression::Integer(Integer::from(2))),
2340            )
2341        );
2342
2343        let src = "1 + //test\n2";
2344        let expr = parse_unwrap(src);
2345        assert_eq!(
2346            expr,
2347            DatexExpression::BinaryOperation(
2348                BinaryOperator::Add,
2349                Box::new(DatexExpression::Integer(Integer::from(1))),
2350                Box::new(DatexExpression::Integer(Integer::from(2))),
2351            )
2352        );
2353    }
2354
2355    #[test]
2356    fn test_multiline_comment() {
2357        let src = "/* This is a\nmultiline comment */\n1 + 2";
2358        let expr = parse_unwrap(src);
2359        assert_eq!(
2360            expr,
2361            DatexExpression::BinaryOperation(
2362                BinaryOperator::Add,
2363                Box::new(DatexExpression::Integer(Integer::from(1))),
2364                Box::new(DatexExpression::Integer(Integer::from(2))),
2365            )
2366        );
2367
2368        let src = "1 + /*test*/ 2";
2369        let expr = parse_unwrap(src);
2370        assert_eq!(
2371            expr,
2372            DatexExpression::BinaryOperation(
2373                BinaryOperator::Add,
2374                Box::new(DatexExpression::Integer(Integer::from(1))),
2375                Box::new(DatexExpression::Integer(Integer::from(2))),
2376            )
2377        );
2378    }
2379
2380    #[test]
2381    fn test_shebang() {
2382        let src = "#!/usr/bin/env datex\n1 + 2";
2383        let expr = parse_unwrap(src);
2384        assert_eq!(
2385            expr,
2386            DatexExpression::BinaryOperation(
2387                BinaryOperator::Add,
2388                Box::new(DatexExpression::Integer(Integer::from(1))),
2389                Box::new(DatexExpression::Integer(Integer::from(2))),
2390            )
2391        );
2392
2393        let src = "1;\n#!/usr/bin/env datex\n2";
2394        // syntax error
2395        let res = parse(src);
2396        assert!(
2397            res.is_err(),
2398            "Expected error when parsing expression with shebang"
2399        );
2400    }
2401
2402    #[test]
2403    fn test_remote_execution() {
2404        let src = "a :: b";
2405        let expr = parse_unwrap(src);
2406        assert_eq!(
2407            expr,
2408            DatexExpression::RemoteExecution(
2409                Box::new(DatexExpression::Variable(None, "a".to_string())),
2410                Box::new(DatexExpression::Variable(None, "b".to_string()))
2411            )
2412        );
2413    }
2414    #[test]
2415    fn test_remote_execution_no_space() {
2416        let src = "a::b";
2417        let expr = parse_unwrap(src);
2418        assert_eq!(
2419            expr,
2420            DatexExpression::RemoteExecution(
2421                Box::new(DatexExpression::Variable(None, "a".to_string())),
2422                Box::new(DatexExpression::Variable(None, "b".to_string()))
2423            )
2424        );
2425    }
2426
2427    #[test]
2428    fn test_remote_execution_complex() {
2429        let src = "a :: b + c * 2";
2430        let expr = parse_unwrap(src);
2431        assert_eq!(
2432            expr,
2433            DatexExpression::RemoteExecution(
2434                Box::new(DatexExpression::Variable(None, "a".to_string())),
2435                Box::new(DatexExpression::BinaryOperation(
2436                    BinaryOperator::Add,
2437                    Box::new(DatexExpression::Variable(None, "b".to_string())),
2438                    Box::new(DatexExpression::BinaryOperation(
2439                        BinaryOperator::Multiply,
2440                        Box::new(DatexExpression::Variable(None, "c".to_string())),
2441                        Box::new(DatexExpression::Integer(Integer::from(2))),
2442                    )),
2443                )),
2444            )
2445        );
2446    }
2447
2448    #[test]
2449    fn test_remote_execution_statements() {
2450        let src = "a :: b; 1";
2451        let expr = parse_unwrap(src);
2452        assert_eq!(
2453            expr,
2454            DatexExpression::Statements(vec![
2455                Statement {
2456                    expression: DatexExpression::RemoteExecution(
2457                        Box::new(DatexExpression::Variable(None, "a".to_string())),
2458                        Box::new(DatexExpression::Variable(None, "b".to_string()))
2459                    ),
2460                    is_terminated: true,
2461                },
2462                Statement {
2463                    expression: DatexExpression::Integer(Integer::from(1)),
2464                    is_terminated: false,
2465                },
2466            ])
2467        );
2468    }
2469
2470    #[test]
2471    fn test_remote_execution_inline_statements() {
2472        let src = "a :: (1; 2 + 3)";
2473        let expr = parse_unwrap(src);
2474        assert_eq!(
2475            expr,
2476            DatexExpression::RemoteExecution(
2477                Box::new(DatexExpression::Variable(None, "a".to_string())),
2478                Box::new(DatexExpression::Statements(vec![
2479                    Statement {
2480                        expression: DatexExpression::Integer(Integer::from(1)),
2481                        is_terminated: true,
2482                    },
2483                    Statement {
2484                        expression: DatexExpression::BinaryOperation(
2485                            BinaryOperator::Add,
2486                            Box::new(DatexExpression::Integer(Integer::from(
2487                                2
2488                            ))),
2489                            Box::new(DatexExpression::Integer(Integer::from(
2490                                3
2491                            ))),
2492                        ),
2493                        is_terminated: false,
2494                    },
2495                ])),
2496            )
2497        );
2498    }
2499
2500    #[test]
2501    fn test_named_slot() {
2502        let src = "#endpoint";
2503        let expr = parse_unwrap(src);
2504        assert_eq!(
2505            expr,
2506            DatexExpression::Slot(Slot::Named("endpoint".to_string()))
2507        );
2508    }
2509
2510    #[test]
2511    fn test_addressed_slot() {
2512        let src = "#123";
2513        let expr = parse_unwrap(src);
2514        assert_eq!(
2515            expr,
2516            DatexExpression::Slot(Slot::Addressed(123))
2517        );
2518    }
2519}