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
use sway_core::{AstNode, AstNodeContent, Declaration, Expression, ReturnStatement, SwayParseTree};

use sway_types::span::Span;

use crate::traversal_helper::{
    format_data_types, format_delineated_path, format_include_statement, format_use_statement,
};

/// Change contains the formatted change itself.
/// `start` and `end` denote the start and end of that change,
/// which are used to caluclate the position for inserting this change in the existing file.
#[derive(Debug)]
pub struct Change {
    pub text: String,
    pub start: usize,
    pub end: usize,
}

impl Change {
    fn new(span: &Span, change_type: ChangeType) -> Self {
        let text = match change_type {
            ChangeType::Struct => format_data_types(span.as_str()),
            ChangeType::Enum => format_data_types(span.as_str()),
            ChangeType::IncludeStatement => format_include_statement(span.as_str()),
            ChangeType::UseStatement => format_use_statement(span.as_str()),
            ChangeType::DelineatedPath => format_delineated_path(span.as_str()),
        };

        Self {
            text,
            start: span.start(),
            end: span.end(),
        }
    }
}

#[derive(Debug)]
enum ChangeType {
    Struct,
    Enum,
    IncludeStatement,
    UseStatement,
    DelineatedPath,
}

/// traverses the Sway ParseTree and returns list of formatted changes
pub fn traverse_for_changes(parse_tree: &SwayParseTree) -> Vec<Change> {
    let mut changes = vec![];

    for node in &parse_tree.tree.root_nodes {
        traverse_ast_node(node, &mut changes);
    }

    changes.sort_by(|a, b| a.start.cmp(&b.start));

    changes
}

fn traverse_ast_node(ast_node: &AstNode, changes: &mut Vec<Change>) {
    match &ast_node.content {
        AstNodeContent::Declaration(dec) => handle_declaration(dec, ast_node, changes),

        AstNodeContent::ReturnStatement(ret) => handle_return_statement(ret, changes),

        AstNodeContent::Expression(expr) => handle_expression(expr, changes),

        AstNodeContent::ImplicitReturnExpression(expr) => {
            handle_implicit_return_expression(expr, changes)
        }

        AstNodeContent::UseStatement(_) => {
            // The AST generates one root node per use statement, we must avoid duplicating them
            // while formatting
            let next_span = &ast_node.span;
            match changes.last() {
                Some(last_change) => {
                    if last_change.start != next_span.start() {
                        changes.push(Change::new(next_span, ChangeType::UseStatement));
                    }
                }
                _ => changes.push(Change::new(next_span, ChangeType::UseStatement)),
            }
        }

        AstNodeContent::IncludeStatement(_) => {
            changes.push(Change::new(&ast_node.span, ChangeType::IncludeStatement))
        }

        _ => {}
    }
}

fn handle_return_statement(ret: &ReturnStatement, changes: &mut Vec<Change>) {
    handle_expression(&ret.expr, changes)
}

fn handle_declaration(dec: &Declaration, ast_node: &AstNode, changes: &mut Vec<Change>) {
    match &dec {
        Declaration::VariableDeclaration(var_dec) => handle_expression(&var_dec.body, changes),

        Declaration::StructDeclaration(_) => {
            changes.push(Change::new(&ast_node.span, ChangeType::Struct))
        }

        Declaration::EnumDeclaration(_) => {
            changes.push(Change::new(&ast_node.span, ChangeType::Enum))
        }

        Declaration::FunctionDeclaration(func) => {
            for content in &func.body.contents {
                traverse_ast_node(content, changes);
            }
        }

        Declaration::ImplSelf(impl_self) => {
            for func in &impl_self.functions {
                for content in &func.body.contents {
                    traverse_ast_node(content, changes);
                }
            }
        }
        Declaration::ImplTrait(impl_trait) => {
            for func in &impl_trait.functions {
                for content in &func.body.contents {
                    traverse_ast_node(content, changes);
                }
            }
        }
        _ => {}
    };
}

fn handle_expression(expr: &Expression, changes: &mut Vec<Change>) {
    match &expr {
        Expression::StructExpression {
            struct_name: _,
            fields: _,
            span,
        } => changes.push(Change::new(span, ChangeType::Struct)),
        Expression::IfExp {
            condition: _,
            then,
            r#else,
            span: _,
        } => {
            handle_expression(then, changes);

            if let Some(else_expr) = r#else {
                handle_expression(else_expr, changes);
            }
        }
        Expression::CodeBlock { contents, span: _ } => {
            for content in &contents.contents {
                traverse_ast_node(content, changes);
            }
        }
        Expression::DelineatedPath {
            span,
            args: _,
            call_path: _,
            type_arguments: _,
        } => {
            changes.push(Change::new(span, ChangeType::DelineatedPath));
        }
        _ => {}
    }
}

fn handle_implicit_return_expression(expr: &Expression, changes: &mut Vec<Change>) {
    handle_expression(expr, changes)
}