mcfunction-debugger 2.0.0

A debugger for Minecraft's *.mcfunction files that does not require any Minecraft mods
Documentation
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
// Mcfunction-Debugger is a debugger for Minecraft's *.mcfunction files that does not require any
// Minecraft mods.
//
// © Copyright (C) 2021-2024 Adrodoc <adrodoc55@googlemail.com> & Skagaros <skagaros@gmail.com>
//
// This file is part of Mcfunction-Debugger.
//
// Mcfunction-Debugger is free software: you can redistribute it and/or modify it under the terms of
// the GNU General Public License as published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
//
// Mcfunction-Debugger is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with Mcfunction-Debugger.
// If not, see <http://www.gnu.org/licenses/>.

pub mod utils;

use crate::{
    adapter::utils::{
        events_between, parse_function_path, McfunctionStackFrame, SourceLocation, StoppedData,
        StoppedEvent,
    },
    dap::{
        api::{DebugAdapter, DebugAdapterContext},
        error::{PartialErrorResponse, RequestError},
    },
    generator::{
        config::GeneratorConfig,
        generate_debug_datapack,
        parser::{
            command::{
                resource_location::{ResourceLocation, ResourceLocationRef},
                CommandParser,
            },
            parse_line, Line,
        },
        partition::SuspensionPositionInLine,
        DebugDatapackMetadata,
    },
    installer::establish_connection,
};
use async_trait::async_trait;
use debug_adapter_protocol::{
    events::{
        Event, OutputCategory, OutputEventBody, StoppedEventBody, StoppedEventReason,
        TerminatedEventBody,
    },
    requests::{
        ContinueRequestArguments, EvaluateRequestArguments, InitializeRequestArguments,
        LaunchRequestArguments, NextRequestArguments, PathFormat, PauseRequestArguments,
        ScopesRequestArguments, SetBreakpointsRequestArguments, StackTraceRequestArguments,
        StepInRequestArguments, StepOutRequestArguments, TerminateRequestArguments,
        VariablesRequestArguments,
    },
    responses::{
        ContinueResponseBody, EvaluateResponseBody, ScopesResponseBody, SetBreakpointsResponseBody,
        StackTraceResponseBody, ThreadsResponseBody, VariablesResponseBody,
    },
    types::{Breakpoint, Capabilities, Scope, Thread, Variable},
    ProtocolMessage,
};
use futures::future::Either;
use log::trace;
use minect::{
    command::{
        logged_block_commands, named_logged_block_commands, query_scoreboard_command,
        summon_named_entity_command, QueryScoreboardOutput, SummonNamedEntityOutput,
    },
    log::LogEvent,
    Command, MinecraftConnection,
};
use multimap::MultiMap;
use std::{
    convert::TryFrom,
    io,
    path::{Path, PathBuf},
    str::FromStr,
};
use tokio::{
    fs::{remove_dir_all, File},
    io::{AsyncBufReadExt, BufReader},
    sync::mpsc::UnboundedSender,
};
use tokio_stream::{wrappers::LinesStream, StreamExt};

const LISTENER_NAME: &'static str = "mcfunction_debugger";

struct ClientSession {
    lines_start_at_1: bool,
    columns_start_at_1: bool,
    path_format: PathFormat,
    mc_session: Option<MinecraftSession>,
    breakpoints: MultiMap<ResourceLocation, usize>,
    parser: CommandParser,
}
impl ClientSession {
    fn get_line_offset(&self) -> usize {
        if self.lines_start_at_1 {
            0
        } else {
            1
        }
    }

    fn get_column_offset(&self) -> usize {
        if self.columns_start_at_1 {
            0
        } else {
            1
        }
    }
}

struct MinecraftSession {
    connection: MinecraftConnection,
    datapack: PathBuf,
    namespace: String,
    output_path: PathBuf,
    metadata: DebugDatapackMetadata,
    scopes: Vec<ScopeReference>,
    step_target_depth: Option<i32>,
    stopped_data: Option<StoppedData>,
}
impl MinecraftSession {
    fn inject_commands(&mut self, commands: Vec<Command>) -> Result<(), PartialErrorResponse> {
        inject_commands(&mut self.connection, commands)
            .map_err(|e| PartialErrorResponse::new(format!("Failed to inject commands: {}", e)))
    }

    fn replace_ns(&self, command: &str) -> String {
        command.replace("-ns-", &self.namespace)
    }

    fn try_update_stopped_position(
        &mut self,
        function: &ResourceLocation,
        old_breakpoints: &[usize],
        new_breakpoints: &[usize],
    ) {
        macro_rules! unwrap_or_return {
            ($option:expr) => {
                match $option {
                    Some(value) => value,
                    None => return,
                }
            };
        }

        let stopped_data = unwrap_or_return!(self.stopped_data.as_mut());
        if stopped_data.function != *function {
            return;
        }
        if stopped_data.position_in_line != SuspensionPositionInLine::Breakpoint {
            return;
        }
        let breakpoint_index = unwrap_or_return!(old_breakpoints
            .iter()
            .position(|&it| it == stopped_data.line_number));

        stopped_data.line_number = new_breakpoints[breakpoint_index];
    }

    pub fn setup_breakpoint_commands(
        &self,
        breakpoints: &MultiMap<ResourceLocation, usize>,
    ) -> Vec<Command> {
        let mut commands = Vec::new();
        commands.push(Command::new(
            self.replace_ns("scoreboard players reset * -ns-_break"),
        ));
        for (function, breakpoints) in breakpoints.iter_all() {
            for &line_number in breakpoints {
                commands.push(self.activate_breakpoint_command(function, line_number));
            }
        }
        commands
    }

    pub(crate) fn activate_breakpoint_command(
        &self,
        fn_name: &ResourceLocation,
        line_number: usize,
    ) -> Command {
        Command::new(self.replace_ns(&format!(
            "scoreboard players set {} -ns-_break 1",
            self.metadata.get_breakpoint_score_holder(fn_name, line_number)
        )))
    }

    pub(crate) fn deactivate_breakpoint_command(
        &self,
        fn_name: &ResourceLocation,
        line_number: usize,
    ) -> Command {
        Command::new(self.replace_ns(&format!(
            "scoreboard players reset {} -ns-_break",
            self.metadata.get_breakpoint_score_holder(fn_name, line_number)
        )))
    }

    fn set_step_target_depth_command(&self, step_target_depth: Option<i32>) -> Command {
        if let Some(step_target_depth) = step_target_depth {
            Command::new(self.replace_ns(&format!(
                "scoreboard players set step_target -ns-_depth {}",
                step_target_depth
            )))
        } else {
            Command::new(self.replace_ns("scoreboard players reset step_target -ns-_depth"))
        }
    }

    async fn get_context_entity_id(&mut self, depth: i32) -> Result<i32, PartialErrorResponse> {
        let events = self.connection.add_listener();

        const START: &str = "get_context_entity_id.start";
        const END: &str = "get_context_entity_id.end";

        let scoreboard = self.replace_ns("-ns-_id");
        self.inject_commands(vec![
            Command::named(LISTENER_NAME, summon_named_entity_command(START)),
            Command::new(query_scoreboard_command(
                self.replace_ns(&format!(
                    "@e[\
                        type=area_effect_cloud,\
                        tag=-ns-_context,\
                        tag=-ns-_active,\
                        tag=-ns-_current,\
                        scores={{-ns-_depth={}}},\
                    ]",
                    depth
                )),
                &scoreboard,
            )),
            Command::named(LISTENER_NAME, summon_named_entity_command(END)),
        ])?;

        events_between(events, START, END)
            .filter_map(|event| event.output.parse::<QueryScoreboardOutput>().ok())
            .filter(|output| output.scoreboard == scoreboard)
            .map(|output| output.score)
            .next()
            .await
            .ok_or_else(|| PartialErrorResponse::new("Minecraft connection closed".to_string()))
    }

    fn get_cached_stack_trace(
        &self,
    ) -> Result<&Vec<McfunctionStackFrame>, RequestError<io::Error>> {
        Ok(&self
            .stopped_data
            .as_ref()
            .ok_or(PartialErrorResponse::new("Not stopped".to_string()))?
            .stack_trace)
    }

    async fn get_stack_trace(&mut self) -> io::Result<Vec<McfunctionStackFrame>> {
        const START: &str = "stack_trace.start";
        const END: &str = "stack_trace.end";

        let events = self.connection.add_listener();

        let commands = Vec::from_iter([
            Command::named(LISTENER_NAME, summon_named_entity_command(START)),
            Command::new(self.replace_ns(&format!(
                "execute as @e[type=area_effect_cloud,tag=-ns-_function_call] run {}",
                query_scoreboard_command("@s", self.replace_ns("-ns-_depth"))
            ))),
            Command::named(LISTENER_NAME, summon_named_entity_command(END)),
        ]);
        inject_commands(&mut self.connection, commands)?;

        let mut stack_trace = events_between(events, START, END)
            .filter_map(McfunctionStackFrame::parse)
            .collect::<Vec<_>>()
            .await;
        stack_trace.sort_by_key(|it| it.id);
        Ok(stack_trace)
    }

    async fn uninstall_datapack(&mut self) -> io::Result<()> {
        let events = self.connection.add_listener();

        let uninstalled = format!("{}.uninstalled", LISTENER_NAME);
        inject_commands(
            &mut self.connection,
            vec![
                Command::new(format!("function {}:uninstall", self.namespace)),
                Command::new(summon_named_entity_command(&uninstalled)),
            ],
        )?;

        trace!("Waiting for datapack to be uninstalled...");
        events
            .filter_map(|e| e.output.parse::<SummonNamedEntityOutput>().ok())
            .filter(|o| o.name == uninstalled)
            .next()
            .await;
        trace!("Datapack is uninstalled");

        remove_dir_all(&self.output_path).await?;
        Ok(())
    }
}

pub(crate) fn inject_commands(
    connection: &mut MinecraftConnection,
    commands: Vec<Command>,
) -> io::Result<()> {
    trace!(
        "Injecting commands:{}",
        commands
            .iter()
            .map(|it| it.get_command())
            .fold(String::new(), |joined, command| joined + "\n" + command)
    );
    connection.execute_commands(commands)?;
    Ok(())
}

const MAIN_THREAD_ID: i32 = 0;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ScopeKind {
    SelectedEntityScores,
}
pub const SELECTED_ENTITY_SCORES: &str = "@s scores";
impl ScopeKind {
    fn get_display_name(&self) -> &'static str {
        match self {
            ScopeKind::SelectedEntityScores => SELECTED_ENTITY_SCORES,
        }
    }
}

struct ScopeReference {
    frame_id: i32,
    kind: ScopeKind,
}

enum DebuggerError {
    ContextEntityKilled,
    SelectedEntityKilled,
    FunctionInvalid(ResourceLocation),
    FunctionCallEntityKilled,
    FunctionCallDeleted,
}
impl DebuggerError {
    fn get_message(&self) -> String {
        match self {
            DebuggerError::ContextEntityKilled => {
                "Error: Debugger context entity was killed!".to_string()
            }
            DebuggerError::SelectedEntityKilled => "Error: Selected entity was killed!".to_string(),
            DebuggerError::FunctionInvalid(fn_name) => {
                format!(
                    "Error: Cannot debug {}, because it contains an invalid command!",
                    fn_name
                )
            }
            DebuggerError::FunctionCallEntityKilled => {
                "Error: Debugger function call entity was killed!".to_string()
            }
            DebuggerError::FunctionCallDeleted => "Error: Function call was deleted!".to_string(),
        }
    }
}
impl FromStr for DebuggerError {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Some(fn_name) = s.strip_prefix("function_invalid+") {
            let fn_name = ResourceLocationRef::try_from(fn_name)
                .map_err(|_| ())?
                .to_owned();
            Ok(DebuggerError::FunctionInvalid(fn_name))
        } else {
            match s {
                "context_entity_killed" => Ok(DebuggerError::ContextEntityKilled),
                "selected_entity_killed" => Ok(DebuggerError::SelectedEntityKilled),
                "function_call_entity_killed" => Ok(DebuggerError::FunctionCallEntityKilled),
                "function_call_deleted" => Ok(DebuggerError::FunctionCallDeleted),
                _ => Err(()),
            }
        }
    }
}

pub struct McfunctionDebugAdapter {
    message_sender: UnboundedSender<Either<ProtocolMessage, LogEvent>>,
    client_session: Option<ClientSession>,
}
impl McfunctionDebugAdapter {
    pub fn new(message_sender: UnboundedSender<Either<ProtocolMessage, LogEvent>>) -> Self {
        McfunctionDebugAdapter {
            message_sender,
            client_session: None,
        }
    }

    async fn on_debugger_error(
        &mut self,
        context: &mut (impl DebugAdapterContext + Send),
        error: DebuggerError,
    ) -> io::Result<()> {
        context.fire_event(
            OutputEventBody::builder()
                .category(OutputCategory::Important)
                .output(error.get_message())
                .build(),
        );
        Ok(())
    }

    async fn on_console_event(
        &mut self,
        context: &mut (impl DebugAdapterContext + Send),
        message: &str,
    ) -> io::Result<()> {
        context.fire_event(
            OutputEventBody::builder()
                .category(OutputCategory::Console)
                .output(format!("{}\n", message))
                .build(),
        );
        Ok(())
    }

    async fn on_stopped(
        &mut self,
        event: StoppedEvent,
        context: &mut (impl DebugAdapterContext + Send),
    ) -> io::Result<()> {
        if let Some(client_session) = &mut self.client_session {
            if let Some(mc_session) = &mut client_session.mc_session {
                let mut stack_trace = mc_session.get_stack_trace().await?;
                let current_depth = stack_trace.len() as i32;

                stack_trace.push(McfunctionStackFrame {
                    id: current_depth,
                    location: SourceLocation {
                        function: event.function.clone(),
                        line_number: event.line_number,
                        column_number: event.column_number,
                    },
                });

                mc_session.stopped_data = Some(StoppedData {
                    function: event.function,
                    line_number: event.line_number,
                    position_in_line: event.position_in_line,
                    stack_trace,
                });

                let reason = match mc_session.step_target_depth {
                    Some(step_target_depth) if current_depth <= step_target_depth => {
                        StoppedEventReason::Step
                    }
                    _ => StoppedEventReason::Breakpoint,
                };

                let event = StoppedEventBody::builder()
                    .reason(reason)
                    .thread_id(Some(MAIN_THREAD_ID))
                    .build();
                context.fire_event(event);
            }
        }

        Ok(())
    }

    async fn on_exited(
        &mut self,
        context: &mut (impl DebugAdapterContext + Send),
    ) -> io::Result<()> {
        if let Some(client_session) = &mut self.client_session {
            if let Some(mc_session) = &mut client_session.mc_session {
                mc_session.uninstall_datapack().await?;

                context.fire_event(TerminatedEventBody::builder().build());
            }
        }

        Ok(())
    }

    fn unwrap_client_session(
        client_session: &mut Option<ClientSession>,
    ) -> Result<&mut ClientSession, PartialErrorResponse> {
        client_session.as_mut().ok_or_else(|| PartialErrorResponse {
            message: "Not initialized".to_string(),
            details: None,
        })
    }

    fn unwrap_minecraft_session(
        mc_session: &mut Option<MinecraftSession>,
    ) -> Result<&mut MinecraftSession, PartialErrorResponse> {
        mc_session.as_mut().ok_or_else(|| PartialErrorResponse {
            message: "Not launched or attached".to_string(),
            details: None,
        })
    }

    async fn continue_internal(
        &mut self,
        depth_offset: Option<i32>,
    ) -> Result<(), RequestError<io::Error>> {
        let client_session = Self::unwrap_client_session(&mut self.client_session)?;
        let mc_session = Self::unwrap_minecraft_session(&mut client_session.mc_session)?;

        let stopped_data = mc_session
            .stopped_data
            .as_ref()
            .ok_or(PartialErrorResponse::new("Not stopped".to_string()))?;

        let current_depth = stopped_data.stack_trace.len() as i32 - 1;
        let step_target_depth = depth_offset.map(|depth_offset| current_depth + depth_offset);
        mc_session.step_target_depth = step_target_depth;

        // Continue must be scheduled to ensure it runs before suspended schedules
        let commands = Vec::from_iter([
            mc_session.set_step_target_depth_command(step_target_depth),
            Command::new(mc_session.replace_ns("schedule function -ns-:prepare_resume 1t")),
            Command::new(mc_session.replace_ns(&format!(
                "schedule function -ns-:{}/{}/continue_current_iteration_at_{}_{} 1t",
                stopped_data.function.namespace(),
                stopped_data.function.path(),
                stopped_data.line_number,
                stopped_data.position_in_line,
            ))),
        ]);

        mc_session.inject_commands(commands)?;
        mc_session.stopped_data = None;
        mc_session.scopes.clear();

        Ok(())
    }
}

#[async_trait]
impl DebugAdapter for McfunctionDebugAdapter {
    type Message = LogEvent;
    type CustomError = io::Error;

    async fn handle_other_message(
        &mut self,
        msg: Self::Message,
        mut context: impl DebugAdapterContext + Send,
    ) -> Result<(), Self::CustomError> {
        trace!(
            "Received message from Minecraft by {}: {}",
            msg.executor,
            msg.output
        );
        if let Ok(output) = msg.output.parse::<SummonNamedEntityOutput>() {
            if let Some(error) = output.name.strip_prefix("error+") {
                if let Ok(error) = error.parse::<DebuggerError>() {
                    self.on_debugger_error(&mut context, error).await?;
                }
            }
            if let Some(message) = output.name.strip_prefix("console+") {
                self.on_console_event(&mut context, message).await?;
            }
            if let Ok(event) = output.name.parse() {
                self.on_stopped(event, &mut context).await?;
            }
            if output.name == "exited" {
                self.on_exited(&mut context).await?;
            }
        }
        Ok(())
    }

    async fn continue_(
        &mut self,
        _args: ContinueRequestArguments,
        _context: impl DebugAdapterContext + Send,
    ) -> Result<ContinueResponseBody, RequestError<Self::CustomError>> {
        self.continue_internal(None).await?;

        Ok(ContinueResponseBody::builder().build())
    }

    async fn evaluate(
        &mut self,
        _args: EvaluateRequestArguments,
        _context: impl DebugAdapterContext + Send,
    ) -> Result<EvaluateResponseBody, RequestError<Self::CustomError>> {
        let client_session = Self::unwrap_client_session(&mut self.client_session)?;
        let _mc_session = Self::unwrap_minecraft_session(&mut client_session.mc_session)?;

        Err(RequestError::Respond(PartialErrorResponse::new(
            "Not supported yet, see: \
            https://codeberg.org/vanilla-technologies/mcfunction-debugger/issues/68"
                .to_string(),
        )))
    }

    async fn initialize(
        &mut self,
        args: InitializeRequestArguments,
        mut context: impl DebugAdapterContext + Send,
    ) -> Result<Capabilities, RequestError<Self::CustomError>> {
        let parser = CommandParser::default()
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
            .map_err(Self::map_custom_error)?;
        self.client_session = Some(ClientSession {
            lines_start_at_1: args.lines_start_at_1,
            columns_start_at_1: args.columns_start_at_1,
            path_format: args.path_format,
            mc_session: None,
            breakpoints: MultiMap::new(),
            parser,
        });

        context.fire_event(Event::Initialized);

        Ok(Capabilities::builder()
            .supports_cancel_request(true)
            .supports_terminate_request(true)
            .build())
    }

    async fn launch(
        &mut self,
        args: LaunchRequestArguments,
        context: impl DebugAdapterContext + Send,
    ) -> Result<(), RequestError<Self::CustomError>> {
        let client_session = Self::unwrap_client_session(&mut self.client_session)?;

        let config = get_config(&args)?;

        let mut connection = establish_connection(
            &config.minecraft_world_dir,
            &config.minecraft_log_file,
            context,
        )
        .await?;

        let mut events = connection.add_named_listener(LISTENER_NAME);
        let message_sender = self.message_sender.clone();
        tokio::spawn(async move {
            while let Some(event) = events.next().await {
                if let Err(_) = message_sender.send(Either::Right(event)) {
                    break;
                }
            }
        });

        let namespace = "mcfd".to_string(); // Hardcoded in installer as well
        let debug_datapack_name = format!("debug-{}", config.datapack_name);
        let output_path = config
            .minecraft_world_dir
            .join("datapacks")
            .join(&debug_datapack_name);

        let datapack = config.datapack.to_path_buf();

        let generator_config = GeneratorConfig {
            namespace: &namespace,
            adapter_listener_name: LISTENER_NAME,
        };
        let _ = remove_dir_all(&output_path).await;
        let metadata = generate_debug_datapack(&datapack, &output_path, &generator_config)
            .await
            .map_err(|e| {
                PartialErrorResponse::new(format!("Failed to generate debug datapack: {}", e))
            })?;

        let mut mc_session = MinecraftSession {
            connection,
            datapack,
            namespace,
            output_path,
            metadata,
            scopes: Vec::new(),
            step_target_depth: None,
            stopped_data: None,
        };

        let commands = vec![
            Command::new("reload"),
            Command::new(format!("datapack enable \"file/{}\"", debug_datapack_name)),
        ];
        mc_session.inject_commands(commands)?;
        // After loading the datapack we must wait one tick for it to install itself
        let mut commands = mc_session.setup_breakpoint_commands(&client_session.breakpoints);
        // By scheduling this function call we have a defined execution position
        commands.push(Command::new(format!(
            "schedule function {}:{}/{}/start 1t",
            mc_session.namespace,
            config.function.namespace(),
            config.function.path(),
        )));
        mc_session.inject_commands(commands)?;

        client_session.mc_session = Some(mc_session);
        Ok(())
    }

    async fn next(
        &mut self,
        _args: NextRequestArguments,
        _context: impl DebugAdapterContext + Send,
    ) -> Result<(), RequestError<Self::CustomError>> {
        self.continue_internal(Some(0)).await
    }

    async fn pause(
        &mut self,
        _args: PauseRequestArguments,
        mut context: impl DebugAdapterContext + Send,
    ) -> Result<(), RequestError<Self::CustomError>> {
        let client_session = Self::unwrap_client_session(&mut self.client_session)?;
        let _mc_session = Self::unwrap_minecraft_session(&mut client_session.mc_session)?;

        let event = OutputEventBody::builder()
            .category(OutputCategory::Important)
            .output("Minecraft cannot be paused".to_string())
            .build();
        context.fire_event(event);

        Err(RequestError::Respond(PartialErrorResponse::new(
            "Minecraft cannot be paused".to_string(),
        )))
    }

    async fn scopes(
        &mut self,
        args: ScopesRequestArguments,
        _context: impl DebugAdapterContext + Send,
    ) -> Result<ScopesResponseBody, RequestError<Self::CustomError>> {
        let client_session = Self::unwrap_client_session(&mut self.client_session)?;
        let mc_session = Self::unwrap_minecraft_session(&mut client_session.mc_session)?;

        let mut scopes = Vec::new();
        let is_server_context = mc_session.get_context_entity_id(args.frame_id).await? == 0;
        if !is_server_context {
            scopes.push(create_selected_entity_scores_scope(mc_session, args));
        }
        Ok(ScopesResponseBody::builder().scopes(scopes).build().into())
    }

    async fn set_breakpoints(
        &mut self,
        args: SetBreakpointsRequestArguments,
        _context: impl DebugAdapterContext + Send,
    ) -> Result<SetBreakpointsResponseBody, RequestError<Self::CustomError>> {
        let client_session = Self::unwrap_client_session(&mut self.client_session)?;

        let offset = client_session.get_line_offset();
        let path = match client_session.path_format {
            PathFormat::Path => args.source.path.as_ref().ok_or_else(|| {
                PartialErrorResponse::new("Missing argument source.path".to_string())
            })?,
            PathFormat::URI => todo!("Implement path URIs"),
        };
        let (_datapack, function) = parse_function_path(path.as_ref())
            .map_err(|e| PartialErrorResponse::new(format!("Argument source.path {}", e)))?;

        let breakpoints = args
            .breakpoints
            .iter()
            .map(|source_breakpoint| (function.clone(), source_breakpoint.line as usize + offset))
            .collect::<Vec<_>>();

        let mut response = Vec::new();
        let old_breakpoints = client_session
            .breakpoints
            .remove(&function)
            .unwrap_or_default();
        let mut new_breakpoints = Vec::with_capacity(breakpoints.len());
        for (function, line_number) in breakpoints.into_iter() {
            let verified = verify_breakpoint(&client_session.parser, path, line_number)
                .await
                .map_err(|e| {
                    PartialErrorResponse::new(format!(
                        "Failed to verify breakpoint {}:{}: {}",
                        function, line_number, e
                    ))
                })?;
            new_breakpoints.push(line_number);
            response.push(
                Breakpoint::builder()
                    .id(None)
                    .verified(verified)
                    .line(Some((line_number - offset) as i32))
                    .build(),
            );
        }

        client_session
            .breakpoints
            .insert_many(function.clone(), new_breakpoints);
        // Unwrap is safe, because we just inserted the value
        let new_breakpoints = client_session.breakpoints.get_vec(&function).unwrap();

        if let Some(mc_session) = client_session.mc_session.as_mut() {
            let mut commands = Vec::new();
            for &breakpoint in &old_breakpoints {
                commands.push(mc_session.deactivate_breakpoint_command(&function, breakpoint));
            }
            for &breakpoint in new_breakpoints {
                commands.push(mc_session.activate_breakpoint_command(&function, breakpoint));
            }
            // TODO: https://codeberg.org/vanilla-technologies/mcfunction-debugger/issues/70
            if false && args.source_modified && old_breakpoints.len() == new_breakpoints.len() {
                mc_session.try_update_stopped_position(
                    &function,
                    &old_breakpoints,
                    new_breakpoints,
                );
            }
            mc_session.inject_commands(commands)?;
        }

        Ok(SetBreakpointsResponseBody::builder()
            .breakpoints(response)
            .build())
    }

    async fn stack_trace(
        &mut self,
        _args: StackTraceRequestArguments,
        _context: impl DebugAdapterContext + Send,
    ) -> Result<StackTraceResponseBody, RequestError<Self::CustomError>> {
        let client_session = Self::unwrap_client_session(&mut self.client_session)?;
        let get_line_offset = client_session.get_line_offset();
        let get_column_offset = client_session.get_column_offset();
        let mc_session = Self::unwrap_minecraft_session(&mut client_session.mc_session)?;

        let stack_trace = mc_session
            .get_cached_stack_trace()?
            .into_iter()
            .rev()
            .map(|it| it.to_stack_frame(&mc_session.datapack, get_line_offset, get_column_offset))
            .collect::<Vec<_>>();

        Ok(StackTraceResponseBody::builder()
            .total_frames(Some(stack_trace.len() as i32))
            .stack_frames(stack_trace)
            .build())
    }

    async fn terminate(
        &mut self,
        _args: TerminateRequestArguments,
        mut context: impl DebugAdapterContext + Send,
    ) -> Result<(), RequestError<Self::CustomError>> {
        if let Some(client_session) = &mut self.client_session {
            if let Some(mc_session) = &mut client_session.mc_session {
                mc_session.inject_commands(vec![Command::new(format!(
                    "function {}:stop",
                    mc_session.namespace
                ))])?;

                context.fire_event(TerminatedEventBody::builder().build());
            }
        }
        Ok(())
    }

    async fn step_in(
        &mut self,
        _args: StepInRequestArguments,
        _context: impl DebugAdapterContext + Send,
    ) -> Result<(), RequestError<Self::CustomError>> {
        self.continue_internal(Some(1)).await
    }

    async fn step_out(
        &mut self,
        _args: StepOutRequestArguments,
        _context: impl DebugAdapterContext + Send,
    ) -> Result<(), RequestError<Self::CustomError>> {
        self.continue_internal(Some(-1)).await
    }

    async fn threads(
        &mut self,
        _context: impl DebugAdapterContext + Send,
    ) -> Result<ThreadsResponseBody, RequestError<Self::CustomError>> {
        let client_session = Self::unwrap_client_session(&mut self.client_session)?;
        let _mc_session = Self::unwrap_minecraft_session(&mut client_session.mc_session)?;

        let thread = Thread::builder()
            .id(MAIN_THREAD_ID)
            .name("Main Thread".to_string())
            .build();
        Ok(ThreadsResponseBody::builder()
            .threads(vec![thread])
            .build()
            .into())
    }

    async fn variables(
        &mut self,
        args: VariablesRequestArguments,
        _context: impl DebugAdapterContext + Send,
    ) -> Result<VariablesResponseBody, RequestError<Self::CustomError>> {
        let client_session = Self::unwrap_client_session(&mut self.client_session)?;
        let mc_session = Self::unwrap_minecraft_session(&mut client_session.mc_session)?;

        let unknown_variables_reference = || {
            PartialErrorResponse::new(format!(
                "Unknown variables_reference: {}",
                args.variables_reference
            ))
        };
        let scope_id = usize::try_from(args.variables_reference - 1)
            .map_err(|_| unknown_variables_reference())?;
        let scope: &ScopeReference = mc_session
            .scopes
            .get(scope_id)
            .ok_or_else(unknown_variables_reference)?;

        const START: &str = "variables.start";
        const END: &str = "variables.end";

        match scope.kind {
            ScopeKind::SelectedEntityScores => {
                let events = mc_session.connection.add_listener();

                let execute_as_context = format!(
                    "execute as @e[\
                        type=area_effect_cloud,\
                        tag=-ns-_context,\
                        tag=-ns-_active,\
                        tag=-ns-_current,\
                        scores={{-ns-_depth={}}},\
                    ] run",
                    scope.frame_id
                );
                let decrement_ids = mc_session.replace_ns(&format!(
                    "{} scoreboard players operation @e[tag=!-ns-_context] -ns-_id -= @s -ns-_id",
                    execute_as_context
                ));
                let increment_ids = mc_session.replace_ns(&format!(
                    "{} scoreboard players operation @e[tag=!-ns-_context] -ns-_id += @s -ns-_id",
                    execute_as_context
                ));
                let mut commands = Vec::new();
                commands.extend(named_logged_block_commands(
                    LISTENER_NAME,
                    &summon_named_entity_command(START),
                ));
                commands.extend(logged_block_commands(&decrement_ids));
                commands.push(mc_session.replace_ns("function -ns-:log_scores"));
                commands.extend(logged_block_commands(&increment_ids));
                commands.extend(named_logged_block_commands(
                    LISTENER_NAME,
                    &summon_named_entity_command(END),
                ));
                let commands = commands.into_iter().map(Command::new).collect();
                mc_session.inject_commands(commands)?;

                let variables = events_between(events, START, END)
                    .filter_map(|event| event.output.parse::<QueryScoreboardOutput>().ok())
                    .map(|output| {
                        Variable::builder()
                            .name(output.scoreboard)
                            .value(output.score.to_string())
                            .variables_reference(0)
                            .build()
                    })
                    .collect::<Vec<_>>()
                    .await;

                Ok(VariablesResponseBody::builder()
                    .variables(variables)
                    .build())
            }
        }
    }
}

struct AdapterConfig<'l> {
    datapack: &'l Path,
    datapack_name: &'l str,
    function: ResourceLocation,
    minecraft_world_dir: &'l Path,
    minecraft_log_file: &'l Path,
}

fn get_config(args: &LaunchRequestArguments) -> Result<AdapterConfig, PartialErrorResponse> {
    let program = get_path(&args, "program")?;

    let (datapack, function) = parse_function_path(program)
        .map_err(|e| PartialErrorResponse::new(format!("Attribute 'program' {}", e)))?;

    let datapack_name = datapack
        .file_name()
        .ok_or_else(|| {
            PartialErrorResponse::new(format!(
                "Attribute 'program' contains an invalid path: {}",
                program.display()
            ))
        })?
        .to_str()
        .unwrap(); // Path is known to be UTF-8

    let minecraft_world_dir = get_path(&args, "minecraftWorldDir")?;
    let minecraft_log_file = get_path(&args, "minecraftLogFile")?;
    Ok(AdapterConfig {
        datapack,
        datapack_name,
        function,
        minecraft_world_dir,
        minecraft_log_file,
    })
}

fn get_path<'a>(
    args: &'a LaunchRequestArguments,
    key: &str,
) -> Result<&'a Path, PartialErrorResponse> {
    let value = args
        .additional_attributes
        .get(key)
        .ok_or_else(|| PartialErrorResponse::new(format!("Missing attribute '{}'", key)))?
        .as_str()
        .ok_or_else(|| {
            PartialErrorResponse::new(format!("Attribute '{}' is not of type string", key))
        })?;
    let value = Path::new(value);
    Ok(value)
}

fn create_selected_entity_scores_scope(
    mc_session: &mut MinecraftSession,
    args: ScopesRequestArguments,
) -> Scope {
    let kind = ScopeKind::SelectedEntityScores;
    mc_session.scopes.push(ScopeReference {
        frame_id: args.frame_id,
        kind,
    });
    let variables_reference = mc_session.scopes.len();
    Scope::builder()
        .name(kind.get_display_name().to_string())
        .variables_reference(variables_reference as i32)
        .expensive(false)
        .build()
}

async fn verify_breakpoint(
    parser: &CommandParser,
    path: impl AsRef<Path>,
    line_number: usize,
) -> io::Result<bool> {
    let file = File::open(path).await?;
    let lines = BufReader::new(file).lines();
    if let Some(result) = LinesStream::new(lines).skip(line_number - 1).next().await {
        let line = result?;
        let line = parse_line(parser, &line);
        return Ok(is_command(line));
    } else {
        Ok(false)
    }
}

fn is_command(line: Line) -> bool {
    !matches!(line, Line::Empty | Line::Comment)
}