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
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
// McFunction-Debugger is a debugger for Minecraft's *.mcfunction files that does not require any
// Minecraft mods.
//
// © Copyright (C) 2021-2023 Adrodoc <adrodoc55@googlemail.com> & skess42 <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::{
        can_resume_from, events_between, generate_datapack, parse_function_path,
        to_stopped_event_reason, BreakpointPosition, McfunctionStackFrame, StoppedData,
        StoppedEvent,
    },
    error::{PartialErrorResponse, RequestError},
    installer::establish_connection,
    DebugAdapter, DebugAdapterContext,
};
use async_trait::async_trait;
use debug_adapter_protocol::{
    events::{Event, OutputCategory, OutputEventBody, StoppedEventBody, 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 mcfunction_debugger::{
    config::adapter::{
        BreakpointKind, BreakpointPositionInLine, LocalBreakpoint, LocalBreakpointPosition,
    },
    parser::{
        command::{resource_location::ResourceLocation, CommandParser},
        parse_line, Line,
    },
};
use minect::{
    command::{
        enable_logging_command, logged_command, named_logged_command, query_scoreboard_command,
        reset_logging_command, summon_named_entity_command, AddTagOutput, QueryScoreboardOutput,
        SummonNamedEntityOutput,
    },
    log::LogEvent,
    Command, MinecraftConnection,
};
use multimap::MultiMap;
use std::{
    convert::TryFrom,
    io,
    path::{Path, PathBuf},
};
use tokio::{
    fs::{read_to_string, 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,
    minecraft_session: Option<MinecraftSession>,
    breakpoints: MultiMap<ResourceLocation, LocalBreakpoint>,
    temporary_breakpoints: MultiMap<ResourceLocation, LocalBreakpoint>,
    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,
    scopes: Vec<ScopeReference>,
    stopped_data: Option<StoppedData>,
}
impl MinecraftSession {
    fn get_function_path(&self, function: &ResourceLocation) -> PathBuf {
        self.datapack.join("data").join(function.mcfunction_path())
    }

    fn new_step_breakpoint(
        &self,
        function: ResourceLocation,
        line_number: usize,
        position_in_line: BreakpointPositionInLine,
        depth: usize,
    ) -> (ResourceLocation, LocalBreakpoint) {
        let condition = self.replace_ns(&format!("if score current -ns-_depth matches {}", depth));
        let kind = BreakpointKind::Step { condition };
        let position = LocalBreakpointPosition {
            line_number,
            position_in_line,
        };
        (function, LocalBreakpoint { kind, position })
    }

    async fn create_step_in_breakpoints(
        &self,
        stack_trace: &[McfunctionStackFrame],
        parser: &CommandParser,
    ) -> Result<Vec<(ResourceLocation, LocalBreakpoint)>, RequestError<io::Error>> {
        let mut breakpoints = Vec::new();

        if stack_trace.is_empty() {
            return Ok(breakpoints); // should not happen
        }
        let current = &stack_trace[0];
        let current_depth = stack_trace.len() - 1;
        let current_path = self.get_function_path(&current.location.function);

        let callee =
            get_function_command(current_path, current.location.line_number, &parser).await?;
        if let Some(callee) = callee {
            let callee_path = self.get_function_path(&callee);
            let callee_line_number = find_first_target_line_number(&callee_path, &parser).await?;

            breakpoints.push(self.new_step_breakpoint(
                callee,
                callee_line_number,
                BreakpointPositionInLine::Breakpoint,
                current_depth + 1,
            ));
        }

        breakpoints.extend(
            self.create_step_over_breakpoints(&stack_trace, &parser)
                .await?,
        );

        Ok(breakpoints)
    }

    async fn create_step_over_breakpoints(
        &self,
        stack_trace: &[McfunctionStackFrame],
        parser: &CommandParser,
    ) -> Result<Vec<(ResourceLocation, LocalBreakpoint)>, RequestError<io::Error>> {
        let mut breakpoints = Vec::new();

        if stack_trace.is_empty() {
            return Ok(breakpoints); // should not happen
        }
        let current = &stack_trace[0];
        let current_depth = stack_trace.len() - 1;
        let current_path = self.get_function_path(&current.location.function);

        let next_line_number = find_step_target_line_number(
            &current_path,
            current.location.line_number,
            &parser,
            false,
        )
        .await?;
        if let Some(next_line_number) = next_line_number {
            breakpoints.push(self.new_step_breakpoint(
                current.location.function.clone(),
                next_line_number,
                BreakpointPositionInLine::Breakpoint,
                current_depth,
            ));
        } else {
            breakpoints.extend(
                self.create_step_out_breakpoint(&stack_trace, &parser)
                    .await?,
            );

            // Reentry for next executor
            let first_line_number = find_first_target_line_number(&current_path, &parser).await?;
            breakpoints.push(self.new_step_breakpoint(
                current.location.function.clone(),
                first_line_number,
                BreakpointPositionInLine::Breakpoint,
                current_depth,
            ));
        }

        Ok(breakpoints)
    }

    async fn create_step_out_breakpoint(
        &self,
        stack_trace: &[McfunctionStackFrame],
        parser: &CommandParser,
    ) -> Result<Vec<(ResourceLocation, LocalBreakpoint)>, RequestError<io::Error>> {
        let mut breakpoints = Vec::new();

        if stack_trace.len() <= 1 {
            return Ok(breakpoints);
        }
        let caller = &stack_trace[1];

        let line_number = find_step_target_line_number(
            self.get_function_path(&caller.location.function),
            caller.location.line_number,
            parser,
            true,
        )
        .await?;

        let position_in_line = if line_number.is_some() {
            BreakpointPositionInLine::Breakpoint
        } else {
            BreakpointPositionInLine::AfterFunction
        };

        let current_depth = stack_trace.len() - 1;
        let caller_depth = current_depth - 1;
        breakpoints.push(self.new_step_breakpoint(
            caller.location.function.clone(),
            line_number.unwrap_or(caller.location.line_number),
            position_in_line,
            caller_depth,
        ));

        Ok(breakpoints)
    }

    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)
    }

    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>> {
        let stack_trace = &self
            .stopped_data
            .as_ref()
            .ok_or(PartialErrorResponse::new("Not stopped".to_string()))?
            .stack_trace;
        Ok(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 stack_trace_tag = self.replace_ns("-ns-_stack_trace");
        let depth_scoreboard = self.replace_ns("-ns-_depth");

        let events = self.connection.add_listener();

        let commands = vec![
            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", &depth_scoreboard)
            ))),
            Command::new(self.replace_ns(&format!(
                "execute as @e[type=area_effect_cloud,tag=-ns-_breakpoint] run tag @s add {}",
                stack_trace_tag
            ))),
            Command::new(self.replace_ns(&format!(
                "execute as @e[type=area_effect_cloud,tag=-ns-_breakpoint] run tag @s remove {}",
                stack_trace_tag
            ))),
            Command::named(LISTENER_NAME, summon_named_entity_command(END)),
        ];
        inject_commands(&mut self.connection, commands)?;

        let mut stack_trace = Vec::new();
        let mut events = events_between(events, START, END);
        while let Some(event) = events.next().await {
            if let Ok(location) = event.executor.parse() {
                let id = if let Some(output) = event
                    .output
                    .parse::<QueryScoreboardOutput>()
                    .ok()
                    .filter(|output| output.scoreboard == depth_scoreboard)
                {
                    output.score // depth
                } else if let Some(_) = event
                    .output
                    .parse::<AddTagOutput>()
                    .ok()
                    .filter(|output| output.tag == stack_trace_tag)
                {
                    stack_trace.len() as i32 // Breakpoint
                } else {
                    continue; // Shouldn't actually happen
                };
                stack_trace.push(McfunctionStackFrame { id, location });
            }
        }
        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("function debug:uninstall"),
                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,
}

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_stopped(
        &mut self,
        event: StoppedEvent,
        context: &mut (impl DebugAdapterContext + Send),
    ) -> io::Result<()> {
        if let Some(client_session) = &mut self.client_session {
            if let Some(minecraft_session) = &mut client_session.minecraft_session {
                minecraft_session.stopped_data = Some(StoppedData {
                    position: event.position,
                    stack_trace: minecraft_session.get_stack_trace().await?,
                });

                let event = StoppedEventBody::builder()
                    .reason(to_stopped_event_reason(event.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(minecraft_session) = &mut client_session.minecraft_session {
                minecraft_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(
        minecraft_session: &mut Option<MinecraftSession>,
    ) -> Result<&mut MinecraftSession, PartialErrorResponse> {
        minecraft_session
            .as_mut()
            .ok_or_else(|| PartialErrorResponse {
                message: "Not launched or attached".to_string(),
                details: None,
            })
    }

    async fn continue_internal(
        &mut self,
        temporary_breakpoints: Vec<(ResourceLocation, LocalBreakpoint)>,
    ) -> 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.minecraft_session)?;

        if let Some(stopped_data) = mc_session.stopped_data.as_ref() {
            let mut dirty = false;

            if !client_session.temporary_breakpoints.is_empty() {
                client_session.temporary_breakpoints.clear();
                dirty = true;
            }

            for (function, breakpoint) in temporary_breakpoints {
                client_session
                    .temporary_breakpoints
                    .insert(function, breakpoint);
                dirty = true;
            }

            // Always insert continue point to avoid a race condition where the user removes the breakpoint right before Minecraft continues
            client_session.temporary_breakpoints.insert(
                stopped_data.position.function.clone(),
                LocalBreakpoint {
                    kind: BreakpointKind::Continue,
                    position: LocalBreakpointPosition {
                        line_number: stopped_data.position.line_number,
                        position_in_line: stopped_data.position.position_in_line,
                    },
                },
            );
            // If there isn't already a breakpoint that can resume we need to load the continue point
            if !can_resume_from(&client_session.breakpoints, &stopped_data.position) {
                dirty = true;
            }

            let mut commands = Vec::new();

            if dirty {
                generate_datapack(
                    mc_session,
                    &client_session.breakpoints,
                    &client_session.temporary_breakpoints,
                )
                .await?;
                commands.push(Command::new("reload"));
            };

            commands.push(Command::new("function debug:resume"));
            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::<AddTagOutput>() {
            if output.entity == LISTENER_NAME {
                if let Ok(event) = output.tag.parse() {
                    self.on_stopped(event, &mut context).await?;
                }
                if output.tag == "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(Vec::new()).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.minecraft_session)?;

        Err(RequestError::Respond(PartialErrorResponse::new(
            "Not supported yet, see: \
            https://github.com/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,
            minecraft_session: None,
            breakpoints: MultiMap::new(),
            temporary_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 mut minecraft_session = MinecraftSession {
            connection,
            datapack: config.datapack.to_path_buf(),
            namespace,
            output_path,
            scopes: Vec::new(),
            stopped_data: None,
        };

        generate_datapack(
            &minecraft_session,
            &client_session.breakpoints,
            &client_session.temporary_breakpoints,
        )
        .await?;

        minecraft_session.inject_commands(vec![
            Command::new("reload"),
            Command::new(format!("datapack enable \"file/{}\"", debug_datapack_name)),
            // After loading the datapack we must wait one tick for it to install itself
            // By scheduling this function call we also have a defined execution position
            Command::new(format!(
                "schedule function debug:{}/{} 1t",
                config.function.namespace(),
                config.function.path(),
            )),
        ])?;

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

    async fn next(
        &mut self,
        _args: NextRequestArguments,
        _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.minecraft_session)?;

        let stack_trace = mc_session.get_cached_stack_trace()?;
        let temporary_breakpoints = mc_session
            .create_step_over_breakpoints(stack_trace, &client_session.parser)
            .await?;
        self.continue_internal(temporary_breakpoints).await?;

        Ok(())
    }

    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.minecraft_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.minecraft_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 (i, (function, line_number)) in breakpoints.into_iter().enumerate() {
            let id = (i + client_session.breakpoints.len()) as i32;
            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(LocalBreakpoint {
                kind: if verified {
                    BreakpointKind::Normal
                } else {
                    BreakpointKind::Invalid
                },
                position: LocalBreakpointPosition {
                    line_number,
                    position_in_line: BreakpointPositionInLine::Breakpoint,
                },
            });
            response.push(
                Breakpoint::builder()
                    .id(verified.then(|| id))
                    .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(minecraft_session) = client_session.minecraft_session.as_mut() {
            generate_datapack(
                minecraft_session,
                &client_session.breakpoints,
                &client_session.temporary_breakpoints,
            )
            .await?;
            let mut commands = vec![Command::new("reload")];
            if args.source_modified && old_breakpoints.len() == new_breakpoints.len() {
                commands.extend(get_move_breakpoint_commands(
                    old_breakpoints.iter().map(|it| {
                        BreakpointPosition::from_breakpoint(function.clone(), &it.position)
                    }),
                    new_breakpoints.iter().map(|it| {
                        BreakpointPosition::from_breakpoint(function.clone(), &it.position)
                    }),
                    &minecraft_session.namespace,
                ));
            }
            minecraft_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.minecraft_session)?;

        let stack_trace = mc_session
            .get_cached_stack_trace()?
            .into_iter()
            .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,
        _context: impl DebugAdapterContext + Send,
    ) -> Result<(), RequestError<Self::CustomError>> {
        if let Some(client_session) = &mut self.client_session {
            if let Some(minecraft_session) = &mut client_session.minecraft_session {
                minecraft_session.inject_commands(vec![Command::new("function debug:stop")])?;
            }
        }
        Ok(())
    }

    async fn step_in(
        &mut self,
        _args: StepInRequestArguments,
        _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.minecraft_session)?;

        let stack_trace = mc_session.get_cached_stack_trace()?;
        let temporary_breakpoints = mc_session
            .create_step_in_breakpoints(stack_trace, &client_session.parser)
            .await?;
        self.continue_internal(temporary_breakpoints).await?;

        Ok(())
    }

    async fn step_out(
        &mut self,
        _args: StepOutRequestArguments,
        _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.minecraft_session)?;

        let stack_trace = mc_session.get_cached_stack_trace()?;
        let temporary_breakpoints = mc_session
            .create_step_out_breakpoint(&stack_trace, &client_session.parser)
            .await?;
        self.continue_internal(temporary_breakpoints).await?;

        Ok(())
    }

    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.minecraft_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.minecraft_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
                ));
                mc_session.inject_commands(vec![
                    Command::new(logged_command(enable_logging_command())),
                    Command::new(named_logged_command(
                        LISTENER_NAME,
                        summon_named_entity_command(START),
                    )),
                    Command::new(logged_command(decrement_ids)),
                    Command::new(mc_session.replace_ns("function -ns-:log_scores")),
                    Command::new(logged_command(increment_ids)),
                    Command::new(named_logged_command(
                        LISTENER_NAME,
                        summon_named_entity_command(END),
                    )),
                    Command::new(logged_command(reset_logging_command())),
                ])?;

                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())
            }
        }
    }
}

async fn find_first_target_line_number(
    path: impl AsRef<Path>,
    parser: &CommandParser,
) -> Result<usize, RequestError<io::Error>> {
    Ok(find_step_target_line_number(&path, 0, parser, false)
        .await?
        .unwrap_or(1))
}

// TODO: replace allow_empty_lines with custom enum return type
async fn find_step_target_line_number(
    path: impl AsRef<Path>,
    after_line_number: usize,
    parser: &CommandParser,
    allow_empty_lines: bool,
) -> Result<Option<usize>, RequestError<io::Error>> {
    let content = read_to_string(&path).await.map_err(|e| {
        PartialErrorResponse::new(format!(
            "Failed to read file {}: {}",
            path.as_ref().display(),
            e
        ))
    })?;

    let lines = content.split('\n').enumerate().skip(after_line_number);
    let mut last_line_of_file = true;
    for (line_index, line) in lines {
        last_line_of_file = false;
        let line = line.strip_suffix('\r').unwrap_or(line); // Remove trailing carriage return on Windows
        let line = parse_line(parser, &line, false);
        if is_command(line) {
            let line_number = line_index + 1;
            return Ok(Some(line_number));
        }
    }

    if last_line_of_file {
        Ok(None)
    } else {
        if allow_empty_lines {
            Ok(Some(after_line_number + 1)) // This line is empty or a comment
        } else {
            Ok(None)
        }
    }
}

async fn get_function_command(
    path: impl AsRef<Path>,
    line_number: usize,
    parser: &CommandParser,
) -> Result<Option<ResourceLocation>, RequestError<io::Error>> {
    let file = File::open(&path).await.map_err(|e| {
        PartialErrorResponse::new(format!(
            "Failed to open file {}: {}",
            path.as_ref().display(),
            e
        ))
    })?;
    let lines = BufReader::new(file).lines();
    let mut lines = LinesStream::new(lines).skip(line_number - 1);
    if let Some(line) = lines.next().await {
        let line = line.map_err(|e| {
            PartialErrorResponse::new(format!(
                "Failed to read file {}: {}",
                path.as_ref().display(),
                e
            ))
        })?;

        let line = parse_line(parser, &line, false);
        if let Line::FunctionCall { name, .. } = line {
            return Ok(Some(name));
        }
    }
    Ok(None)
}

struct Config<'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<Config, 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(Config {
        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, false);
        return Ok(is_command(line));
    } else {
        Ok(false)
    }
}
fn get_move_breakpoint_commands(
    old_positions: impl ExactSizeIterator<Item = BreakpointPosition>,
    new_positions: impl ExactSizeIterator<Item = BreakpointPosition>,
    namespace: &str,
) -> Vec<Command> {
    let tmp_tag = format!("{}_tmp", namespace);
    let breakpoint_tag = format!("{}_breakpoint", namespace);
    let mut commands = Vec::new();
    for (old_position, new_position) in old_positions.zip(new_positions) {
        if old_position != new_position {
            let old_tag = format!("{}+{}", namespace, old_position);
            let new_tag = format!("{}+{}", namespace, new_position);
            commands.push(Command::new(format!(
                "tag @e[tag={},tag={},tag=!{}] add {}",
                breakpoint_tag, old_tag, tmp_tag, new_tag,
            )));
            commands.push(Command::new(format!(
                "tag @e[tag={},tag={}] add {}",
                breakpoint_tag, old_tag, tmp_tag
            )));
            commands.push(Command::new(format!(
                "tag @e[tag={},tag={},tag={}] remove {}",
                breakpoint_tag, old_tag, new_tag, old_tag
            )));
        }
    }
    commands.push(Command::new(format!(
        "tag @e[tag={},tag={}] remove {}",
        breakpoint_tag, tmp_tag, tmp_tag
    )));
    commands
}

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