datex-core 0.0.14

The DATEX Core Rust implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
use crate::{
    ast::expressions::{
        BinaryOperation, ComparisonOperation, DatexExpression,
        DatexExpressionData, UnaryOperation,
    },
    fmt::{
        Assoc, Format, Formatter, Operation, ParentContext,
        options::BracketStyle,
    },
    global::operators::{
        BinaryOperator, ComparisonOperator, LogicalUnaryOperator,
        UnaryOperator,
        binary::{ArithmeticOperator, LogicalOperator},
    },
};

impl<'a> Formatter<'a> {
    /// Handles bracketing of an expression based on the current formatting options.
    pub fn handle_bracketing(
        &'a self,
        expression: &'a DatexExpression,
        doc: Format<'a>,
        parent_ctx: Option<ParentContext<'a>>,
        is_left_child_of_parent: bool,
    ) -> Format<'a> {
        self.maybe_wrap_by_parent(
            expression,
            doc,
            parent_ctx,
            is_left_child_of_parent,
        )
    }

    /// Decides whether to wrap an expression in parentheses based on its parent context.
    pub fn maybe_wrap_by_parent(
        &'a self,
        expression: &'a DatexExpression,
        inner: Format<'a>,
        parent_ctx: Option<ParentContext<'a>>,
        is_left_child_of_parent: bool,
    ) -> Format<'a> {
        // If there's no parent context, nothing forces parentheses.
        if parent_ctx.is_none() {
            return inner;
        }

        // handle Statements expression specially
        if let DatexExpressionData::Statements(statements) = expression.data() {
            return
                // brackets definitely needed because multiple statements or terminated
                if statements.statements.len() > 1 || statements.is_terminated {
                    self.wrap_in_parens(inner)
                }
                // single unterminated statement - decide based on bracket style
                else {
                    match self.options.bracket_style {
                        BracketStyle::KeepAll => self.wrap_in_parens(inner),
                        BracketStyle::RemoveDuplicate | BracketStyle::Minimal => inner,
                    }
                };
        }

        let need = self.needs_parens_for_child_expr(
            expression,
            &parent_ctx.unwrap(),
            is_left_child_of_parent,
        );

        if need {
            self.wrap_in_parens(inner)
        } else {
            inner
        }
    }

    /// Returns information about a binary operator: (precedence, associativity, is_associative)
    pub fn binary_operator_info(
        &self,
        op: &BinaryOperator,
    ) -> (u8, Assoc, bool) {
        match op {
            BinaryOperator::Arithmetic(aop) => match aop {
                ArithmeticOperator::Multiply
                | ArithmeticOperator::Divide
                | ArithmeticOperator::Modulo => (20, Assoc::Left, false),
                ArithmeticOperator::Add => (10, Assoc::Left, true), // + is associative
                ArithmeticOperator::Subtract => (10, Assoc::Left, false), // - is not associative
                ArithmeticOperator::Power => (30, Assoc::Right, false),
            },
            BinaryOperator::Logical(lop) => match lop {
                LogicalOperator::And => (5, Assoc::Left, false),
                LogicalOperator::Or => (4, Assoc::Left, false),
            },
            // fallback
            _ => (1, Assoc::None, false),
        }
    }

    /// Returns information about a comparison operator: (precedence, associativity, is_associative)
    fn comparison_operator_info(
        &self,
        op: &ComparisonOperator,
    ) -> (u8, Assoc, bool) {
        match op {
            ComparisonOperator::Equal
            | ComparisonOperator::NotEqual
            | ComparisonOperator::LessThan
            | ComparisonOperator::LessThanOrEqual
            | ComparisonOperator::GreaterThan
            | ComparisonOperator::GreaterThanOrEqual => (7, Assoc::None, false),
            _ => (7, Assoc::None, false),
        }
    }

    /// Returns information about a unary operator: (precedence, associativity, is_associative)
    fn unary_operator_info(&self, op: &UnaryOperator) -> (u8, Assoc, bool) {
        match op {
            UnaryOperator::Arithmetic(_) => (35, Assoc::Right, false),
            UnaryOperator::Logical(LogicalUnaryOperator::Not) => {
                (35, Assoc::Right, false)
            }
            UnaryOperator::Reference(_) => (40, Assoc::Right, false),
            UnaryOperator::Bitwise(_) => (35, Assoc::Right, false),
        }
    }

    // precedence of an expression (used for children that are not binary/comparison)
    fn expression_precedence(&self, expression: &DatexExpression) -> u8 {
        match expression.data() {
            DatexExpressionData::BinaryOperation(BinaryOperation {
                operator,
                ..
            }) => {
                let (prec, _, _) = self.binary_operator_info(operator);
                prec
            }
            DatexExpressionData::ComparisonOperation(ComparisonOperation {
                operator,
                ..
            }) => {
                let (prec, _, _) = self.comparison_operator_info(operator);
                prec
            }
            DatexExpressionData::UnaryOperation(UnaryOperation {
                operator: op,
                ..
            }) => {
                let (prec, _, _) = self.unary_operator_info(op);
                prec
            }
            DatexExpressionData::CreateShared(_) => 40,
            _ => 255, // never need parens
        }
    }

    /// Decide if a child binary expression needs parentheses when placed under a parent operator.
    /// `parent_prec` is precedence of parent operator, `parent_assoc` its associativity.
    /// `is_left_child` indicates whether the child is the left operand.
    fn needs_parens_for_child_expr(
        &self,
        child: &DatexExpression,
        parent_context: &ParentContext<'a>,
        is_left_child: bool,
    ) -> bool {
        // compute child's precedence (based on its expression kind)
        let child_prec = self.expression_precedence(child);

        if child_prec < parent_context.precedence {
            return true; // child binds weaker -> parens required
        }
        if child_prec > parent_context.precedence {
            return false; // child binds stronger -> safe without parens
        }

        // equal precedence, need to inspect operator identity & associativity
        // If both child and parent are binary/comparison/unary, we can check operator identity
        // and whether that operator is associative (so we can drop parens for same-op associative cases).

        // check if same operator and is associative
        let same_op_and_assoc = match (child.data(), &parent_context.operation)
        {
            (
                DatexExpressionData::BinaryOperation(BinaryOperation {
                    operator,
                    ..
                }),
                Operation::Binary(parent_op),
            ) => {
                let (_, _, c_is_assoc) = self.binary_operator_info(operator);
                operator == *parent_op && c_is_assoc
            }
            (
                DatexExpressionData::ComparisonOperation(ComparisonOperation {
                    operator,
                    ..
                }),
                Operation::Comparison(parent_op),
            ) => {
                let (_, _, c_is_assoc) =
                    self.comparison_operator_info(operator);
                operator == *parent_op && c_is_assoc
            }
            (
                DatexExpressionData::UnaryOperation(UnaryOperation {
                    operator,
                    ..
                }),
                Operation::Unary(parent_op),
            ) => {
                let (_, _, c_is_assoc) = self.unary_operator_info(operator);
                operator == *parent_op && c_is_assoc
            }
            _ => false,
        };

        if same_op_and_assoc {
            // associative same op and precedence -> safe without parens
            return false;
        }

        // fallback to parent associativity + which side the child is on
        match parent_context.associativity {
            Assoc::Left => {
                // left-assoc: right child with equal precedence needs parens
                !is_left_child
            }
            Assoc::Right => {
                // right-assoc: left child with equal precedence needs parens
                is_left_child
            }
            Assoc::None => {
                // non-associative -> always need parens for equal-precedence children
                true
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        fmt::options::{BracketStyle, FormattingOptions},
        prelude::*,
    };

    fn to_string(script: &str, options: FormattingOptions) -> String {
        let formatter = Formatter::new(script, options);
        formatter.render()
    }

    #[test]
    #[ignore = "bracketing must be fixed"]
    fn bracketing() {
        let expr = "((42))";
        assert_eq!(
            to_string(
                expr,
                FormattingOptions {
                    bracket_style: BracketStyle::KeepAll,
                    ..Default::default()
                }
            ),
            "((42))"
        );
        assert_eq!(
            to_string(
                expr,
                FormattingOptions {
                    bracket_style: BracketStyle::RemoveDuplicate,
                    ..Default::default()
                }
            ),
            "(42)"
        );
        assert_eq!(
            to_string(
                expr,
                FormattingOptions {
                    bracket_style: BracketStyle::Minimal,
                    ..Default::default()
                }
            ),
            "42"
        );
    }

    #[test]
    #[ignore = "bracketing must be fixed"]
    fn binary_operations_wrapped() {
        // (1 + 2) * 3 requires parentheses around (1 + 2)
        let expr = "(1 + 2) * 3 - 4 / 5";
        assert_eq!(
            to_string(
                expr,
                FormattingOptions {
                    bracket_style: BracketStyle::Minimal,
                    ..Default::default()
                }
            ),
            "(1 + 2) * 3 - 4 / 5"
        );

        // 1 + (2 * 3) doesn't require parentheses
        let expr = "1 + (2 * 3) - 4 / 5";
        assert_eq!(
            to_string(
                expr,
                FormattingOptions {
                    bracket_style: BracketStyle::Minimal,
                    ..Default::default()
                }
            ),
            "1 + 2 * 3 - 4 / 5"
        );
    }

    #[test]
    fn associative_operations_no_parens_needed() {
        // (1 + 2) + 3  ->  1 + 2 + 3
        let expr = "(1 + 2) + 3";
        assert_eq!(
            to_string(
                expr,
                FormattingOptions {
                    bracket_style: BracketStyle::Minimal,
                    ..Default::default()
                }
            ),
            "1 + 2 + 3"
        );

        // 1 + (2 + 3)  ->  1 + 2 + 3
        let expr = "1 + (2 + 3)";
        assert_eq!(
            to_string(
                expr,
                FormattingOptions {
                    bracket_style: BracketStyle::Minimal,
                    ..Default::default()
                }
            ),
            "1 + 2 + 3"
        );
    }

    #[test]
    #[ignore = "bracketing must be fixed"]
    fn non_associative_operations_keep_parens() {
        // 1 - (2 - 3) must keep parentheses
        let expr = "1 - (2 - 3)";
        assert_eq!(
            to_string(
                expr,
                FormattingOptions {
                    bracket_style: BracketStyle::Minimal,
                    ..Default::default()
                }
            ),
            "1 - (2 - 3)"
        );

        // (1 - 2) - 3 may drop parentheses
        let expr = "(1 - 2) - 3";
        assert_eq!(
            to_string(
                expr,
                FormattingOptions {
                    bracket_style: BracketStyle::Minimal,
                    ..Default::default()
                }
            ),
            "1 - 2 - 3"
        );
    }

    #[test]
    #[ignore = "bracketing must be fixed"]
    fn power_operator_right_associative() {
        // Power is right-associative: 2 ^ (3 ^ 4) -> no parens needed
        let expr = "2 ^ (3 ^ 4)";
        assert_eq!(
            to_string(
                expr,
                FormattingOptions {
                    bracket_style: BracketStyle::Minimal,
                    ..Default::default()
                }
            ),
            "2 ^ 3 ^ 4"
        );

        // (2 ^ 3) ^ 4 -> needs parens to preserve grouping
        let expr = "(2 ^ 3) ^ 4";
        assert_eq!(
            to_string(
                expr,
                FormattingOptions {
                    bracket_style: BracketStyle::Minimal,
                    ..Default::default()
                }
            ),
            "(2 ^ 3) ^ 4"
        );
    }

    #[test]
    #[ignore = "bracketing must be fixed"]
    fn logical_and_or_precedence() {
        // (a && b) || c -> we don't need parentheses
        let expr = "(true and false) or true";
        assert_eq!(
            to_string(
                expr,
                FormattingOptions {
                    bracket_style: BracketStyle::Minimal,
                    ..Default::default()
                }
            ),
            "true and false or true"
        );

        // a && (b || c) -> parentheses required
        let expr = "true and (false or true)";
        assert_eq!(
            to_string(
                expr,
                FormattingOptions {
                    bracket_style: BracketStyle::Minimal,
                    ..Default::default()
                }
            ),
            "true and (false or true)"
        );
    }

    #[test]
    #[ignore = "bracketing must be fixed"]
    fn remove_duplicate_brackets() {
        // (((1 + 2))) -> (1 + 2)
        let expr = "(((1 + 2)))";
        assert_eq!(
            to_string(
                expr,
                FormattingOptions {
                    bracket_style: BracketStyle::RemoveDuplicate,
                    ..Default::default()
                }
            ),
            "(1 + 2)"
        );
    }

    #[test]
    fn keep_all_brackets_exactly() {
        // Keep exactly what the user wrote
        let expr = "(((1 + 2)))";
        assert_eq!(
            to_string(
                expr,
                FormattingOptions {
                    bracket_style: BracketStyle::KeepAll,
                    ..Default::default()
                }
            ),
            "(((1 + 2)))"
        );
    }

    #[test]
    fn minimal_vs_keepall_equivalence_for_simple() {
        let expr = "1 + 2 * 3";
        let minimal = to_string(
            expr,
            FormattingOptions {
                bracket_style: BracketStyle::Minimal,
                ..Default::default()
            },
        );
        let keep_all = to_string(
            expr,
            FormattingOptions {
                bracket_style: BracketStyle::KeepAll,
                ..Default::default()
            },
        );
        assert_eq!(minimal, keep_all);
        assert_eq!(minimal, "1 + 2 * 3");
    }
}