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
//! Trait for replacing an existing identifier.
// TODO: Generalize it for any AST element.

use crate::ir::{Identifier, Implementation, ImplementationItem, Type, Reference, Parameter, Path};

/// Trait to replace identifiers in IR AST.
pub trait ReplaceIdentifier {
    /// Replace all occurrences of the `old` identifier by the `new` identifier.
    fn replace_identifier(&mut self, old: &Identifier, new: &Identifier);
}

impl ReplaceIdentifier for Implementation {
    fn replace_identifier(&mut self, old: &Identifier, new: &Identifier) {
        for item in &mut self.items {
            item.replace_identifier(old, new);
        }
    }
}

impl ReplaceIdentifier for ImplementationItem {
    fn replace_identifier(&mut self, old: &Identifier, new: &Identifier) {
        match self {
            ImplementationItem::Method(function) => {
                function.identifier.replace_identifier(old, new);
                function.output.as_mut().map(|type_| type_.replace_identifier(old, new));
                for parameter in &mut function.inputs {
                    parameter.replace_identifier(old, new);
                }
            },
            ImplementationItem::Constant(constant) => {
                constant.identifier.replace_identifier(old, new);
            }
        }
    }
}

impl ReplaceIdentifier for Parameter {
    fn replace_identifier(&mut self, old: &Identifier, new: &Identifier) {
        self.identifier.replace_identifier(old, new);
        self.type_.replace_identifier(old, new);
    }
}

impl ReplaceIdentifier for Path {
    fn replace_identifier(&mut self, old: &Identifier, new: &Identifier) {
        for segment in self.segments.iter_mut() {
            segment.replace_identifier(old, new);
        }
    }
}

impl ReplaceIdentifier for Type {
    fn replace_identifier(&mut self, old: &Identifier, new: &Identifier) {
        match self {
            Type::Reference(reference) => {
                reference.replace_identifier(old, new);
            },
            Type::Compound(compound) => {
                compound.replace_identifier(old, new);
            },
            _ => ()
        }
    }
}

impl ReplaceIdentifier for Reference {
    fn replace_identifier(&mut self, old: &Identifier, new: &Identifier) {
        self.type_.replace_identifier(old, new);
    }
}

impl ReplaceIdentifier for Identifier {
    fn replace_identifier(&mut self, old: &Identifier, new: &Identifier) {
        self.name = self.name.replace(&old.name, &new.name);
    }
}