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
use code_blocks::{Block, BlockTree};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Clone, Hash, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct BlockLocation {
    pub start_byte: usize,
    pub end_byte: usize,
    pub start_row: usize,
    pub start_col: usize,
    pub end_row: usize,
    pub end_col: usize,
}

impl From<Block<'_>> for BlockLocation {
    fn from(value: Block) -> Self {
        let (Some(head), Some(tail)) = value.head_tail() else {
            panic!("Got empty block");
        };

        Self {
            start_byte: head.start_byte(),
            end_byte: tail.end_byte(),
            start_row: head.start_position().row,
            start_col: head.start_position().column,
            end_row: tail.end_position().row,
            end_col: tail.end_position().column,
        }
    }
}

impl From<&Block<'_>> for BlockLocation {
    fn from(value: &Block) -> Self {
        let (Some(head), Some(tail)) = value.head_tail() else {
            panic!("Got empty block");
        };

        Self {
            start_byte: head.start_byte(),
            end_byte: tail.end_byte(),
            start_row: head.start_position().row,
            start_col: head.start_position().column,
            end_row: tail.end_position().row,
            end_col: tail.end_position().column,
        }
    }
}

#[derive(Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Clone, Hash, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct BlockLocationTree {
    pub block: BlockLocation,
    pub children: Vec<BlockLocationTree>,
}

impl From<BlockTree<'_>> for BlockLocationTree {
    fn from(value: BlockTree<'_>) -> Self {
        Self {
            block: value.block.into(),
            children: value.children.iter().map(|c| c.into()).collect(),
        }
    }
}

impl From<&BlockTree<'_>> for BlockLocationTree {
    fn from(value: &BlockTree<'_>) -> Self {
        Self {
            block: value.block.clone().into(),
            children: value.children.iter().map(Into::into).collect(),
        }
    }
}