cairo_lang_semantic/items/
modifiers.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
use cairo_lang_syntax::node::ast::Modifier;
use cairo_lang_syntax::node::db::SyntaxGroup;
use cairo_lang_syntax::node::Terminal;
use smol_str::SmolStr;

use crate::diagnostic::SemanticDiagnosticKind::RedundantModifier;
use crate::diagnostic::{SemanticDiagnostics, SemanticDiagnosticsBuilder};
use crate::Mutability;

/// Returns the mutability of a variable, given the list of modifiers in the AST.
pub fn compute_mutability(
    diagnostics: &mut SemanticDiagnostics,
    syntax_db: &dyn SyntaxGroup,
    modifier_list: &[Modifier],
) -> Mutability {
    let mut mutability = Mutability::Immutable;

    for modifier in modifier_list {
        match mutability {
            Mutability::Immutable => {
                mutability = match modifier {
                    Modifier::Ref(_) => Mutability::Reference,
                    Modifier::Mut(_) => Mutability::Mutable,
                };
            }
            Mutability::Mutable | Mutability::Reference => match modifier {
                Modifier::Ref(terminal) => {
                    diagnostics.report(
                        terminal,
                        RedundantModifier {
                            current_modifier: terminal.text(syntax_db),
                            previous_modifier: get_relevant_modifier(&mutability),
                        },
                    );
                }
                Modifier::Mut(terminal) => {
                    diagnostics.report(
                        terminal,
                        RedundantModifier {
                            current_modifier: terminal.text(syntax_db),
                            previous_modifier: get_relevant_modifier(&mutability),
                        },
                    );
                }
            },
        }
    }
    mutability
}

/// Gets the text of the modifier that causes a variable to have the given mutability status.
fn get_relevant_modifier(mutability: &Mutability) -> SmolStr {
    match mutability {
        Mutability::Immutable => "",
        Mutability::Mutable => "mut",
        Mutability::Reference => "ref",
    }
    .to_string()
    .into()
}