hamelin_legacy 0.3.9

Legacy AST translation code for Hamelin (to be deprecated)
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
use std::collections::HashMap;
use std::fmt::{Debug, Display, Formatter};
use std::rc::Rc;
use std::sync::Arc;

use antlr_rust::parser_rule_context::ParserRuleContext;
use antlr_rust::token::{CommonToken, Token};
use anyhow::anyhow;
use hamelin_lib::translation::ExpressionTranslation;
use ordermap::OrderMap;
use strsim;
use thiserror::Error;

use crate::ast::expression::HamelinExpression;
use crate::env::Environment;
use hamelin_lib::antlr::hamelinparser::{
    BinaryOperatorContext, ExpressionContextAll, FunctionCallContext, FunctionCallContextAttrs,
    NamedArgumentContextAll, NamedArgumentContextAttrs, PositionalArgumentContextAll,
    PositionalArgumentContextAttrs, SimpleIdentifierContextAll, UnaryPostfixOperatorContext,
    UnaryPostfixOperatorContextAttrs, UnaryPrefixOperatorContext, UnaryPrefixOperatorContextAttrs,
};
use hamelin_lib::err::{Context, TranslationError, TranslationErrors};
use hamelin_lib::func::def::{
    bind, FunctionBindFailure, FunctionDef, FunctionParameterBindingFailure,
    FunctionParameterBindingFailures, FunctionTranslationFailure,
};
use hamelin_lib::operator::Operator;
use hamelin_lib::parse_expression;
use hamelin_lib::sql::expression::apply::{FunctionCallApply, Lambda};
use hamelin_lib::sql::expression::identifier::HamelinSimpleIdentifier;
use hamelin_lib::sql::expression::identifier::{Identifier, SimpleIdentifier};
use hamelin_lib::types::array::Array;
use hamelin_lib::types::struct_type::Struct;
use hamelin_lib::types::Type;

use super::ExpressionTranslationContext;

pub trait CanMatchArgs {
    fn function_name(&self) -> Result<String, TranslationErrors>;
    fn positional(&self) -> Result<Vec<ExpressionTranslation>, TranslationErrors>;
    fn named(&self) -> Result<OrderMap<String, ExpressionTranslation>, TranslationErrors>;
    fn functions(&self) -> &HashMap<String, Vec<Arc<dyn FunctionDef>>>;
    fn expression_translation_context(&self) -> Rc<ExpressionTranslationContext>;

    /// Attempts to match a function definition based on the provided function name, positional
    /// arguments, named arguments, and a list of possible function definitions. If a match is
    /// found, it returns the translation of the function. If no match is found, it returns a
    /// map of function definitions to their respective error messages.
    ///
    /// # Arguments
    /// - `function_name` - the name of the function to match
    /// - `positional` - a list of positional arguments for the function
    /// - `named` - a map of named arguments for the function
    /// - `functions` - a list of possible function definitions to match against
    ///
    /// # Returns
    /// A Result containing either the translation of the matched function or a map of function
    /// definitions to their respective error messages
    fn match_function<'a, T>(&self, ctx: &T) -> Result<ExpressionTranslation, TranslationErrors>
    where
        T: ParserRuleContext<'a>,
    {
        let (function_name, positional, named) =
            TranslationErrors::from_3(self.function_name(), self.positional(), self.named())?;

        let mut attempts = vec![];
        let lookup_key = function_name.to_lowercase();
        for f in self.functions().get(&lookup_key).unwrap_or(&vec![]).iter() {
            match bind(&**f, positional.clone(), named.clone()) {
                Ok(resolution) => {
                    // Check if special position is allowed before translating
                    // This allows us to skip disallowed functions and try other candidates
                    if let Some(special_position) = (**f).special_position() {
                        let fctx = self.expression_translation_context();
                        if !fctx.fctx.specials_allowed.contains(&special_position) {
                            attempts.push(ApplyAttempt {
                                function_def: (**f).to_string(),
                                binding_failures: FunctionParameterBindingFailures(vec![
                                    FunctionParameterBindingFailure::DoesNotMatch(
                                        format!("{} not allowed here", special_position).into(),
                                    ),
                                ]),
                            });
                            continue;
                        }
                    }

                    let ectx = self.expression_translation_context();

                    match ectx.translation_registry.translate(
                        &**f,
                        &function_name,
                        &ectx.fctx,
                        resolution,
                    ) {
                        Ok(t) => {
                            let nested_special = positional
                                .iter()
                                .chain(named.values())
                                .flat_map(|t| {
                                    t.special
                                        .as_ref()
                                        .map(|s| (s.clone(), t.span.clone().unwrap()))
                                        .into_iter()
                                        .chain(t.nested_special.clone().into_iter())
                                })
                                .collect::<Vec<_>>();

                            match (**f).special_position() {
                                Some(s) => {
                                    if !nested_special.is_empty() {
                                        let err = TranslationError::msg(
                                            ctx,
                                            format!(
                                                "Nested special function calls not allowed in {}",
                                                s
                                            )
                                            .as_str(),
                                        )
                                        .with_context_vec(
                                            nested_special
                                                .into_iter()
                                                .map(|(sp, rng)| {
                                                    Context::new(rng, sp.to_string().as_str())
                                                })
                                                .collect(),
                                        )
                                        .single();

                                        return Err(err);
                                    } else {
                                        return Ok(t.clone().with_special(s));
                                    }
                                }
                                None => {
                                    if !nested_special.is_empty() {
                                        let mut res = t.clone();
                                        for (sp, rng) in nested_special.into_iter() {
                                            res = res.with_nested_special(sp, rng);
                                        }
                                        return Ok(res);
                                    } else {
                                        return Ok(t);
                                    }
                                }
                            }
                        }
                        Err(FunctionTranslationFailure::Fatal(e)) => {
                            return Err(TranslationError::wrap_box(ctx, e).into())
                        }
                    }
                }
                Err(FunctionBindFailure::ParameterBindingFailures(bf)) => {
                    attempts.push(ApplyAttempt {
                        function_def: (**f).to_string(),
                        binding_failures: bf,
                    });
                }
                Err(FunctionBindFailure::Fatal(e)) => {
                    return Err(TranslationError::wrap_box(ctx, e).into())
                }
            }
        }

        // Second pass to check all combinations of passthrough for array arguments
        // TODO: Get rid of this. I fucking hate it so much.
        if let Some(t) = self.match_function_array_passthrough(&positional, &named)? {
            return Ok(t);
        }

        if attempts.is_empty() {
            let all_functions = self.functions();
            let all_function_names: Vec<&String> = all_functions.keys().collect();
            let suggestions = find_similar_function_names(&function_name, &all_function_names, 5);
            let mut e = TranslationError::msg(ctx, "No matching function found");

            if !suggestions.is_empty() {
                e = e.with_source_boxed(
                    anyhow!(
                        "Did you mean one of these?\n{}",
                        suggestions
                            .iter()
                            .map(|s| format!("  - {}", s))
                            .collect::<Vec<_>>()
                            .join("\n")
                    )
                    .into(),
                );
            }

            Err(e.single())
        } else {
            let mut error =
                TranslationError::msg(ctx, "could not find a matching function definition")
                    .with_source(ApplyFailure(attempts));
            let args = positional
                .iter()
                .map(|p| (p.span.clone(), &p.typ))
                .chain(named.iter().map(|(_, v)| (v.span.clone(), &v.typ)));
            for (span, typ) in args {
                if let Some(s) = span {
                    error.add_context(s, &format!("{}", typ));
                }
            }
            Err(error.into())
        }
    }

    /// Attempts to match a function definition by considering the element types of array arguments
    /// for the provided function name, positional arguments, named arguments, and a list of
    /// possible function definitions. If a match is found, it returns the translation of the
    /// function with the necessary transformations applied. If no match is found, it returns an
    /// empty Optional.
    ///
    /// # Arguments
    /// - `function_name` - the name of the function to match
    /// - `positional` - a list of positional arguments for the function
    /// - `named` - a map of named arguments for the function
    /// - `functions` - a list of possible function definitions to match against
    ///
    /// # Returns
    /// An Optional containing the translation of the matched function with transformations, or
    /// an empty Optional if no match is found
    fn match_function_array_passthrough(
        &self,
        positional: &Vec<ExpressionTranslation>,
        named: &OrderMap<String, ExpressionTranslation>,
    ) -> Result<Option<ExpressionTranslation>, TranslationErrors> {
        let all_overrides = self.array_passthrough_overrides(positional)?;

        if all_overrides.is_empty() {
            return Ok(None);
        }

        let override_combinations = make_combinations(&all_overrides);
        for overrides in override_combinations {
            let mut new_positional = positional.clone();
            let mut new_named = named.clone();

            for override_ in &overrides {
                match override_ {
                    ArgumentOverride::NamedOverride(no) => {
                        new_named.insert(no.name.clone(), no.translation.clone());
                    }
                    ArgumentOverride::PositionalOverride(po) => {
                        new_positional[po.position] = po.translation.clone();
                    }
                }
            }

            let call_name = self.function_name()?;
            let call_name_lower = call_name.to_lowercase();
            let ectx = self.expression_translation_context();
            for f in self
                .functions()
                .get(&call_name_lower)
                .unwrap_or(&vec![])
                .iter()
            {
                if let Ok(res) = bind(&**f, new_positional.clone(), new_named.clone()) {
                    if let Ok(translation) = ectx
                        .translation_registry
                        .translate(&**f, &call_name, &ectx.fctx, res)
                    {
                        let mut expression = translation.sql;
                        for override_ in &overrides {
                            match override_ {
                                ArgumentOverride::NamedOverride(no) => {
                                    expression = FunctionCallApply::with_two(
                                        "transform",
                                        new_named.get(&no.name).unwrap().sql.clone(),
                                        Lambda::from_single_argument(
                                            no.identifier.clone(),
                                            expression,
                                        )
                                        .into(),
                                    )
                                    .into();
                                }
                                ArgumentOverride::PositionalOverride(po) => {
                                    expression = FunctionCallApply::with_two(
                                        "transform",
                                        positional.get(po.position).unwrap().sql.clone(),
                                        Lambda::from_single_argument(
                                            po.identifier.clone(),
                                            expression,
                                        )
                                        .into(),
                                    )
                                    .into();
                                }
                            }
                        }
                        return Ok(Some(ExpressionTranslation::with_defaults(
                            Array::new(translation.typ).into(),
                            expression,
                        )));
                    }
                }
            }
        }

        Ok(None)
    }

    /// Generates a list of argument overrides for array arguments. This method inspects the
    /// provided positional and named arguments, and for each argument that is an array, it
    /// creates an override that can be used to simulate the array element type as the argument.

    /// # Arguments
    /// - `positional_args` - a list of positional arguments for the function
    /// - `named_args` - a map of named arguments for the function
    ///
    /// # Returns
    /// a list of argument overrides for array arguments
    fn array_passthrough_overrides(
        &self,
        positional: &Vec<ExpressionTranslation>,
    ) -> Result<Vec<ArgumentOverride>, TranslationErrors> {
        let mut overrides = vec![];

        for (i, arg) in positional.iter().enumerate() {
            if let Type::Array(a) = &arg.typ {
                let reference_name = format!("e_{}", i);
                let reference_ident: Identifier = reference_name.parse()?;
                let reference_name_parsed = parse_expression(reference_name.clone())?;
                let new_env = Arc::new(Environment::new(
                    Struct::default().with(reference_ident, (*a.element_type).clone()),
                ));
                let new_context = self
                    .expression_translation_context()
                    .without_completion()
                    .with_env(new_env);
                let translation =
                    HamelinExpression::new(reference_name_parsed, new_context).translate()?;
                overrides.push(ArgumentOverride::PositionalOverride(PositionalOverride {
                    identifier: SimpleIdentifier::new(&reference_name),
                    translation,
                    position: i,
                }));
            }
        }

        for (key, value) in self.named()?.into_iter() {
            if let Type::Array(a) = value.typ {
                let reference_name = format!("e_{}", key);
                let reference_ident: Identifier = reference_name.parse()?;
                let reference_name_parsed = parse_expression(reference_name.clone())?;
                let new_env = Arc::new(Environment::new(
                    Struct::default().with(reference_ident, *a.element_type),
                ));
                let new_context = self
                    .expression_translation_context()
                    .without_completion()
                    .with_env(new_env);
                let translation =
                    HamelinExpression::new(reference_name_parsed, new_context).translate()?;
                overrides.push(ArgumentOverride::NamedOverride(NamedOverride {
                    identifier: SimpleIdentifier::new(&reference_name),
                    translation,
                    name: key.clone(),
                }));
            }
        }

        Ok(overrides)
    }
}

pub struct HamelinUnaryPrefixApply {
    expression: Rc<ExpressionContextAll<'static>>,
    operator: Box<CommonToken<'static>>,
    expression_translation_context: Rc<ExpressionTranslationContext>,
}

impl HamelinUnaryPrefixApply {
    pub fn try_new(
        tree: &UnaryPrefixOperatorContext<'static>,
        expression_translation_context: Rc<ExpressionTranslationContext>,
    ) -> Result<Self, TranslationErrors> {
        Ok(Self {
            expression: TranslationErrors::expect(tree, tree.expression().clone())?,
            operator: TranslationErrors::expect(tree, tree.operator.clone())?,
            expression_translation_context,
        })
    }
}

impl CanMatchArgs for HamelinUnaryPrefixApply {
    fn function_name(&self) -> Result<String, TranslationErrors> {
        Operator::of(self.operator.get_text().to_uppercase().as_str())
            .map(|o| o.to_string())
            .map_err(|e| {
                TranslationError::new(Context::new(
                    self.operator.get_start() as usize..=self.operator.get_stop() as usize,
                    "unexpected operator",
                ))
                .with_source_boxed(e.into())
                .into()
            })
    }

    fn positional(&self) -> Result<Vec<ExpressionTranslation>, TranslationErrors> {
        let expr = HamelinExpression::new(
            self.expression.clone(),
            self.expression_translation_context.clone(),
        );
        TranslationErrors::from_vec(vec![expr.translate()])
    }

    fn named(&self) -> Result<OrderMap<String, ExpressionTranslation>, TranslationErrors> {
        Ok(OrderMap::new())
    }

    fn functions(&self) -> &HashMap<String, Vec<Arc<dyn FunctionDef>>> {
        &self
            .expression_translation_context
            .registry
            .unary_prefix_operation_defs
    }

    fn expression_translation_context(&self) -> Rc<ExpressionTranslationContext> {
        self.expression_translation_context.clone()
    }
}

pub struct HamelinUnaryPostfixApply {
    expression: Rc<ExpressionContextAll<'static>>,
    operator: Box<CommonToken<'static>>,
    expression_translation_context: Rc<ExpressionTranslationContext>,
}

impl CanMatchArgs for HamelinUnaryPostfixApply {
    fn function_name(&self) -> Result<String, TranslationErrors> {
        Operator::of(self.operator.get_text().to_uppercase().as_str())
            .map(|o| o.to_string())
            .map_err(|e| {
                TranslationError::new(Context::new(
                    self.operator.get_start() as usize..=self.operator.get_stop() as usize,
                    "unexpected operator",
                ))
                .with_source_boxed(e.into())
                .into()
            })
    }

    fn functions(&self) -> &HashMap<String, Vec<Arc<dyn FunctionDef>>> {
        &self
            .expression_translation_context
            .registry
            .unary_postfix_operation_defs
    }

    fn positional(&self) -> Result<Vec<ExpressionTranslation>, TranslationErrors> {
        let expr = HamelinExpression::new(
            self.expression.clone(),
            self.expression_translation_context.clone(),
        );
        TranslationErrors::from_vec(vec![expr.translate()])
    }

    fn named(&self) -> Result<OrderMap<String, ExpressionTranslation>, TranslationErrors> {
        Ok(OrderMap::new())
    }

    fn expression_translation_context(&self) -> Rc<ExpressionTranslationContext> {
        self.expression_translation_context.clone()
    }
}

impl HamelinUnaryPostfixApply {
    pub fn try_new(
        tree: &UnaryPostfixOperatorContext<'static>,
        expression_translation_context: Rc<ExpressionTranslationContext>,
    ) -> Result<Self, TranslationErrors> {
        Ok(Self {
            expression: TranslationErrors::expect(tree, tree.expression().clone())?,
            operator: TranslationErrors::expect(tree, tree.operator.clone())?,
            expression_translation_context,
        })
    }
}

pub struct HamelinBinaryOperatorApply {
    left: Rc<ExpressionContextAll<'static>>,
    right: Rc<ExpressionContextAll<'static>>,
    operator: Box<CommonToken<'static>>,
    expression_translation_context: Rc<ExpressionTranslationContext>,
}

impl HamelinBinaryOperatorApply {
    pub fn try_new(
        tree: &BinaryOperatorContext<'static>,
        expression_translation_context: Rc<ExpressionTranslationContext>,
    ) -> Result<Self, TranslationErrors> {
        Ok(Self {
            left: TranslationErrors::expect(tree, tree.left.clone())?,
            right: TranslationErrors::expect(tree, tree.right.clone())?,
            operator: TranslationErrors::expect(tree, tree.operator.clone())?,
            expression_translation_context,
        })
    }
}

impl CanMatchArgs for HamelinBinaryOperatorApply {
    fn function_name(&self) -> Result<String, TranslationErrors> {
        Operator::of(self.operator.get_text().to_uppercase().as_str())
            .map(|o| o.to_string())
            .map_err(|e| {
                TranslationError::new(Context::new(
                    self.operator.get_start() as usize..=self.operator.get_stop() as usize,
                    "unexpected operator",
                ))
                .with_source_boxed(e.into())
                .into()
            })
    }

    fn positional(&self) -> Result<Vec<ExpressionTranslation>, TranslationErrors> {
        let left = HamelinExpression::new(
            self.left.clone(),
            self.expression_translation_context.clone(),
        );
        let right = HamelinExpression::new(
            self.right.clone(),
            self.expression_translation_context.clone(),
        );

        TranslationErrors::from_vec(vec![left.translate(), right.translate()])
    }

    fn named(&self) -> Result<OrderMap<String, ExpressionTranslation>, TranslationErrors> {
        Ok(OrderMap::new())
    }

    fn functions(&self) -> &HashMap<String, Vec<Arc<dyn FunctionDef>>> {
        &self
            .expression_translation_context
            .registry
            .binary_operation_defs
    }

    fn expression_translation_context(&self) -> Rc<ExpressionTranslationContext> {
        self.expression_translation_context.clone()
    }
}

pub struct HamelinFunctionCallApply {
    function_name: Rc<SimpleIdentifierContextAll<'static>>,
    positional_arguments: Vec<Rc<PositionalArgumentContextAll<'static>>>,
    named_arguments: Vec<Rc<NamedArgumentContextAll<'static>>>,
    expression_translation_context: Rc<ExpressionTranslationContext>,
}

impl HamelinFunctionCallApply {
    pub fn try_new(
        tree: &FunctionCallContext<'static>,
        expression_translation_context: Rc<ExpressionTranslationContext>,
    ) -> Result<Self, TranslationErrors> {
        Ok(Self {
            function_name: TranslationErrors::expect(tree, tree.functionName.clone())?,
            named_arguments: tree.namedArgument_all().clone(),
            positional_arguments: tree.positionalArgument_all().clone(),
            expression_translation_context,
        })
    }
}

impl CanMatchArgs for HamelinFunctionCallApply {
    fn function_name(&self) -> Result<String, TranslationErrors> {
        Ok(HamelinSimpleIdentifier::new(self.function_name.clone())
            .to_sql()?
            .name
            .to_lowercase())
    }

    fn positional(&self) -> Result<Vec<ExpressionTranslation>, TranslationErrors> {
        TranslationErrors::from_vec(
            self.positional_arguments
                .iter()
                .map(|pa| {
                    TranslationErrors::expect(pa.as_ref(), pa.expression()).and_then(|exp| {
                        HamelinExpression::new(exp, self.expression_translation_context.clone())
                            .translate()
                    })
                })
                .collect(),
        )
    }

    fn named(&self) -> Result<OrderMap<String, ExpressionTranslation>, TranslationErrors> {
        let keys = TranslationErrors::from_vec(
            self.named_arguments
                .iter()
                .map(|ctx| {
                    TranslationErrors::expect(ctx.as_ref(), ctx.simpleIdentifier())
                        .and_then(|si| HamelinSimpleIdentifier::new(si).to_sql())
                })
                .collect(),
        );

        let values = TranslationErrors::from_vec(
            self.named_arguments
                .iter()
                .map(|ctx| {
                    TranslationErrors::expect(ctx.as_ref(), ctx.expression()).and_then(|e| {
                        HamelinExpression::new(e, self.expression_translation_context.clone())
                            .translate()
                    })
                })
                .collect(),
        );

        let (keys, values) = TranslationErrors::from_2(keys, values)?;

        Ok(keys
            .into_iter()
            .map(|k| k.name.to_lowercase())
            .zip(values.into_iter())
            .collect())
    }

    fn functions(&self) -> &HashMap<String, Vec<Arc<dyn FunctionDef>>> {
        &self.expression_translation_context.registry.function_defs
    }

    fn expression_translation_context(&self) -> Rc<ExpressionTranslationContext> {
        self.expression_translation_context.clone()
    }
}

#[derive(Error, Debug)]
#[error("Attempted {function_def}\n{binding_failures}")]
pub struct ApplyAttempt {
    pub function_def: String,
    pub binding_failures: FunctionParameterBindingFailures,
}
#[derive(Error, Debug)]
pub struct ApplyFailure(pub Vec<ApplyAttempt>);

impl Display for ApplyFailure {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        for attempt in self.0.iter() {
            write!(f, "{}\n", attempt)?;
        }
        Ok(())
    }
}

#[derive(Clone)]
pub enum ArgumentOverride {
    PositionalOverride(PositionalOverride),
    NamedOverride(NamedOverride),
}

#[derive(Clone)]
pub struct PositionalOverride {
    pub identifier: SimpleIdentifier,
    pub translation: ExpressionTranslation,
    pub position: usize,
}

#[derive(Clone)]
pub struct NamedOverride {
    pub identifier: SimpleIdentifier,
    pub translation: ExpressionTranslation,
    pub name: String,
}

/// Generates all possible combinations of argument overrides. This method takes a list of argument
/// overrides and generates all possible combinations of those overrides. The original combination
/// (no overrides) is removed from the result.
/// # Arguments
/// - `overrides` - a list of argument overrides
///
/// # Returns
/// a list of all possible combinations of argument overrides
fn make_combinations(overrides: &[ArgumentOverride]) -> Vec<Vec<ArgumentOverride>> {
    let mut result: Vec<Vec<ArgumentOverride>> = vec![vec![]];

    for element in overrides {
        let current_size = result.len();
        for i in 0..current_size {
            let mut new_combination = result[i].clone();
            new_combination.push(element.clone());
            result.push(new_combination);
        }
    }

    // remove the original combination (no overrides)
    result.remove(0);
    result
}

/// Finds similar function names based on multiple similarity algorithms
fn find_similar_function_names(
    target: &str,
    available: &[&String],
    max_suggestions: usize,
) -> Vec<String> {
    let mut candidates: Vec<(String, f64)> = Vec::new();
    let target_lower = target.to_lowercase();

    for &func_name in available {
        let func_lower = func_name.to_lowercase();
        let mut score = 0.0f64;

        // Exact match (case insensitive) - highest priority
        if target_lower == func_lower {
            score = 1.0;
        }
        // Target is substring of function name
        else if func_lower.contains(&target_lower) {
            let length_penalty = (func_name.len() - target.len()) as f64 / func_name.len() as f64;
            score = 0.9 - (length_penalty * 0.3);
        }
        // Function name is substring of target
        else if target_lower.contains(&func_lower) {
            let length_penalty = (target.len() - func_name.len()) as f64 / target.len() as f64;
            score = 0.8 - (length_penalty * 0.3);
        }
        // Fuzzy matching using multiple algorithms
        else {
            // Use Jaro-Winkler for fuzzy string matching (good for typos and similar strings)
            let jaro_winkler = strsim::jaro_winkler(&target_lower, &func_lower);

            // Use normalized Levenshtein (Damerau-Levenshtein for transpositions)
            let normalized_levenshtein =
                strsim::normalized_damerau_levenshtein(&target_lower, &func_lower);

            // Combine scores with weights favoring Jaro-Winkler for typos
            let combined_score = (jaro_winkler * 0.7) + (normalized_levenshtein * 0.3);

            // Only suggest if similarity is reasonably high
            if combined_score >= 0.6 {
                score = combined_score * 0.7; // Scale down to be less than substring matches
            }
        }

        if score > 0.0 {
            candidates.push((func_name.clone(), score));
        }
    }

    // Sort by score (highest first), then by name for consistency
    candidates.sort_by(|a, b| {
        b.1.partial_cmp(&a.1)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then(a.0.cmp(&b.0))
    });

    // Take top suggestions
    candidates
        .into_iter()
        .take(max_suggestions)
        .map(|(name, _)| name)
        .collect()
}