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
use std::collections::HashSet;

use sway_error::error::CompileError;
use sway_types::{Ident, Span};

use crate::{
    decl_engine::DeclEngine, error::*, language::ty, type_system::TypeId, Engines, TypeInfo,
};

use super::{
    patstack::PatStack,
    pattern::{EnumPattern, Pattern, StructPattern},
    range::Range,
};

pub(crate) struct ConstructorFactory {
    possible_types: Vec<TypeInfo>,
}

impl ConstructorFactory {
    pub(crate) fn new(engines: Engines<'_>, type_id: TypeId) -> Self {
        let possible_types = engines.te().get(type_id).extract_nested_types(engines);
        ConstructorFactory { possible_types }
    }

    /// Given Σ, computes a `Pattern` not present in Σ from the type of the
    /// elements of Σ. If more than one `Pattern` is found, these patterns are
    /// wrapped in an or-pattern.
    ///
    /// For example, given this Σ:
    ///
    /// ```ignore
    /// [
    ///     Pattern::U64(Range { first: std::u64::MIN, last: 3 }),
    ///     Pattern::U64(Range { first: 16, last: std::u64::MAX })
    /// ]
    /// ```
    ///
    /// this would result in this `Pattern`:
    ///
    /// ```ignore
    /// Pattern::U64(Range { first: 4, last: 15 })
    /// ```
    ///
    /// Given this Σ (which is more likely to occur than the above example):
    ///
    /// ```ignore
    /// [
    ///     Pattern::U64(Range { first: 2, last: 3 }),
    ///     Pattern::U64(Range { first: 16, last: 17 })
    /// ]
    /// ```
    ///
    /// this would result in this `Pattern`:
    ///
    /// ```ignore
    /// Pattern::Or([
    ///     Pattern::U64(Range { first: std::u64::MIN, last: 1 }),
    ///     Pattern::U64(Range { first: 4, last: 15 }),
    ///     Pattern::U64(Range { first: 18, last: std::u64::MAX })
    /// ])
    /// ```
    pub(crate) fn create_pattern_not_present(
        &self,
        engines: Engines<'_>,
        sigma: PatStack,
        span: &Span,
    ) -> CompileResult<Pattern> {
        let mut warnings = vec![];
        let mut errors = vec![];
        let (first, rest) = check!(
            sigma.flatten().filter_out_wildcards().split_first(span),
            return err(warnings, errors),
            warnings,
            errors
        );
        let pat = match first {
            Pattern::U8(range) => {
                let mut ranges = vec![range];
                for pat in rest.into_iter() {
                    match pat {
                        Pattern::U8(range) => ranges.push(range),
                        _ => {
                            errors.push(CompileError::Internal(
                                "expected all patterns to be of the same type",
                                span.clone(),
                            ));
                            return err(warnings, errors);
                        }
                    }
                }
                let unincluded: PatStack = check!(
                    Range::find_exclusionary_ranges(ranges, Range::u8(), span),
                    return err(warnings, errors),
                    warnings,
                    errors
                )
                .into_iter()
                .map(Pattern::U8)
                .collect::<Vec<_>>()
                .into();
                check!(
                    Pattern::from_pat_stack(unincluded, span),
                    return err(warnings, errors),
                    warnings,
                    errors
                )
            }
            Pattern::U16(range) => {
                let mut ranges = vec![range];
                for pat in rest.into_iter() {
                    match pat {
                        Pattern::U16(range) => ranges.push(range),
                        _ => {
                            errors.push(CompileError::Internal(
                                "expected all patterns to be of the same type",
                                span.clone(),
                            ));
                            return err(warnings, errors);
                        }
                    }
                }
                let unincluded: PatStack = check!(
                    Range::find_exclusionary_ranges(ranges, Range::u16(), span),
                    return err(warnings, errors),
                    warnings,
                    errors
                )
                .into_iter()
                .map(Pattern::U16)
                .collect::<Vec<_>>()
                .into();
                check!(
                    Pattern::from_pat_stack(unincluded, span),
                    return err(warnings, errors),
                    warnings,
                    errors
                )
            }
            Pattern::U32(range) => {
                let mut ranges = vec![range];
                for pat in rest.into_iter() {
                    match pat {
                        Pattern::U32(range) => ranges.push(range),
                        _ => {
                            errors.push(CompileError::Internal(
                                "expected all patterns to be of the same type",
                                span.clone(),
                            ));
                            return err(warnings, errors);
                        }
                    }
                }
                let unincluded: PatStack = check!(
                    Range::find_exclusionary_ranges(ranges, Range::u32(), span),
                    return err(warnings, errors),
                    warnings,
                    errors
                )
                .into_iter()
                .map(Pattern::U32)
                .collect::<Vec<_>>()
                .into();
                check!(
                    Pattern::from_pat_stack(unincluded, span),
                    return err(warnings, errors),
                    warnings,
                    errors
                )
            }
            Pattern::U64(range) => {
                let mut ranges = vec![range];
                for pat in rest.into_iter() {
                    match pat {
                        Pattern::U64(range) => ranges.push(range),
                        _ => {
                            errors.push(CompileError::Internal(
                                "expected all patterns to be of the same type",
                                span.clone(),
                            ));
                            return err(warnings, errors);
                        }
                    }
                }
                let unincluded: PatStack = check!(
                    Range::find_exclusionary_ranges(ranges, Range::u64(), span),
                    return err(warnings, errors),
                    warnings,
                    errors
                )
                .into_iter()
                .map(Pattern::U64)
                .collect::<Vec<_>>()
                .into();
                check!(
                    Pattern::from_pat_stack(unincluded, span),
                    return err(warnings, errors),
                    warnings,
                    errors
                )
            }
            Pattern::Numeric(range) => {
                let mut ranges = vec![range];
                for pat in rest.into_iter() {
                    match pat {
                        Pattern::Numeric(range) => ranges.push(range),
                        _ => {
                            errors.push(CompileError::Internal(
                                "expected all patterns to be of the same type",
                                span.clone(),
                            ));
                            return err(warnings, errors);
                        }
                    }
                }
                let unincluded: PatStack = check!(
                    Range::find_exclusionary_ranges(ranges, Range::u64(), span),
                    return err(warnings, errors),
                    warnings,
                    errors
                )
                .into_iter()
                .map(Pattern::Numeric)
                .collect::<Vec<_>>()
                .into();
                check!(
                    Pattern::from_pat_stack(unincluded, span),
                    return err(warnings, errors),
                    warnings,
                    errors
                )
            }
            // we will not present every string case
            Pattern::String(_) => Pattern::Wildcard,
            Pattern::Wildcard => Pattern::Wildcard,
            // we will not present every b256 case
            Pattern::B256(_) => Pattern::Wildcard,
            Pattern::Boolean(b) => {
                let mut true_found = false;
                let mut false_found = false;
                if b {
                    true_found = true;
                } else {
                    false_found = true;
                }
                if rest.contains(&Pattern::Boolean(true)) {
                    true_found = true;
                } else if rest.contains(&Pattern::Boolean(false)) {
                    false_found = true;
                }
                if true_found && false_found {
                    errors.push(CompileError::Internal(
                        "unable to create a new pattern",
                        span.clone(),
                    ));
                    return err(warnings, errors);
                } else if true_found {
                    Pattern::Boolean(false)
                } else {
                    Pattern::Boolean(true)
                }
            }
            Pattern::Struct(struct_pattern) => {
                let fields = struct_pattern
                    .fields()
                    .iter()
                    .map(|(name, _)| (name.clone(), Pattern::Wildcard))
                    .collect::<Vec<_>>();
                Pattern::Struct(StructPattern::new(
                    struct_pattern.struct_name().clone(),
                    fields,
                ))
            }
            ref pat @ Pattern::Enum(ref enum_pattern) => {
                let type_info = check!(
                    self.resolve_possible_types(pat, span, engines.de()),
                    return err(warnings, errors),
                    warnings,
                    errors
                );
                let enum_decl = engines.de().get_enum(&check!(
                    type_info.expect_enum(engines, "", span),
                    return err(warnings, errors),
                    warnings,
                    errors
                ));
                let enum_name = enum_decl.call_path.suffix;
                let enum_variants = enum_decl.variants;
                let (all_variants, variant_tracker) = check!(
                    ConstructorFactory::resolve_enum(
                        &enum_name,
                        &enum_variants,
                        enum_pattern,
                        rest,
                        span
                    ),
                    return err(warnings, errors),
                    warnings,
                    errors
                );
                check!(
                    Pattern::from_pat_stack(
                        PatStack::from(
                            all_variants
                                .difference(&variant_tracker)
                                .map(|x| {
                                    Pattern::Enum(EnumPattern {
                                        enum_name: enum_name.to_string(),
                                        variant_name: x.clone(),
                                        value: Box::new(Pattern::Wildcard),
                                    })
                                })
                                .collect::<Vec<_>>()
                        ),
                        span
                    ),
                    return err(warnings, errors),
                    warnings,
                    errors
                )
            }
            Pattern::Tuple(elems) => Pattern::Tuple(PatStack::fill_wildcards(elems.len())),
            Pattern::Or(_) => {
                errors.push(CompileError::Unimplemented(
                    "or patterns are not supported",
                    span.clone(),
                ));
                return err(warnings, errors);
            }
        };
        ok(pat, warnings, errors)
    }

    /// Reports if the `PatStack` Σ is a "complete signature" of the type of the
    /// elements of Σ.
    ///
    /// For example, a Σ composed of `Pattern::U64(..)`s would need to check for
    /// if it is a complete signature for the `U64` pattern type. Versus a Σ
    /// composed of `Pattern::Tuple([.., ..])` which would need to check for if
    /// it is a complete signature for "`Tuple` with 2 sub-patterns" type.
    ///
    /// There are several rules with which to determine if Σ is a complete
    /// signature:
    ///
    /// 1. If Σ is empty it is not a complete signature.
    /// 2. If Σ contains only wildcard patterns, it is not a complete signature.
    /// 3. If Σ contains all constructors for the type of the elements of Σ then
    ///    it is a complete signature.
    ///
    /// For example, given this Σ:
    ///
    /// ```ignore
    /// [
    ///     Pattern::U64(Range { first: 0, last: 0 }),
    ///     Pattern::U64(Range { first: 7, last: 7 })
    /// ]
    /// ```
    ///
    /// this would not be a complete signature as it does not contain all
    /// elements from the `U64` type.
    ///
    /// Given this Σ:
    ///
    /// ```ignore
    /// [
    ///     Pattern::U64(Range { first: std::u64::MIN, last: std::u64::MAX })
    /// ]
    /// ```
    ///
    /// this would be a complete signature as it does contain all elements from
    /// the `U64` type.
    ///
    /// Given this Σ:
    ///
    /// ```ignore
    /// [
    ///     Pattern::Tuple([
    ///         Pattern::U64(Range { first: 0, last: 0 }),
    ///         Pattern::Wildcard
    ///     ]),
    /// ]
    /// ```
    ///
    /// this would also be a complete signature as it does contain all elements
    /// from the "`Tuple` with 2 sub-patterns" type.
    pub(crate) fn is_complete_signature(
        &self,
        engines: Engines<'_>,
        pat_stack: &PatStack,
        span: &Span,
    ) -> CompileResult<bool> {
        let mut warnings = vec![];
        let mut errors = vec![];
        if pat_stack.is_empty() {
            return ok(false, warnings, errors);
        }
        if pat_stack.contains(&Pattern::Wildcard) {
            return ok(true, warnings, errors);
        }
        let (first, rest) = check!(
            pat_stack.split_first(span),
            return err(warnings, errors),
            warnings,
            errors
        );
        match first {
            // its assumed that no one is ever going to list every string
            Pattern::String(_) => ok(false, warnings, errors),
            // its assumed that no one is ever going to list every B256
            Pattern::B256(_) => ok(false, warnings, errors),
            Pattern::U8(range) => {
                let mut ranges = vec![range];
                for pat in rest.into_iter() {
                    match pat {
                        Pattern::U8(range) => ranges.push(range),
                        _ => {
                            errors.push(CompileError::Internal(
                                "expected all patterns to be of the same type",
                                span.clone(),
                            ));
                            return err(warnings, errors);
                        }
                    }
                }
                Range::do_ranges_equal_range(ranges, Range::u8(), span)
            }
            Pattern::U16(range) => {
                let mut ranges = vec![range];
                for pat in rest.into_iter() {
                    match pat {
                        Pattern::U16(range) => ranges.push(range),
                        _ => {
                            errors.push(CompileError::Internal(
                                "expected all patterns to be of the same type",
                                span.clone(),
                            ));
                            return err(warnings, errors);
                        }
                    }
                }
                Range::do_ranges_equal_range(ranges, Range::u16(), span)
            }
            Pattern::U32(range) => {
                let mut ranges = vec![range];
                for pat in rest.into_iter() {
                    match pat {
                        Pattern::U32(range) => ranges.push(range),
                        _ => {
                            errors.push(CompileError::Internal(
                                "expected all patterns to be of the same type",
                                span.clone(),
                            ));
                            return err(warnings, errors);
                        }
                    }
                }
                Range::do_ranges_equal_range(ranges, Range::u32(), span)
            }
            Pattern::U64(range) => {
                let mut ranges = vec![range];
                for pat in rest.into_iter() {
                    match pat {
                        Pattern::U64(range) => ranges.push(range),
                        _ => {
                            errors.push(CompileError::Internal(
                                "expected all patterns to be of the same type",
                                span.clone(),
                            ));
                            return err(warnings, errors);
                        }
                    }
                }
                Range::do_ranges_equal_range(ranges, Range::u64(), span)
            }
            Pattern::Numeric(range) => {
                let mut ranges = vec![range];
                for pat in rest.into_iter() {
                    match pat {
                        Pattern::Numeric(range) => ranges.push(range),
                        _ => {
                            errors.push(CompileError::Internal(
                                "expected all patterns to be of the same type",
                                span.clone(),
                            ));
                            return err(warnings, errors);
                        }
                    }
                }
                Range::do_ranges_equal_range(ranges, Range::u64(), span)
            }
            Pattern::Boolean(b) => {
                let mut true_found = false;
                let mut false_found = false;
                match b {
                    true => true_found = true,
                    false => false_found = true,
                }
                for pat in rest.iter() {
                    match pat {
                        Pattern::Boolean(b) => match b {
                            true => true_found = true,
                            false => false_found = true,
                        },
                        _ => {
                            errors.push(CompileError::Internal(
                                "expected all patterns to be of the same type",
                                span.clone(),
                            ));
                            return err(warnings, errors);
                        }
                    }
                }
                ok(true_found && false_found, warnings, errors)
            }
            ref pat @ Pattern::Enum(ref enum_pattern) => {
                let type_info = check!(
                    self.resolve_possible_types(pat, span, engines.de()),
                    return err(warnings, errors),
                    warnings,
                    errors
                );
                let enum_decl = engines.de().get_enum(&check!(
                    type_info.expect_enum(engines, "", span),
                    return err(warnings, errors),
                    warnings,
                    errors
                ));
                let enum_name = enum_decl.call_path.suffix;
                let enum_variants = enum_decl.variants;
                let (all_variants, variant_tracker) = check!(
                    ConstructorFactory::resolve_enum(
                        &enum_name,
                        &enum_variants,
                        enum_pattern,
                        rest,
                        span
                    ),
                    return err(warnings, errors),
                    warnings,
                    errors
                );
                ok(
                    all_variants.difference(&variant_tracker).next().is_none(),
                    warnings,
                    errors,
                )
            }
            ref tup @ Pattern::Tuple(_) => {
                for pat in rest.iter() {
                    if !pat.has_the_same_constructor(tup) {
                        return ok(false, warnings, errors);
                    }
                }
                ok(true, warnings, errors)
            }
            ref strct @ Pattern::Struct(_) => {
                for pat in rest.iter() {
                    if !pat.has_the_same_constructor(strct) {
                        return ok(false, warnings, errors);
                    }
                }
                ok(true, warnings, errors)
            }
            Pattern::Wildcard => {
                errors.push(CompileError::Internal(
                    "expected the wildcard pattern to be filtered out here",
                    span.clone(),
                ));
                err(warnings, errors)
            }
            Pattern::Or(_) => {
                errors.push(CompileError::Unimplemented(
                    "or patterns are not supported",
                    span.clone(),
                ));
                err(warnings, errors)
            }
        }
    }

    fn resolve_possible_types(
        &self,
        pattern: &Pattern,
        span: &Span,
        decl_engine: &DeclEngine,
    ) -> CompileResult<&TypeInfo> {
        let warnings = vec![];
        let mut errors = vec![];
        let mut type_info = None;
        for possible_type in self.possible_types.iter() {
            let matches = pattern.matches_type_info(possible_type, decl_engine);
            if matches {
                type_info = Some(possible_type);
                break;
            }
        }
        match type_info {
            Some(type_info) => ok(type_info, warnings, errors),
            None => {
                errors.push(CompileError::Internal(
                    "there is no type that matches this pattern",
                    span.clone(),
                ));
                err(warnings, errors)
            }
        }
    }

    fn resolve_enum(
        enum_name: &Ident,
        enum_variants: &[ty::TyEnumVariant],
        enum_pattern: &EnumPattern,
        rest: PatStack,
        span: &Span,
    ) -> CompileResult<(HashSet<String>, HashSet<String>)> {
        let warnings = vec![];
        let mut errors = vec![];
        if enum_pattern.enum_name.as_str() != enum_name.as_str() {
            errors.push(CompileError::Internal(
                "expected matching enum names",
                span.clone(),
            ));
            return err(warnings, errors);
        }
        let mut all_variants: HashSet<String> = HashSet::new();
        for variant in enum_variants.iter() {
            all_variants.insert(variant.name.to_string().clone());
        }
        let mut variant_tracker: HashSet<String> = HashSet::new();
        variant_tracker.insert(enum_pattern.variant_name.clone());
        for pat in rest.iter() {
            match pat {
                Pattern::Enum(enum_pattern2) => {
                    if enum_pattern2.enum_name.as_str() != enum_name.as_str() {
                        errors.push(CompileError::Internal(
                            "expected matching enum names",
                            span.clone(),
                        ));
                        return err(warnings, errors);
                    }
                    variant_tracker.insert(enum_pattern2.variant_name.to_string());
                }
                _ => {
                    errors.push(CompileError::Internal(
                        "expected all patterns to be of the same type",
                        span.clone(),
                    ));
                    return err(warnings, errors);
                }
            }
        }
        ok((all_variants, variant_tracker), warnings, errors)
    }
}