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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
use datapack_common::vfs::Directory;
use debris_common::CompileContext;
use debris_llir::Llir;

use crate::Backend;

use super::generator::DatapackGenerator;

/// The Datapack Backend implementation
#[derive(Debug, Default)]
pub struct DatapackBackend;

impl DatapackBackend {
    pub const FILE_EXTENSION: &'static str = ".mcfunction";
    // Internal namespaces must be prefixed by double underscores, other namespaces may
    // be occupied by the user
    /// The directory which will contain all automatically generated minecraft files
    pub const FUNCTION_INTERNAL_PATH: &'static str = "__generated/";
}

impl Backend for DatapackBackend {
    fn generate(&self, llir: &Llir, ctx: &CompileContext) -> Directory {
        DatapackGenerator::new(ctx, llir).build()
    }
}

#[cfg(test)]
mod tests {
    use datapack_common::vfs::Directory;
    use debris_common::{CompilationId, CompileContext};
    use debris_llir::{
        block_id::BlockId,
        item_id::ItemId,
        json_format::{FormattedText, JsonFormatComponent},
        llir_nodes::{Branch, Condition, FastStore, Function, Node, WriteMessage, WriteTarget},
        minecraft_utils::{ScoreboardComparison, ScoreboardValue},
        CallGraph, CodeStats, Llir, Runtime,
    };
    use rustc_hash::FxHashMap;

    use crate::{Backend, DatapackBackend};

    fn text(msg: &str) -> FormattedText {
        FormattedText {
            components: vec![JsonFormatComponent::RawText(msg.into())],
        }
    }

    fn compile(nodes: Vec<Node>) -> Directory {
        let id = BlockId::dummy(0);
        let function = Function::_dummy(id, nodes);
        let mut map = FxHashMap::default();
        map.insert(id, function);
        let mut runtime = Runtime::default();
        runtime.add_on_load(id);
        let call_graph = CallGraph::from(&map);
        let mut stats = CodeStats::new(call_graph);
        stats.update(&runtime, &map);
        let llir = Llir {
            entry_function: id,
            functions: map,
            runtime,
            stats,
        };
        let mut dir = DatapackBackend.generate(&llir, &CompileContext::new(CompilationId(0)));
        let mut dir = dir.directories.remove("data").unwrap();
        let mut dir = dir.directories.remove("debris_project").unwrap();
        let mut dir = dir.directories.remove("functions").unwrap();
        dir.directories.remove("__generated").unwrap()
    }

    // ## Branch tests ##
    // Unfortunately, it is not possible to directly translate an if-else statement into minecraft functions.
    // The problem arises when `pos_branch` or `neg_branch` modify a value the condition depends on, because then both branches might be taken
    // The solution unfortunately contains many variants, depending on how exactly the if statement looks like, so for that reason
    // this many tests are required.

    #[test]
    fn test_branch_simple() {
        let value_id = ItemId { id: 0 };
        let nodes = vec![
            Node::FastStore(FastStore {
                id: value_id,
                value: ScoreboardValue::Static(1),
            }),
            Node::Branch(Branch {
                condition: Condition::Compare {
                    comparison: ScoreboardComparison::Equal,
                    lhs: ScoreboardValue::Scoreboard(value_id),
                    rhs: ScoreboardValue::Static(1),
                },
                pos_branch: Box::new(Node::Write(WriteMessage {
                    target: WriteTarget::Chat,
                    message: text("Equal to 1"),
                })),
                neg_branch: Box::new(Node::Write(WriteMessage {
                    target: WriteTarget::Chat,
                    message: text("Not equal to 1"),
                })),
            }),
        ];

        let mut pack = compile(nodes);
        let main = pack.file("main.mcfunction".to_string());
        assert_eq!(
            main.contents,
            concat!(
                "scoreboard objectives remove debris\n",
                "scoreboard objectives add debris dummy\n",
                "scoreboard players set var_0 debris 1\n",
                "execute if score var_0 debris matches 1 run tellraw @a [{\"text\":\"Equal to 1\"}]\n",
                "execute unless score var_0 debris matches 1 run tellraw @a [{\"text\":\"Not equal to 1\"}]\n",
            )
        );
    }

    #[test]
    fn test_branch_reordered_simple() {
        let value_id = ItemId { id: 0 };
        let nodes = vec![
            Node::FastStore(FastStore {
                id: value_id,
                value: ScoreboardValue::Static(1),
            }),
            Node::Branch(Branch {
                condition: Condition::Compare {
                    comparison: ScoreboardComparison::Equal,
                    lhs: ScoreboardValue::Scoreboard(value_id),
                    rhs: ScoreboardValue::Static(1),
                },
                pos_branch: Box::new(Node::FastStore(FastStore {
                    id: value_id,
                    value: ScoreboardValue::Static(0),
                })),
                neg_branch: Box::new(Node::Write(WriteMessage {
                    target: WriteTarget::Chat,
                    message: text("Not equal to 1"),
                })),
            }),
        ];

        let mut pack = compile(nodes);
        let main = pack.file("main.mcfunction".to_string());
        assert_eq!(
            main.contents,
            concat!(
                "scoreboard objectives remove debris\n",
                "scoreboard objectives add debris dummy\n",
                "scoreboard players set var_0 debris 1\n",
                "execute unless score var_0 debris matches 1 run tellraw @a [{\"text\":\"Not equal to 1\"}]\n",
                "execute if score var_0 debris matches 1 run scoreboard players set var_0 debris 0\n",
            )
        );
    }

    #[test]
    fn test_branch_reordered_complex() {
        let value_id = ItemId { id: 0 };
        let nodes = vec![
            Node::FastStore(FastStore {
                id: value_id,
                value: ScoreboardValue::Static(1),
            }),
            Node::Branch(Branch {
                condition: Condition::Or(vec![
                    Condition::Compare {
                        comparison: ScoreboardComparison::Equal,
                        lhs: ScoreboardValue::Scoreboard(value_id),
                        rhs: ScoreboardValue::Static(1),
                    },
                    Condition::Compare {
                        comparison: ScoreboardComparison::Equal,
                        lhs: ScoreboardValue::Static(0),
                        rhs: ScoreboardValue::Static(1),
                    },
                ]),
                pos_branch: Box::new(Node::FastStore(FastStore {
                    id: value_id,
                    value: ScoreboardValue::Static(0),
                })),
                neg_branch: Box::new(Node::Write(WriteMessage {
                    target: WriteTarget::Chat,
                    message: text("Not equal to 1"),
                })),
            }),
        ];

        let mut pack = compile(nodes);
        let main = pack.file("main.mcfunction".to_string());
        assert_eq!(
            main.contents,
            concat!(
                "scoreboard objectives remove debris\n",
                "scoreboard objectives add debris dummy\n",
                "scoreboard players set const_0 debris 0\n",
                "scoreboard players set const_1 debris 1\n",
                "scoreboard players set var_0 debris 1\n",
                "scoreboard players set var_1 debris 0\n",
                "execute store result score var_1 debris run execute unless score var_0 debris matches 1 unless score const_0 debris = const_1 debris \n",
                "execute unless score var_1 debris matches 0 run tellraw @a [{\"text\":\"Not equal to 1\"}]\n",
                "execute if score var_1 debris matches 0 run scoreboard players set var_0 debris 0\n",
            )
        );
    }

    #[test]
    fn test_branch_both_modify_simple() {
        let value_id = ItemId { id: 0 };
        let nodes = vec![
            Node::FastStore(FastStore {
                id: value_id,
                value: ScoreboardValue::Static(1),
            }),
            Node::Branch(Branch {
                condition: Condition::Compare {
                    comparison: ScoreboardComparison::Equal,
                    lhs: ScoreboardValue::Scoreboard(value_id),
                    rhs: ScoreboardValue::Static(1),
                },
                pos_branch: Box::new(Node::FastStore(FastStore {
                    id: value_id,
                    value: ScoreboardValue::Static(0),
                })),
                neg_branch: Box::new(Node::FastStore(FastStore {
                    id: value_id,
                    value: ScoreboardValue::Static(-1),
                })),
            }),
        ];

        let mut pack = compile(nodes);
        let main = pack.file("main.mcfunction".to_string());
        assert_eq!(
            main.contents,
            concat!(
                "scoreboard objectives remove debris\n",
                "scoreboard objectives add debris dummy\n",
                "scoreboard players set var_0 debris 1\n",
                "scoreboard players set var_1 debris 0\n",
                "execute if score var_0 debris matches 1 run function debris_project:__generated/block_0\n",
                "execute if score var_1 debris matches 0 unless score var_0 debris matches 1 run scoreboard players set var_0 debris -1\n",
            )
        );

        let block_0 = pack.file("block_0.mcfunction".to_string());
        assert_eq!(
            block_0.contents,
            concat!(
                "scoreboard players set var_0 debris 0\n",
                "scoreboard players set var_1 debris 1\n",
            )
        );
    }

    #[test]
    fn test_branch_both_modify_complex() {
        let value_id = ItemId { id: 0 };
        let nodes = vec![
            Node::FastStore(FastStore {
                id: value_id,
                value: ScoreboardValue::Static(1),
            }),
            Node::Branch(Branch {
                condition: Condition::Or(vec![
                    Condition::Compare {
                        comparison: ScoreboardComparison::Equal,
                        lhs: ScoreboardValue::Scoreboard(value_id),
                        rhs: ScoreboardValue::Static(1),
                    },
                    Condition::Compare {
                        comparison: ScoreboardComparison::Equal,
                        lhs: ScoreboardValue::Static(0),
                        rhs: ScoreboardValue::Static(1),
                    },
                ]),
                pos_branch: Box::new(Node::FastStore(FastStore {
                    id: value_id,
                    value: ScoreboardValue::Static(0),
                })),
                neg_branch: Box::new(Node::FastStore(FastStore {
                    id: value_id,
                    value: ScoreboardValue::Static(-1),
                })),
            }),
        ];

        let mut pack = compile(nodes);
        let main = pack.file("main.mcfunction".to_string());
        assert_eq!(
            main.contents,
            concat!(
                "scoreboard objectives remove debris\n",
                "scoreboard objectives add debris dummy\n",
                "scoreboard players set const_0 debris 0\n",
                "scoreboard players set const_1 debris 1\n",
                "scoreboard players set var_0 debris 1\n",
                "scoreboard players set var_1 debris 0\n",
                "scoreboard players set var_2 debris 0\n",
                "execute store result score var_2 debris run execute unless score var_0 debris matches 1 unless score const_0 debris = const_1 debris \n",
                "execute if score var_2 debris matches 0 run function debris_project:__generated/block_0\n",
                "execute if score var_1 debris matches 0 unless score var_2 debris matches 0 run scoreboard players set var_0 debris -1\n",
            )
        );

        let block_0 = pack.file("block_0.mcfunction".to_string());
        assert_eq!(
            block_0.contents,
            concat!(
                "scoreboard players set var_0 debris 0\n",
                "scoreboard players set var_1 debris 1\n",
            )
        );
    }
}