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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
//! Contains every node that can be produced in the llir step.
//!
//! Note that changing any node kind can lead to miscompilations if it isn't also updated
//! at the optimizers!

use std::ops::Index;
use std::{fmt, rc::Rc};

use itertools::Itertools;
use rustc_hash::FxHashSet;

use crate::{block_id::BlockId, item_id::ItemId, type_context::TypeContext};

use super::{
    json_format::{FormattedText, JsonFormatComponent},
    minecraft_utils::{ScoreboardComparison, ScoreboardOperation, ScoreboardValue},
    ObjectRef,
};

/// A function node, contains other nodes
#[derive(Debug)]
pub struct Function {
    /// The id of this function
    pub id: BlockId,
    /// The nodes which this function contains
    pub(crate) nodes: Vec<Node>,
    pub(crate) return_value: ObjectRef,
}

/// Stores a 'fast' variable
///
/// Fast variables are scoreboard values.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FastStore {
    /// The id of the target var
    pub id: ItemId,
    /// The value to store into the target var
    pub value: ScoreboardValue,
}

/// Stores a 'fast' variable from the result of another node
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FastStoreFromResult {
    /// The id of the target var
    pub id: ItemId,
    /// The command to use
    pub command: Box<Node>,
}

/// Operates on two scoreboard values and stores the result into the target var
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BinaryOperation {
    /// The id of the resulting value
    pub id: ItemId,
    /// The left value
    pub lhs: ScoreboardValue,
    /// The right value
    pub rhs: ScoreboardValue,
    /// The kind of operation
    pub operation: ScoreboardOperation,
}

/// Calls a function
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Call {
    /// The id of that function
    pub id: BlockId,
}

/// Evaluates a condition and returns either true or false
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Condition {
    /// Comparison between two values, eg. val1 <= val2
    Compare {
        lhs: ScoreboardValue,
        rhs: ScoreboardValue,
        comparison: ScoreboardComparison,
    },
    And(Vec<Condition>),
    Or(Vec<Condition>),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BranchKind {
    PosBranch,
    NegBranch,
    Both,
}

/// Branches based on a condition
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Branch {
    /// The condition to test
    pub condition: Condition,
    /// The node to execute if that condition is true
    pub pos_branch: Box<Node>,
    /// The node to execute if that condition is false
    pub neg_branch: Box<Node>,
}

/// A component for a raw execute command
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExecuteRawComponent {
    /// Writes a string literal
    String(Rc<str>),
    /// References the value locations
    ScoreboardValue(ScoreboardValue),
    /// Embeds another node in the output
    Node(Node),
}

/// Executes a literal string
///
/// Any String that modifies a variable that belongs to debris
/// or modifies the program state in any other way
/// causes undefined behavior!
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExecuteRaw(pub Vec<ExecuteRawComponent>);

/// Writes a formatted message
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WriteMessage {
    pub target: WriteTarget,
    pub message: FormattedText,
}

/// The buffer to write to
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WriteTarget {
    Chat,
    Actionbar,
    Title,
    Subtitle,
}

impl fmt::Display for WriteTarget {
    #[allow(clippy::use_debug)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self:?}")
    }
}

/// Any node
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Node {
    FastStore(FastStore),
    FastStoreFromResult(FastStoreFromResult),
    BinaryOperation(BinaryOperation),
    Call(Call),
    Condition(Condition),
    Branch(Branch),
    Execute(ExecuteRaw),
    Write(WriteMessage),
    /// Does nothing
    Nop,
}

/// Denotes how a specific node accesses variables.
pub enum VariableAccess<'a> {
    /// Marks that a value is read by this node
    Read(&'a ScoreboardValue),
    /// Marks that a value is written to by this node.
    /// The second argument is the constant value that is written, if applicable.
    Write(&'a ItemId, Option<i32>),
    /// Marks that a value can be both read from and written to by this node.
    ReadWrite(&'a ScoreboardValue),
}

/// See [`VariableAccess`].
pub enum VariableAccessMut<'a> {
    Read(&'a mut ScoreboardValue),
    Write(&'a mut ItemId, Option<i32>),
    ReadWrite(&'a mut ScoreboardValue),
}

/// This awful macro contains code that otherwise would have to be copy-pasted
/// For the immutable and the mutable variable access visitor of [Node] and [Condition].
macro_rules! make_access_visitor {
    (node, $self:ident, $visitor:ident, $fn_name:ident, $VariableAccess:ident) => {
        match $self {
            Node::BinaryOperation(BinaryOperation {
                id,
                lhs,
                rhs,
                operation: _,
            }) => {
                $visitor($VariableAccess::Write(id, None));

                $visitor($VariableAccess::Read(lhs));
                $visitor($VariableAccess::Read(rhs));
            }
            Node::Branch(Branch {
                condition,
                pos_branch,
                neg_branch,
            }) => {
                pos_branch.$fn_name($visitor);
                neg_branch.$fn_name($visitor);
                condition.$fn_name($visitor);
            }
            Node::Call(Call { id: _ }) => {}
            Node::Condition(condition) => {
                condition.$fn_name($visitor);
            }
            Node::Execute(ExecuteRaw(components)) => {
                for component in components {
                    match component {
                        ExecuteRawComponent::ScoreboardValue(value) => {
                            $visitor($VariableAccess::ReadWrite(value));
                        }
                        ExecuteRawComponent::Node(node) => node.$fn_name($visitor),
                        ExecuteRawComponent::String(_) => {}
                    }
                }
            }
            Node::FastStore(FastStore { id, value }) => {
                let static_val = if let ScoreboardValue::Static(value) = value {
                    Some(*value)
                } else {
                    None
                };
                $visitor($VariableAccess::Write(id, static_val));

                $visitor($VariableAccess::Read(value));
            }
            Node::FastStoreFromResult(FastStoreFromResult { id, command }) => {
                $visitor($VariableAccess::Write(id, None));
                command.$fn_name($visitor);
            }
            Node::Nop => {}
            Node::Write(WriteMessage {
                target: _,
                message: FormattedText { components },
            }) => {
                for component in components {
                    match component {
                        JsonFormatComponent::Score(value) => {
                            $visitor($VariableAccess::Read(value));
                        }
                        JsonFormatComponent::RawText(_) | JsonFormatComponent::Function(_) => {}
                    }
                }
            }
        }
    };
    (condition, $self:ident, $visitor:ident, $fn_name:ident, $VariableAccess:ident) => {
        match $self {
            Condition::Compare {
                lhs,
                rhs,
                comparison: _,
            } => {
                $visitor($VariableAccess::Read(lhs));
                $visitor($VariableAccess::Read(rhs));
            }
            Condition::And(conditions) => {
                for condition in conditions {
                    condition.$fn_name($visitor);
                }
            }
            Condition::Or(conditions) => {
                for condition in conditions {
                    condition.$fn_name($visitor);
                }
            }
        }
    };
}

impl Function {
    pub fn nodes(&self) -> &[Node] {
        self.nodes.as_slice()
    }

    /// Checks if this function contains a node that calls the argument.
    /// Note that this is only a shallow check, no other functions will be
    /// visited.
    pub fn calls_function(&self, function_id: &BlockId) -> bool {
        for node in self.nodes() {
            let mut contains_call = false;
            node.scan(&mut |inner_node| match inner_node {
                Node::Call(Call { id }) if id == function_id => {
                    contains_call = true;
                }
                _ => {}
            });
            if contains_call {
                return true;
            }
        }
        false
    }

    pub fn is_empty(&self) -> bool {
        self.nodes.is_empty()
    }

    /// This function should only be used for testing purposes
    #[doc(hidden)]
    pub fn _dummy(id: BlockId, nodes: Vec<Node>) -> Self {
        Function {
            id,
            nodes,
            return_value: TypeContext::default().null(),
        }
    }
}

impl Condition {
    /// Returns a condition that is true, when
    /// this condition is false and the other
    /// way around
    pub fn not(&self) -> Condition {
        match self {
            Condition::Compare {
                comparison,
                lhs,
                rhs,
            } => Condition::Compare {
                comparison: comparison.invert(),
                lhs: *lhs,
                rhs: *rhs,
            },
            Condition::And(conditions) => {
                // -(a AND b) = -a OR -b
                Condition::Or(conditions.iter().map(Condition::not).collect())
            }
            Condition::Or(conditions) => {
                // -(a OR b) = -a AND -b
                Condition::And(conditions.iter().map(Condition::not).collect())
            }
        }
    }

    /// Returns whether evaluating this condition has any side effects
    pub fn is_effect_free(&self) -> bool {
        match self {
            Condition::And(nested) | Condition::Or(nested) => {
                nested.iter().all(Condition::is_effect_free)
            }
            Condition::Compare { .. } => true,
        }
    }

    /// Checks whether this condition is "simple",
    /// which means that it is not expensive to use this condition multiple times
    /// instead of a boolean.
    ///
    /// Right now, only `Condition::Compare` is considered simple.
    pub fn is_simple(&self) -> bool {
        matches!(self, Condition::Compare { .. })
    }

    pub fn variable_reads(&self) -> FxHashSet<ItemId> {
        let mut reads = FxHashSet::default();
        self.variable_accesses(&mut |access| {
            if let VariableAccess::Read(var) | VariableAccess::ReadWrite(var) = access {
                if let ScoreboardValue::Scoreboard(item_id) = var {
                    reads.insert(*item_id);
                }
            }
        });
        reads
    }

    /// Recursively yields all variables that this condition reads from
    pub fn variable_accesses<F: FnMut(VariableAccess)>(&self, visitor: &mut F) {
        make_access_visitor!(condition, self, visitor, variable_accesses, VariableAccess);
    }

    pub fn variable_accesses_mut<F: FnMut(VariableAccessMut)>(&mut self, visitor: &mut F) {
        make_access_visitor!(
            condition,
            self,
            visitor,
            variable_accesses_mut,
            VariableAccessMut
        );
    }
}

impl fmt::Display for Condition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Condition::Compare {
                lhs,
                rhs,
                comparison,
            } => write!(f, "{lhs} {} {rhs}", comparison.str_value()),
            Condition::And(parts) => {
                let nested = parts.iter().map(Condition::to_string).join(" and ");
                write!(f, "({nested})")
            }
            Condition::Or(parts) => {
                let nested = parts.iter().map(Condition::to_string).join(" or ");
                write!(f, "({nested})")
            }
        }
    }
}

impl Node {
    /// Iterates over this node and all other nodes that
    /// this node contains.
    /// Changing this function also requires changing [`Node::scan_mut`]
    pub fn scan<F>(&self, func: &mut F)
    where
        F: FnMut(&Node),
    {
        func(self);
        match self {
            Node::Branch(branch) => {
                branch.pos_branch.scan(func);
                branch.neg_branch.scan(func);
            }
            Node::FastStoreFromResult(FastStoreFromResult { command, .. }) => command.scan(func),
            Node::Execute(ExecuteRaw(components)) => {
                for component in components {
                    match component {
                        ExecuteRawComponent::Node(node) => {
                            node.scan(func);
                        }
                        ExecuteRawComponent::ScoreboardValue(_)
                        | ExecuteRawComponent::String(_) => {}
                    }
                }
            }
            _ => {}
        }
    }

    /// A copy of the above function, but with mutability enabled ...
    pub fn scan_mut<F>(&mut self, func: &mut F)
    where
        F: FnMut(&mut Node),
    {
        func(self);
        match self {
            Node::Branch(branch) => {
                branch.pos_branch.scan_mut(func);
                branch.neg_branch.scan_mut(func);
            }
            Node::FastStoreFromResult(FastStoreFromResult { command, .. }) => {
                command.scan_mut(func);
            }
            Node::Execute(ExecuteRaw(components)) => {
                for component in components {
                    match component {
                        ExecuteRawComponent::Node(node) => {
                            node.scan_mut(func);
                        }
                        ExecuteRawComponent::ScoreboardValue(_)
                        | ExecuteRawComponent::String(_) => {}
                    }
                }
            }
            _ => {}
        }
    }

    /// Returns whether this command has no side effect.
    /// sometimes its easier to just to restrict the parameter to a specific type...
    pub fn is_effect_free<'a, 'b: 'a, T>(&'a self, function_map: &'b T) -> bool
    where
        T: Index<&'a BlockId, Output = Function>,
    {
        match self {
            Node::Branch(branch) => {
                branch.condition.is_effect_free()
                    && branch.pos_branch.is_effect_free(function_map)
                    && branch.neg_branch.is_effect_free(function_map)
            }
            // ToDo: track already checked functions, so no infinite loop occurs
            Node::Call(Call { id }) => function_map[id]
                .nodes
                .iter()
                .all(|node| node.is_effect_free(function_map)),
            Node::Condition(condition) => condition.is_effect_free(),
            Node::BinaryOperation(_)
            | Node::Execute(_)
            | Node::FastStore(_)
            | Node::FastStoreFromResult(_)
            | Node::Write(_) => false,
            Node::Nop => true,
        }
    }

    /// Checks whether this node contains a call
    pub fn has_call(&self) -> bool {
        let mut has_call = false;
        self.scan(&mut |node| {
            if matches!(node, Node::Call(_)) {
                has_call = true;
            }
        });
        has_call
    }

    /// Accepts a callback function as argument and calls it with every variable
    /// accessed by this node.
    pub fn variable_accesses<F: FnMut(VariableAccess)>(&self, visitor: &mut F) {
        make_access_visitor!(node, self, visitor, variable_accesses, VariableAccess);
    }

    /// See `variable_accesses`.
    pub fn variable_accesses_mut<F: FnMut(VariableAccessMut)>(&mut self, visitor: &mut F) {
        make_access_visitor!(
            node,
            self,
            visitor,
            variable_accesses_mut,
            VariableAccessMut
        );
    }

    /// Whether this node could modify `item_id`.
    pub fn writes_to(&self, item_id: ItemId) -> bool {
        let mut found_write = false;
        self.variable_accesses(&mut |access| match access {
            VariableAccess::Write(id, _)
            | VariableAccess::ReadWrite(ScoreboardValue::Scoreboard(id))
                if *id == item_id =>
            {
                found_write = true;
            }
            _ => {}
        });
        found_write
    }

    /// Whether this node has a read-dependency on `item_id`
    pub fn reads_from(&self, item_id: ItemId) -> bool {
        let mut has_read = false;
        self.variable_accesses(&mut |access| match access {
            VariableAccess::Read(ScoreboardValue::Scoreboard(id))
            | VariableAccess::ReadWrite(ScoreboardValue::Scoreboard(id))
                if *id == item_id =>
            {
                has_read = true;
            }
            _ => {}
        });
        has_read
    }
}

impl fmt::Display for Function {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let id = self.id.0;
        let content = self.nodes.iter().join("\n");
        write!(f, "Function {id}:\n{content}\n")
    }
}

impl fmt::Display for Node {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Node::BinaryOperation(binop) => write!(
                f,
                "{} = {} {} {}",
                binop.id,
                binop.lhs,
                binop.operation.str_value(),
                binop.rhs
            ),
            Node::Branch(branch) => write!(
                f,
                "if ({}):\n\t{}\n\t{}",
                branch.condition, branch.pos_branch, branch.neg_branch
            ),
            Node::Call(call) => write!(f, "call {}", call.id.0),
            Node::Condition(condition) => condition.fmt(f),
            Node::Execute(ExecuteRaw(components)) => {
                for component in components {
                    match component {
                        ExecuteRawComponent::ScoreboardValue(
                            value @ ScoreboardValue::Scoreboard { .. },
                        ) => write!(f, "${value}")?,
                        ExecuteRawComponent::ScoreboardValue(ScoreboardValue::Static(value)) => {
                            write!(f, "{value}")?;
                        }
                        ExecuteRawComponent::Node(node) => write!(f, "${{{node}}}")?,
                        ExecuteRawComponent::String(string) => f.write_str(string)?,
                    }
                }
                Ok(())
            }
            Node::FastStore(FastStore { id, value }) => write!(f, "{id} = {value}"),
            Node::FastStoreFromResult(FastStoreFromResult { id, command }) => {
                write!(f, "{id} = {command}")
            }
            Node::Write(WriteMessage { target, message }) => {
                write!(f, "write {target}: {message}")
            }
            Node::Nop => f.write_str("Nop"),
        }
    }
}