sway_core/language/ty/declaration/
function.rs

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
use std::{
    fmt,
    hash::{Hash, Hasher},
};

use monomorphization::MonomorphizeHelper;
use sha2::{Digest, Sha256};
use sway_error::handler::{ErrorEmitted, Handler};

use crate::{
    has_changes,
    language::{
        parsed::{FunctionDeclaration, FunctionDeclarationKind},
        CallPath,
    },
    transform::AttributeKind,
};

use crate::{
    decl_engine::*,
    engine_threading::*,
    language::{parsed, ty::*, Inline, Purity, Visibility},
    semantic_analysis::TypeCheckContext,
    transform,
    type_system::*,
    types::*,
};

use sway_types::{
    constants::{INLINE_ALWAYS_NAME, INLINE_NEVER_NAME},
    Ident, Named, Span, Spanned,
};

#[derive(Clone, Debug)]
pub enum TyFunctionDeclKind {
    Default,
    Entry,
    Main,
    Test,
}

#[derive(Clone, Debug)]
pub struct TyFunctionDecl {
    pub name: Ident,
    pub body: TyCodeBlock,
    pub parameters: Vec<TyFunctionParameter>,
    pub implementing_type: Option<TyDecl>,
    pub implementing_for_typeid: Option<TypeId>,
    pub span: Span,
    pub call_path: CallPath,
    pub attributes: transform::AttributesMap,
    pub type_parameters: Vec<TypeParameter>,
    pub return_type: TypeArgument,
    pub visibility: Visibility,
    /// whether this function exists in another contract and requires a call to it or not
    pub is_contract_call: bool,
    pub purity: Purity,
    pub where_clause: Vec<(Ident, Vec<TraitConstraint>)>,
    pub is_trait_method_dummy: bool,
    pub is_type_check_finalized: bool,
    pub kind: TyFunctionDeclKind,
}

impl TyDeclParsedType for TyFunctionDecl {
    type ParsedType = FunctionDeclaration;
}

impl DebugWithEngines for TyFunctionDecl {
    fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
        write!(
            f,
            "{}{:?}{}({}):{}->{}",
            if self.is_trait_method_dummy {
                "dummy ".to_string()
            } else {
                "".to_string()
            },
            self.name,
            if !self.type_parameters.is_empty() {
                format!(
                    "<{}>",
                    self.type_parameters
                        .iter()
                        .map(|p| format!(
                            "{:?} -> {:?}",
                            engines.help_out(p.initial_type_id),
                            engines.help_out(p.type_id)
                        ))
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            } else {
                "".to_string()
            },
            self.parameters
                .iter()
                .map(|p| format!(
                    "{}:{}",
                    p.name.as_str(),
                    engines.help_out(p.type_argument.initial_type_id)
                ))
                .collect::<Vec<_>>()
                .join(", "),
            engines.help_out(self.return_type.initial_type_id),
            engines.help_out(self.return_type.type_id),
        )
    }
}

impl DisplayWithEngines for TyFunctionDecl {
    fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
        write!(
            f,
            "{}{}({}) -> {}",
            self.name,
            if !self.type_parameters.is_empty() {
                format!(
                    "<{}>",
                    self.type_parameters
                        .iter()
                        .map(|p| format!("{}", engines.help_out(p.initial_type_id)))
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            } else {
                "".to_string()
            },
            self.parameters
                .iter()
                .map(|p| format!(
                    "{}: {}",
                    p.name.as_str(),
                    engines.help_out(p.type_argument.initial_type_id)
                ))
                .collect::<Vec<_>>()
                .join(", "),
            engines.help_out(self.return_type.initial_type_id),
        )
    }
}

impl Named for TyFunctionDecl {
    fn name(&self) -> &Ident {
        &self.name
    }
}

impl IsConcrete for TyFunctionDecl {
    fn is_concrete(&self, engines: &Engines) -> bool {
        self.type_parameters
            .iter()
            .all(|tp| tp.is_concrete(engines))
            && self
                .return_type
                .type_id
                .is_concrete(engines, TreatNumericAs::Concrete)
            && self.parameters().iter().all(|t| {
                t.type_argument
                    .type_id
                    .is_concrete(engines, TreatNumericAs::Concrete)
            })
    }
}
impl declaration::FunctionSignature for TyFunctionDecl {
    fn parameters(&self) -> &Vec<TyFunctionParameter> {
        &self.parameters
    }

    fn return_type(&self) -> &TypeArgument {
        &self.return_type
    }
}

impl EqWithEngines for TyFunctionDecl {}
impl PartialEqWithEngines for TyFunctionDecl {
    fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
        self.name == other.name
            && self.body.eq(&other.body, ctx)
            && self.parameters.eq(&other.parameters, ctx)
            && self.return_type.eq(&other.return_type, ctx)
            && self.type_parameters.eq(&other.type_parameters, ctx)
            && self.visibility == other.visibility
            && self.is_contract_call == other.is_contract_call
            && self.purity == other.purity
    }
}

impl HashWithEngines for TyFunctionDecl {
    fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
        let TyFunctionDecl {
            name,
            body,
            parameters,
            return_type,
            type_parameters,
            visibility,
            is_contract_call,
            purity,
            // these fields are not hashed because they aren't relevant/a
            // reliable source of obj v. obj distinction
            call_path: _,
            span: _,
            attributes: _,
            implementing_type: _,
            implementing_for_typeid: _,
            where_clause: _,
            is_trait_method_dummy: _,
            is_type_check_finalized: _,
            kind: _,
        } = self;
        name.hash(state);
        body.hash(state, engines);
        parameters.hash(state, engines);
        return_type.hash(state, engines);
        type_parameters.hash(state, engines);
        visibility.hash(state);
        is_contract_call.hash(state);
        purity.hash(state);
    }
}

impl SubstTypes for TyFunctionDecl {
    fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
        if ctx.subst_function_body {
            has_changes! {
                self.type_parameters.subst(ctx);
                self.parameters.subst(ctx);
                self.return_type.subst(ctx);
                self.body.subst(ctx);
                self.implementing_for_typeid.subst(ctx);
            }
        } else {
            has_changes! {
                self.type_parameters.subst(ctx);
                self.parameters.subst(ctx);
                self.return_type.subst(ctx);
                self.implementing_for_typeid.subst(ctx);
            }
        }
    }
}

impl ReplaceDecls for TyFunctionDecl {
    fn replace_decls_inner(
        &mut self,
        decl_mapping: &DeclMapping,
        handler: &Handler,
        ctx: &mut TypeCheckContext,
    ) -> Result<bool, ErrorEmitted> {
        let mut func_ctx = ctx.by_ref().with_self_type(self.implementing_for_typeid);
        self.body
            .replace_decls(decl_mapping, handler, &mut func_ctx)
    }
}

impl Spanned for TyFunctionDecl {
    fn span(&self) -> Span {
        self.span.clone()
    }
}

impl MonomorphizeHelper for TyFunctionDecl {
    fn type_parameters(&self) -> &[TypeParameter] {
        &self.type_parameters
    }

    fn name(&self) -> &Ident {
        &self.name
    }

    fn has_self_type_param(&self) -> bool {
        false
    }
}

impl CollectTypesMetadata for TyFunctionDecl {
    fn collect_types_metadata(
        &self,
        handler: &Handler,
        ctx: &mut CollectTypesMetadataContext,
    ) -> Result<Vec<TypeMetadata>, ErrorEmitted> {
        let mut body = vec![];
        for content in self.body.contents.iter() {
            body.append(&mut content.collect_types_metadata(handler, ctx)?);
        }
        body.append(
            &mut self
                .return_type
                .type_id
                .collect_types_metadata(handler, ctx)?,
        );
        for type_param in self.type_parameters.iter() {
            body.append(&mut type_param.type_id.collect_types_metadata(handler, ctx)?);
        }
        for param in self.parameters.iter() {
            body.append(
                &mut param
                    .type_argument
                    .type_id
                    .collect_types_metadata(handler, ctx)?,
            );
        }
        Ok(body)
    }
}

impl TyFunctionDecl {
    pub(crate) fn set_implementing_type(&mut self, decl: TyDecl) {
        self.implementing_type = Some(decl);
    }

    /// Used to create a stubbed out function when the function fails to
    /// compile, preventing cascading namespace errors.
    pub(crate) fn error(decl: &parsed::FunctionDeclaration) -> TyFunctionDecl {
        let parsed::FunctionDeclaration {
            name,
            return_type,
            span,
            visibility,
            purity,
            where_clause,
            kind,
            ..
        } = decl;
        TyFunctionDecl {
            purity: *purity,
            name: name.clone(),
            body: TyCodeBlock::default(),
            implementing_type: None,
            implementing_for_typeid: None,
            span: span.clone(),
            call_path: CallPath::from(Ident::dummy()),
            attributes: Default::default(),
            is_contract_call: false,
            parameters: Default::default(),
            visibility: *visibility,
            return_type: return_type.clone(),
            type_parameters: Default::default(),
            where_clause: where_clause.clone(),
            is_trait_method_dummy: false,
            is_type_check_finalized: true,
            kind: match kind {
                FunctionDeclarationKind::Default => TyFunctionDeclKind::Default,
                FunctionDeclarationKind::Entry => TyFunctionDeclKind::Entry,
                FunctionDeclarationKind::Test => TyFunctionDeclKind::Test,
                FunctionDeclarationKind::Main => TyFunctionDeclKind::Main,
            },
        }
    }

    /// If there are parameters, join their spans. Otherwise, use the fn name span.
    pub(crate) fn parameters_span(&self) -> Span {
        if !self.parameters.is_empty() {
            self.parameters.iter().fold(
                // TODO: Use Span::join_all().
                self.parameters[0].name.span(),
                |acc, TyFunctionParameter { type_argument, .. }| {
                    Span::join(acc, &type_argument.span)
                },
            )
        } else {
            self.name.span()
        }
    }

    pub fn to_fn_selector_value_untruncated(
        &self,
        handler: &Handler,
        engines: &Engines,
    ) -> Result<Vec<u8>, ErrorEmitted> {
        let mut hasher = Sha256::new();
        let data = self.to_selector_name(handler, engines)?;
        hasher.update(data);
        let hash = hasher.finalize();
        Ok(hash.to_vec())
    }

    /// Converts a [TyFunctionDecl] into a value that is to be used in contract function
    /// selectors.
    /// Hashes the name and parameters using SHA256, and then truncates to four bytes.
    pub fn to_fn_selector_value(
        &self,
        handler: &Handler,
        engines: &Engines,
    ) -> Result<[u8; 4], ErrorEmitted> {
        let hash = self.to_fn_selector_value_untruncated(handler, engines)?;
        // 4 bytes truncation via copying into a 4 byte buffer
        let mut buf = [0u8; 4];
        buf.copy_from_slice(&hash[..4]);
        Ok(buf)
    }

    pub fn to_selector_name(
        &self,
        handler: &Handler,
        engines: &Engines,
    ) -> Result<String, ErrorEmitted> {
        let named_params = self
            .parameters
            .iter()
            .map(|TyFunctionParameter { type_argument, .. }| {
                engines
                    .te()
                    .to_typeinfo(type_argument.type_id, &type_argument.span)
                    .expect("unreachable I think?")
                    .to_selector_name(handler, engines, &type_argument.span)
            })
            .filter_map(|name| name.ok())
            .collect::<Vec<String>>();

        Ok(format!(
            "{}({})",
            self.name.as_str(),
            named_params.join(","),
        ))
    }

    /// Whether or not this function is the default entry point.
    pub fn is_entry(&self) -> bool {
        matches!(self.kind, TyFunctionDeclKind::Entry)
    }

    pub fn is_main(&self) -> bool {
        matches!(self.kind, TyFunctionDeclKind::Main)
    }

    /// Whether or not this function is a unit test, i.e. decorated with `#[test]`.
    pub fn is_test(&self) -> bool {
        //TODO match kind to Test
        self.attributes
            .contains_key(&transform::AttributeKind::Test)
    }

    pub fn inline(&self) -> Option<Inline> {
        match self
            .attributes
            .get(&transform::AttributeKind::Inline)?
            .last()?
            .args
            .first()?
            .name
            .as_str()
        {
            INLINE_NEVER_NAME => Some(Inline::Never),
            INLINE_ALWAYS_NAME => Some(Inline::Always),
            _ => None,
        }
    }

    pub fn is_fallback(&self) -> bool {
        self.attributes.contains_key(&AttributeKind::Fallback)
    }

    /// Whether or not this function is a constructor for the type given by `type_id`.
    ///
    /// Returns `Some(true)` if the function is surely the constructor and `Some(false)` if
    /// it is surely not a constructor, and `None` if it cannot decide.
    pub fn is_constructor(&self, engines: &Engines, type_id: TypeId) -> Option<bool> {
        if self
            .parameters
            .first()
            .map(|param| param.is_self())
            .unwrap_or_default()
        {
            return Some(false);
        };

        match &self.implementing_type {
            Some(TyDecl::ImplSelfOrTrait(t)) => {
                let unify_check = UnifyCheck::non_dynamic_equality(engines);

                let implementing_for = engines.de().get(&t.decl_id).implementing_for.type_id;

                // TODO: Implement the check in detail for all possible cases (e.g. trait impls for generics etc.)
                //       and return just the definite `bool` and not `Option<bool>`.
                //       That would be too much effort at the moment for the immediate practical need of
                //       error reporting where we suggest obvious most common constructors
                //       that will be found using this simple check.
                if unify_check.check(type_id, implementing_for)
                    && unify_check.check(type_id, self.return_type.type_id)
                {
                    Some(true)
                } else {
                    None
                }
            }
            _ => Some(false),
        }
    }
}

#[derive(Debug, Clone)]
pub struct TyFunctionParameter {
    pub name: Ident,
    pub is_reference: bool,
    pub is_mutable: bool,
    pub mutability_span: Span,
    pub type_argument: TypeArgument,
}

impl EqWithEngines for TyFunctionParameter {}
impl PartialEqWithEngines for TyFunctionParameter {
    fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
        self.name == other.name
            && self.type_argument.eq(&other.type_argument, ctx)
            && self.is_reference == other.is_reference
            && self.is_mutable == other.is_mutable
    }
}

impl HashWithEngines for TyFunctionParameter {
    fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
        let TyFunctionParameter {
            name,
            is_reference,
            is_mutable,
            type_argument,
            // these fields are not hashed because they aren't relevant/a
            // reliable source of obj v. obj distinction
            mutability_span: _,
        } = self;
        name.hash(state);
        type_argument.hash(state, engines);
        is_reference.hash(state);
        is_mutable.hash(state);
    }
}

impl SubstTypes for TyFunctionParameter {
    fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
        self.type_argument.type_id.subst(ctx)
    }
}

impl TyFunctionParameter {
    pub fn is_self(&self) -> bool {
        self.name.as_str() == "self"
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct TyFunctionSig {
    pub return_type: TypeId,
    pub parameters: Vec<TypeId>,
    pub type_parameters: Vec<TypeId>,
}

impl DisplayWithEngines for TyFunctionSig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
        write!(f, "{:?}", engines.help_out(self))
    }
}

impl DebugWithEngines for TyFunctionSig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>, engines: &Engines) -> fmt::Result {
        let tp_str = if self.type_parameters.is_empty() {
            "".to_string()
        } else {
            format!(
                "<{}>",
                self.type_parameters
                    .iter()
                    .map(|p| format!("{}", engines.help_out(p)))
                    .collect::<Vec<_>>()
                    .join(", "),
            )
        };
        write!(
            f,
            "fn{}({}) -> {}",
            tp_str,
            self.parameters
                .iter()
                .map(|p| format!("{}", engines.help_out(p)))
                .collect::<Vec<_>>()
                .join(", "),
            engines.help_out(self.return_type),
        )
    }
}

impl TyFunctionSig {
    pub fn from_fn_decl(fn_decl: &TyFunctionDecl) -> Self {
        Self {
            return_type: fn_decl.return_type.type_id,
            parameters: fn_decl
                .parameters
                .iter()
                .map(|p| p.type_argument.type_id)
                .collect::<Vec<_>>(),
            type_parameters: fn_decl
                .type_parameters
                .iter()
                .map(|p| p.type_id)
                .collect::<Vec<_>>(),
        }
    }

    pub fn is_concrete(&self, engines: &Engines) -> bool {
        self.return_type
            .is_concrete(engines, TreatNumericAs::Concrete)
            && self
                .parameters
                .iter()
                .all(|p| p.is_concrete(engines, TreatNumericAs::Concrete))
            && self
                .type_parameters
                .iter()
                .all(|p| p.is_concrete(engines, TreatNumericAs::Concrete))
    }

    /// Returns a String representing the function.
    /// When the function is monomorphized the returned String is unique.
    /// Two monomorphized functions that generate the same String can be assumed to be the same.
    pub fn get_type_str(&self, engines: &Engines) -> String {
        let tp_str = if self.type_parameters.is_empty() {
            "".to_string()
        } else {
            format!(
                "<{}>",
                self.type_parameters
                    .iter()
                    .map(|p| p.get_type_str(engines))
                    .collect::<Vec<_>>()
                    .join(", "),
            )
        };
        format!(
            "fn{}({}) -> {}",
            tp_str,
            self.parameters
                .iter()
                .map(|p| p.get_type_str(engines))
                .collect::<Vec<_>>()
                .join(", "),
            self.return_type.get_type_str(engines),
        )
    }
}