ligen_core/ir/processing/
replace_identifier.rs

1//! Trait for replacing an existing identifier.
2// TODO: Generalize it for any AST element.
3
4use crate::ir::{Identifier, Implementation, ImplementationItem, Type, Reference, Parameter, Path};
5
6/// Trait to replace identifiers in IR AST.
7pub trait ReplaceIdentifier {
8    /// Replace all occurrences of the `old` identifier by the `new` identifier.
9    fn replace_identifier(&mut self, old: &Identifier, new: &Identifier);
10}
11
12impl ReplaceIdentifier for Implementation {
13    fn replace_identifier(&mut self, old: &Identifier, new: &Identifier) {
14        for item in &mut self.items {
15            item.replace_identifier(old, new);
16        }
17    }
18}
19
20impl ReplaceIdentifier for ImplementationItem {
21    fn replace_identifier(&mut self, old: &Identifier, new: &Identifier) {
22        match self {
23            ImplementationItem::Method(function) => {
24                function.identifier.replace_identifier(old, new);
25                function.output.as_mut().map(|type_| type_.replace_identifier(old, new));
26                for parameter in &mut function.inputs {
27                    parameter.replace_identifier(old, new);
28                }
29            },
30            ImplementationItem::Constant(constant) => {
31                constant.identifier.replace_identifier(old, new);
32            }
33        }
34    }
35}
36
37impl ReplaceIdentifier for Parameter {
38    fn replace_identifier(&mut self, old: &Identifier, new: &Identifier) {
39        self.identifier.replace_identifier(old, new);
40        self.type_.replace_identifier(old, new);
41    }
42}
43
44impl ReplaceIdentifier for Path {
45    fn replace_identifier(&mut self, old: &Identifier, new: &Identifier) {
46        for segment in self.segments.iter_mut() {
47            segment.replace_identifier(old, new);
48        }
49    }
50}
51
52impl ReplaceIdentifier for Type {
53    fn replace_identifier(&mut self, old: &Identifier, new: &Identifier) {
54        match self {
55            Type::Reference(reference) => {
56                reference.replace_identifier(old, new);
57            },
58            Type::Compound(compound) => {
59                compound.replace_identifier(old, new);
60            },
61            _ => ()
62        }
63    }
64}
65
66impl ReplaceIdentifier for Reference {
67    fn replace_identifier(&mut self, old: &Identifier, new: &Identifier) {
68        self.type_.replace_identifier(old, new);
69    }
70}
71
72impl ReplaceIdentifier for Identifier {
73    fn replace_identifier(&mut self, old: &Identifier, new: &Identifier) {
74        self.name = self.name.replace(&old.name, &new.name);
75    }
76}