perl-lsp-inline-completion 0.12.2

Inline completion provider for Perl LSP
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
1070
1071
1072
1073
1074
1075
//! Inline completions provider with deterministic rules and AI backend support.
//!
//! This crate provides context-aware inline completions that appear as
//! ghost text. Deterministic completions are based on patterns; AI-powered
//! suggestions use the `InlineCompletionBackend` trait for pluggable providers.

use perl_position_tracking::utf16_line_col_to_offset;
use serde::{Deserialize, Serialize};

const MAX_INLINE_COMPLETION_ITEMS: usize = 5;

/// Prepared context for inline completion suggestions and future AI handoff.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PreparedInlineCompletionContext {
    /// Prefix on the current line up to the request position.
    pub prefix: String,
    /// Full current line with trailing newline removed.
    pub current_line: String,
    /// Closest previous non-empty line, if any.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub previous_non_empty_line: Option<String>,
    /// Nearest enclosing subroutine name, if one can be inferred.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub current_function: Option<String>,
    /// Nearest package declaration before the cursor, if any.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub current_package: Option<String>,
    /// Nearby variables, ordered from closest to farthest.
    pub variables: Vec<String>,
    /// Imported modules or pragmas visible before the cursor.
    pub imports: Vec<String>,
}

/// Inline completion item (LSP 3.18 preview)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InlineCompletionItem {
    /// The text to be inserted.
    pub insert_text: String,
    /// The text to be used for filtering.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filter_text: Option<String>,
    /// The range to be replaced by the completion.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub range: Option<lsp_types::Range>,
    /// An optional command to be executed after the completion is inserted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub command: Option<lsp_types::Command>,
}

/// Inline completion list (LSP 3.18 preview)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InlineCompletionList {
    /// The inline completion items.
    pub items: Vec<InlineCompletionItem>,
}

// ── AI backend interface ─────────────────────────────────────────────────────

/// Error type for backend operations.
#[derive(Debug)]
pub enum BackendError {
    /// Network or IO error.
    Transport(String),
    /// Authentication failure (bad key, expired token).
    Auth(String),
    /// Provider returned an error response.
    Provider(String),
    /// Request timed out.
    Timeout,
    /// Rate limit exceeded.
    RateLimited,
    /// Request was cancelled.
    Cancelled,
}

impl std::fmt::Display for BackendError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Transport(msg) => write!(f, "transport error: {}", msg),
            Self::Auth(msg) => write!(f, "auth error: {}", msg),
            Self::Provider(msg) => write!(f, "provider error: {}", msg),
            Self::Timeout => write!(f, "request timed out"),
            Self::RateLimited => write!(f, "rate limit exceeded"),
            Self::Cancelled => write!(f, "request cancelled"),
        }
    }
}

impl std::error::Error for BackendError {}

/// Request payload sent to an AI completion backend.
#[derive(Debug, Clone)]
pub struct BackendRequest {
    /// Prepared context from the current buffer.
    pub context: PreparedInlineCompletionContext,
    /// Maximum tokens to generate.
    pub max_output_tokens: u32,
    /// Timeout in milliseconds.
    pub timeout_ms: u64,
}

/// A chunk emitted by a streaming backend.
#[derive(Debug, Clone)]
pub struct StreamChunk {
    /// Cumulative candidate text so far (NOT a delta).
    pub text: String,
    /// Whether this is the final chunk.
    pub is_final: bool,
}

/// Control signal returned by the stream sink callback.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StreamControl {
    /// Continue receiving chunks.
    Continue,
    /// Stop the stream early.
    Stop,
}

/// Trait for AI inline completion backends.
///
/// Implementations provide streaming token generation. The default `complete()`
/// method buffers the stream into a one-shot result, so backends only need to
/// implement `stream()`.
///
/// The trait is sync and callback-based to keep this crate dependency-light
/// and runtime-agnostic. Network I/O happens in the provider crate.
pub trait InlineCompletionBackend: Send + Sync {
    /// One-shot completion: returns the final candidate texts.
    ///
    /// Default implementation buffers the stream.
    fn complete(&self, req: &BackendRequest) -> Result<Vec<String>, BackendError> {
        let mut final_text = String::new();
        self.stream(req, &mut |chunk| {
            final_text = chunk.text.clone();
            if chunk.is_final { StreamControl::Stop } else { StreamControl::Continue }
        })?;
        Ok(if final_text.is_empty() { vec![] } else { vec![final_text] })
    }

    /// Stream completion chunks to a callback sink.
    ///
    /// Each `StreamChunk.text` is **cumulative** — the full candidate so far,
    /// not a delta. The sink returns `StreamControl::Stop` to cancel early.
    fn stream(
        &self,
        req: &BackendRequest,
        sink: &mut dyn FnMut(StreamChunk) -> StreamControl,
    ) -> Result<(), BackendError>;
}

#[derive(Debug)]
struct RankedCompletionItem {
    priority: u8,
    order: usize,
    item: InlineCompletionItem,
}

/// A provider for inline completions.
pub struct InlineCompletionProvider;

impl Default for InlineCompletionProvider {
    fn default() -> Self {
        Self::new()
    }
}

impl InlineCompletionProvider {
    /// Creates a new `InlineCompletionProvider`.
    pub fn new() -> Self {
        Self
    }

    /// Get inline completions for the given context
    pub fn get_inline_completions(
        &self,
        text: &str,
        line: u32,
        character: u32,
    ) -> InlineCompletionList {
        if let Some(context) = self.prepare_context(text, line, character) {
            let items = self.get_completions_for_context(&context);
            return InlineCompletionList { items };
        }

        InlineCompletionList { items: vec![] }
    }

    /// Prepare surrounding code context for deterministic suggestions and
    /// future LLM-backed inline completion.
    pub fn prepare_context(
        &self,
        text: &str,
        line: u32,
        character: u32,
    ) -> Option<PreparedInlineCompletionContext> {
        let line_context = self.line_context_at_position(text, line, character)?;
        let lines = self.normalized_lines(text);
        let line_index = usize::try_from(line).ok()?;
        let (current_function, function_start_line) =
            self.current_function_context(&lines, line_index);
        let visible_text = self.visible_text_until_cursor(&lines, line_index, line_context.prefix);
        let variable_scan_text = self.visible_text_since_line(
            &lines,
            function_start_line.unwrap_or(0),
            line_index,
            line_context.prefix,
        );

        Some(PreparedInlineCompletionContext {
            prefix: line_context.prefix.to_string(),
            current_line: line_context.current_line.to_string(),
            previous_non_empty_line: self
                .previous_non_empty_line(&lines, line_index)
                .map(str::to_string),
            current_function,
            current_package: self.current_package(&lines, line_index),
            variables: self.collect_variables(&variable_scan_text),
            imports: self.collect_imports(&visible_text),
        })
    }

    fn line_context_at_position<'a>(
        &self,
        text: &'a str,
        line: u32,
        character: u32,
    ) -> Option<LineContext<'a>> {
        let lines = self.normalized_lines(text);
        let line_index = usize::try_from(line).ok()?;
        let current_line = *lines.get(line_index)?;
        let prefix_end = utf16_line_col_to_offset(current_line, 0, character);

        Some(LineContext { prefix: &current_line[..prefix_end], current_line })
    }

    fn normalized_lines<'a>(&self, text: &'a str) -> Vec<&'a str> {
        if text.is_empty() {
            return vec![""];
        }

        text.split('\n').map(|line| line.strip_suffix('\r').unwrap_or(line)).collect()
    }

    fn get_completions_for_context(
        &self,
        context: &PreparedInlineCompletionContext,
    ) -> Vec<InlineCompletionItem> {
        let prefix = context.prefix.as_str();
        let full_line = context.current_line.as_str();
        let mut items = Vec::<RankedCompletionItem>::new();
        let mut sequence = 0usize;

        let mut push_item = |priority: u8, item: InlineCompletionItem| {
            items.push(RankedCompletionItem { priority, order: sequence, item });
            sequence += 1;
        };

        // Rule 1: After `->` suggest `new()`
        if prefix.ends_with("->") {
            push_item(
                0,
                InlineCompletionItem {
                    insert_text: "new()".into(),
                    filter_text: Some("new".into()),
                    range: None,
                    command: None,
                },
            );
        }

        // Rule 2: After `use ` suggest common pragmas
        if prefix.trim_end() == "use" || prefix.ends_with("use ") {
            // Suggest strict first as it's most common
            push_item(
                0,
                InlineCompletionItem {
                    insert_text: "strict;".into(),
                    filter_text: Some("strict".into()),
                    range: None,
                    command: None,
                },
            );

            push_item(
                1,
                InlineCompletionItem {
                    insert_text: "warnings;".into(),
                    filter_text: Some("warnings".into()),
                    range: None,
                    command: None,
                },
            );

            push_item(
                2,
                InlineCompletionItem {
                    insert_text: "feature ':5.36';".into(),
                    filter_text: Some("feature".into()),
                    range: None,
                    command: None,
                },
            );
        }

        // Rule 3: After `sub <name>` without `{`, suggest smart body based on name pattern
        if let Some(sub_name) = self.match_sub_declaration(prefix) {
            if !full_line.contains('{') {
                let body = self.generate_smart_body(&sub_name);
                push_item(
                    0,
                    InlineCompletionItem {
                        insert_text: format!(" {{\n{}\n}}", body),
                        filter_text: Some("{".into()),
                        range: None,
                        command: None,
                    },
                );
            }
        }

        // Rule 4: After `my $` suggest common variable patterns
        if prefix.ends_with("my $") {
            push_item(
                0,
                InlineCompletionItem {
                    insert_text: "self = shift;".into(),
                    filter_text: Some("self".into()),
                    range: None,
                    command: None,
                },
            );
        }

        // Rule 5: After `package ` suggest common suffix patterns
        if prefix.ends_with("package ") {
            push_item(
                0,
                InlineCompletionItem {
                    insert_text: "MyPackage;\n\nuse strict;\nuse warnings;".into(),
                    filter_text: Some("MyPackage".into()),
                    range: None,
                    command: None,
                },
            );
        }

        // Rule 6: After `bless ` suggest common patterns
        if prefix.ends_with("bless ") {
            push_item(
                0,
                InlineCompletionItem {
                    insert_text: "$self, $class;".into(),
                    filter_text: Some("$self".into()),
                    range: None,
                    command: None,
                },
            );
        }

        // Rule 7: After `return ` in constructor context
        if prefix.ends_with("return ") {
            if let Some(variable) = self.preferred_return_variable(context) {
                push_item(
                    0,
                    InlineCompletionItem {
                        insert_text: format!("{variable};"),
                        filter_text: Some(variable),
                        range: None,
                        command: None,
                    },
                );
            } else if self.is_in_constructor_context(context.current_function.as_deref(), prefix) {
                push_item(
                    1,
                    InlineCompletionItem {
                        insert_text: "$self;".into(),
                        filter_text: Some("$self".into()),
                        range: None,
                        command: None,
                    },
                );
            }
        }

        // Rule 8: Complete common loops
        if prefix.ends_with("for ") {
            push_item(
                0,
                InlineCompletionItem {
                    insert_text: "my $item (@items) {\n    \n}".into(),
                    filter_text: Some("my".into()),
                    range: None,
                    command: None,
                },
            );
        }

        if prefix.ends_with("foreach ") {
            push_item(
                0,
                InlineCompletionItem {
                    insert_text: "my $item (@items) {\n    \n}".into(),
                    filter_text: Some("my".into()),
                    range: None,
                    command: None,
                },
            );
        }

        // Rule 9: Complete common test patterns
        if prefix.ends_with("ok(") {
            push_item(
                0,
                InlineCompletionItem {
                    insert_text: "$result, 'test description');".into(),
                    filter_text: Some("$result".into()),
                    range: None,
                    command: None,
                },
            );
        }

        if prefix.ends_with("is(") {
            push_item(
                0,
                InlineCompletionItem {
                    insert_text: "$got, $expected, 'test description');".into(),
                    filter_text: Some("$got".into()),
                    range: None,
                    command: None,
                },
            );
        }

        // Rule 10: Complete shebang
        if prefix == "#!" || prefix == "#!/" {
            push_item(
                0,
                InlineCompletionItem {
                    insert_text: "/usr/bin/env perl".into(),
                    filter_text: Some("perl".into()),
                    range: None,
                    command: None,
                },
            );
        }

        self.add_contextual_fallbacks(context, &mut items, &mut sequence);
        self.normalize_items(items)
    }

    /// Check if we're after a sub declaration without body
    fn match_sub_declaration(&self, prefix: &str) -> Option<String> {
        // Match "sub name" pattern
        if let Some(idx) = prefix.rfind("sub ") {
            let after_sub = &prefix[idx + 4..];
            // Check if we have a name and no opening brace
            if !after_sub.is_empty() && !after_sub.contains('{') && !after_sub.contains('(') {
                // Extract just the sub name
                let name = after_sub.trim();
                if !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') {
                    return Some(name.to_string());
                }
            }
        }
        None
    }

    /// Check if we're in a constructor context (sub new or BUILD)
    fn is_in_constructor_context(&self, current_function: Option<&str>, prefix: &str) -> bool {
        matches!(current_function, Some("new" | "BUILD"))
            || prefix.contains("sub new")
            || prefix.contains("sub BUILD")
    }

    /// Generate a smart subroutine body based on naming patterns
    ///
    /// Detects common Perl subroutine naming conventions and generates
    /// appropriate body templates:
    /// - `new`, `BUILD` -> constructor pattern
    /// - `get_*` -> getter pattern
    /// - `set_*` -> setter pattern
    /// - `is_*`, `has_*`, `can_*` -> boolean accessor pattern
    /// - `_*` -> private method placeholder
    /// - default -> simple method template
    fn generate_smart_body(&self, sub_name: &str) -> String {
        // Constructor patterns
        if sub_name == "new" || sub_name == "BUILD" {
            return "    my $class = shift;\n    my $self = bless {}, $class;\n    return $self;"
                .to_string();
        }

        // Getter pattern: get_something or something_getter
        if let Some(field) = sub_name.strip_prefix("get_") {
            // Remove "get_" prefix
            return format!("    my $self = shift;\n    return $self->{{{}}};", field);
        }

        // Setter pattern: set_something or something_setter
        if let Some(field) = sub_name.strip_prefix("set_") {
            // Remove "set_" prefix
            return format!(
                "    my ($self, $value) = @_;\n    $self->{{{}}} = $value;\n    return $self;",
                field
            );
        }

        // Boolean accessor patterns: is_*, has_*, can_*
        if sub_name.starts_with("is_")
            || sub_name.starts_with("has_")
            || sub_name.starts_with("can_")
        {
            let prefix_len = if sub_name.starts_with("is_") { 3 } else { 4 };
            let field = &sub_name[prefix_len..];
            return format!("    my $self = shift;\n    return $self->{{{}}} ? 1 : 0;", field);
        }

        // Private method placeholder
        if sub_name.starts_with('_') {
            return "    my $self = shift;\n    ...".to_string();
        }

        // Default: simple method with shift
        "    my $self = shift;\n    ...".to_string()
    }

    fn current_function_context(
        &self,
        lines: &[&str],
        line_index: usize,
    ) -> (Option<String>, Option<usize>) {
        lines.iter().take(line_index + 1).enumerate().fold(
            (None, None),
            |mut state, (idx, line)| {
                if let Some(name) = self.parse_sub_name(line) {
                    state = (Some(name), Some(idx));
                }
                state
            },
        )
    }

    fn current_package(&self, lines: &[&str], line_index: usize) -> Option<String> {
        lines
            .iter()
            .take(line_index + 1)
            .filter_map(|line| self.parse_package_name(line))
            .next_back()
    }

    fn previous_non_empty_line<'a>(
        &self,
        lines: &'a [&'a str],
        line_index: usize,
    ) -> Option<&'a str> {
        lines
            .get(..line_index)
            .and_then(|slice| slice.iter().rev().find(|line| !line.trim().is_empty()).copied())
    }

    fn visible_text_until_cursor(&self, lines: &[&str], line_index: usize, prefix: &str) -> String {
        self.visible_text_since_line(lines, 0, line_index, prefix)
    }

    fn visible_text_since_line(
        &self,
        lines: &[&str],
        start_line: usize,
        line_index: usize,
        prefix: &str,
    ) -> String {
        let mut visible_text = String::new();

        for (idx, line) in
            lines.iter().enumerate().skip(start_line).take(line_index.saturating_sub(start_line))
        {
            if idx > start_line {
                visible_text.push('\n');
            }
            visible_text.push_str(line);
        }

        if line_index > start_line || !visible_text.is_empty() {
            visible_text.push('\n');
        }
        visible_text.push_str(prefix);
        visible_text
    }

    fn collect_imports(&self, visible_text: &str) -> Vec<String> {
        let mut imports = Vec::new();

        for line in visible_text.lines() {
            if let Some(import_name) = self.parse_use_name(line) {
                self.push_unique(&mut imports, import_name);
            }
        }

        imports
    }

    fn collect_variables(&self, visible_text: &str) -> Vec<String> {
        let mut matches = Vec::new();
        let bytes = visible_text.as_bytes();
        let mut index = 0usize;

        while index < bytes.len() {
            let byte = bytes[index];
            if byte == b'$' || byte == b'@' || byte == b'%' {
                let start = index;
                index += 1;

                if index >= bytes.len() {
                    break;
                }

                let first = bytes[index] as char;
                if !(first.is_ascii_alphabetic() || first == '_') {
                    continue;
                }

                index += 1;
                while index < bytes.len() {
                    let next = bytes[index] as char;
                    if next.is_ascii_alphanumeric() || next == '_' {
                        index += 1;
                    } else {
                        break;
                    }
                }

                matches.push(visible_text[start..index].to_string());
                continue;
            }

            index += 1;
        }

        let mut variables = Vec::new();
        for variable in matches.into_iter().rev() {
            self.push_unique(&mut variables, variable);
            if variables.len() >= 8 {
                break;
            }
        }

        variables
    }

    fn parse_use_name(&self, line: &str) -> Option<String> {
        let trimmed = line.trim_start();
        let rest = trimmed.strip_prefix("use ")?;
        let name: String = rest
            .chars()
            .take_while(|ch| ch.is_ascii_alphanumeric() || matches!(ch, ':' | '_'))
            .collect();

        (!name.is_empty()).then_some(name)
    }

    fn parse_sub_name(&self, line: &str) -> Option<String> {
        let trimmed = line.trim_start();
        let rest = trimmed.strip_prefix("sub ")?;
        let name: String = rest
            .chars()
            .skip_while(|ch| ch.is_whitespace())
            .take_while(|ch| ch.is_ascii_alphanumeric() || *ch == '_')
            .collect();

        (!name.is_empty()).then_some(name)
    }

    fn parse_package_name(&self, line: &str) -> Option<String> {
        let trimmed = line.trim_start();
        let rest = trimmed.strip_prefix("package ")?;
        let name: String = rest
            .chars()
            .take_while(|ch| ch.is_ascii_alphanumeric() || matches!(ch, ':' | '_'))
            .collect();

        (!name.is_empty()).then_some(name)
    }

    fn add_contextual_fallbacks(
        &self,
        context: &PreparedInlineCompletionContext,
        items: &mut Vec<RankedCompletionItem>,
        sequence: &mut usize,
    ) {
        let prefix = context.prefix.trim();
        let comment_context = context
            .previous_non_empty_line
            .as_deref()
            .map(|line| line.trim_start().starts_with('#'))
            .unwrap_or(false);

        if context.current_line.is_empty()
            && context.current_function.is_none()
            && context.imports.is_empty()
            && context.variables.is_empty()
        {
            items.push(RankedCompletionItem {
                priority: 8,
                order: *sequence,
                item: InlineCompletionItem {
                    insert_text: "#!/usr/bin/env perl\nuse strict;\nuse warnings;\n\n".into(),
                    filter_text: Some("perl".into()),
                    range: None,
                    command: None,
                },
            });
            *sequence += 1;
            items.push(RankedCompletionItem {
                priority: 9,
                order: *sequence,
                item: InlineCompletionItem {
                    insert_text: "use strict;\nuse warnings;\n\n".into(),
                    filter_text: Some("strict".into()),
                    range: None,
                    command: None,
                },
            });
            *sequence += 1;
        }

        if prefix.is_empty() {
            if let Some(variable) = self.preferred_return_variable(context) {
                items.push(RankedCompletionItem {
                    priority: 0,
                    order: *sequence,
                    item: InlineCompletionItem {
                        insert_text: format!("return {variable};"),
                        filter_text: Some(variable),
                        range: None,
                        command: None,
                    },
                });
                *sequence += 1;
            }

            if self.imports_include(context, "Test::More")
                || self.imports_include(context, "Test2::V0")
            {
                items.push(RankedCompletionItem {
                    priority: 1,
                    order: *sequence,
                    item: InlineCompletionItem {
                        insert_text: "done_testing();".into(),
                        filter_text: Some("done_testing".into()),
                        range: None,
                        command: None,
                    },
                });
                *sequence += 1;
            }

            if comment_context && let Some(variable) = self.preferred_assignment_variable(context) {
                items.push(RankedCompletionItem {
                    priority: 2,
                    order: *sequence,
                    item: InlineCompletionItem {
                        insert_text: format!("my {variable} = shift;"),
                        filter_text: Some(variable),
                        range: None,
                        command: None,
                    },
                });
                *sequence += 1;
            }
        }
    }

    fn normalize_items(&self, mut items: Vec<RankedCompletionItem>) -> Vec<InlineCompletionItem> {
        items.sort_by(|left, right| {
            left.priority.cmp(&right.priority).then_with(|| left.order.cmp(&right.order))
        });

        let mut deduped = Vec::new();
        let mut seen = Vec::<String>::new();
        for candidate in items.into_iter() {
            if seen.iter().any(|existing| existing == &candidate.item.insert_text) {
                continue;
            }

            seen.push(candidate.item.insert_text.clone());
            deduped.push(candidate.item);
            if deduped.len() >= MAX_INLINE_COMPLETION_ITEMS {
                break;
            }
        }

        deduped
    }

    fn preferred_return_variable(
        &self,
        context: &PreparedInlineCompletionContext,
    ) -> Option<String> {
        context
            .variables
            .iter()
            .find(|variable| variable.as_str() == "$self")
            .cloned()
            .or_else(|| context.variables.first().cloned())
    }

    fn preferred_assignment_variable(
        &self,
        context: &PreparedInlineCompletionContext,
    ) -> Option<String> {
        context
            .variables
            .iter()
            .find(|variable| variable.starts_with('$') && variable.as_str() != "$self")
            .cloned()
    }

    fn imports_include(&self, context: &PreparedInlineCompletionContext, expected: &str) -> bool {
        context.imports.iter().any(|import_name| import_name == expected)
    }

    fn push_unique(&self, values: &mut Vec<String>, value: String) {
        if values.iter().any(|existing| existing == &value) {
            return;
        }
        values.push(value);
    }
}

struct LineContext<'a> {
    prefix: &'a str,
    current_line: &'a str,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_after_arrow() {
        let provider = InlineCompletionProvider::new();
        let completions = provider.get_inline_completions("$obj->", 0, 6);
        assert!(!completions.items.is_empty());
        assert_eq!(completions.items[0].insert_text, "new()");
    }

    #[test]
    fn test_after_use() {
        let provider = InlineCompletionProvider::new();
        let completions = provider.get_inline_completions("use ", 0, 4);
        assert!(!completions.items.is_empty());
        assert!(completions.items.iter().any(|i| i.insert_text == "strict;"));
    }

    #[test]
    fn test_after_sub() {
        let provider = InlineCompletionProvider::new();
        let completions = provider.get_inline_completions("sub hello", 0, 9);
        assert!(!completions.items.is_empty());
        // Default method generates simple template with shift
        assert!(completions.items[0].insert_text.contains("my $self = shift"));
    }

    #[test]
    fn test_sub_new_constructor() {
        let provider = InlineCompletionProvider::new();
        let completions = provider.get_inline_completions("sub new", 0, 7);
        assert!(!completions.items.is_empty());
        // Constructor generates bless pattern
        assert!(completions.items[0].insert_text.contains("bless"));
        assert!(completions.items[0].insert_text.contains("my $class = shift"));
    }

    #[test]
    fn test_sub_getter() {
        let provider = InlineCompletionProvider::new();
        let completions = provider.get_inline_completions("sub get_name", 0, 12);
        assert!(!completions.items.is_empty());
        // Getter generates accessor pattern
        assert!(completions.items[0].insert_text.contains("return $self->{name}"));
    }

    #[test]
    fn test_sub_setter() {
        let provider = InlineCompletionProvider::new();
        let completions = provider.get_inline_completions("sub set_name", 0, 12);
        assert!(!completions.items.is_empty());
        // Setter generates mutator pattern
        assert!(completions.items[0].insert_text.contains("$self->{name} = $value"));
    }

    #[test]
    fn test_sub_is_predicate() {
        let provider = InlineCompletionProvider::new();
        let completions = provider.get_inline_completions("sub is_active", 0, 13);
        assert!(!completions.items.is_empty());
        // Boolean accessor returns 1/0
        assert!(completions.items[0].insert_text.contains("? 1 : 0"));
    }

    #[test]
    fn test_sub_has_predicate() {
        let provider = InlineCompletionProvider::new();
        let completions = provider.get_inline_completions("sub has_items", 0, 13);
        assert!(!completions.items.is_empty());
        // Boolean accessor returns 1/0
        assert!(completions.items[0].insert_text.contains("? 1 : 0"));
    }

    #[test]
    fn test_no_completion_when_brace_exists() {
        let provider = InlineCompletionProvider::new();
        let completions = provider.get_inline_completions("sub hello {", 0, 9);
        // Should not suggest brace when one exists
        assert!(completions.items.is_empty() || !completions.items[0].insert_text.contains('{'));
    }

    #[test]
    fn test_shebang_completion() {
        let provider = InlineCompletionProvider::new();
        let completions = provider.get_inline_completions("#!/", 0, 3);
        assert!(!completions.items.is_empty());
        assert_eq!(completions.items[0].insert_text, "/usr/bin/env perl");
    }

    #[test]
    fn test_after_arrow_with_unicode_prefix_uses_utf16_position() {
        let provider = InlineCompletionProvider::new();
        let source = "my $emoji = \"😀\"; my $obj = Package->";
        let character = source.encode_utf16().count() as u32;
        let completions = provider.get_inline_completions(source, 0, character);

        assert!(!completions.items.is_empty());
        assert_eq!(completions.items[0].insert_text, "new()");
    }

    #[test]
    fn test_prepare_context_collects_function_variables_and_imports()
    -> Result<(), Box<dyn std::error::Error>> {
        let provider = InlineCompletionProvider::new();
        let source = "use Test::More;\npackage Demo;\n\nsub helper {\n    my $result = 1;\n    my $status = $result;\n    \n}\n";
        let line = 6;
        let character = 4;
        let context =
            provider.prepare_context(source, line, character).ok_or("expected prepared context")?;

        assert_eq!(context.current_function.as_deref(), Some("helper"));
        assert_eq!(context.current_package.as_deref(), Some("Demo"));
        assert_eq!(context.previous_non_empty_line.as_deref(), Some("    my $status = $result;"));
        assert!(context.imports.iter().any(|import_name| import_name == "Test::More"));
        assert!(context.variables.iter().any(|variable| variable == "$status"));
        assert!(context.variables.iter().any(|variable| variable == "$result"));
        Ok(())
    }

    #[test]
    fn test_empty_file_gets_scaffold_suggestions() {
        let provider = InlineCompletionProvider::new();
        let completions = provider.get_inline_completions("", 0, 0);

        assert!(!completions.items.is_empty());
        assert!(completions.items.iter().any(|item| item.insert_text.contains("use strict;")));
    }

    #[test]
    fn test_blank_line_in_function_prefers_nearby_variable() {
        let provider = InlineCompletionProvider::new();
        let source = "sub helper {\n    my $result = compute();\n    \n}\n";
        let completions = provider.get_inline_completions(source, 2, 4);

        assert!(!completions.items.is_empty());
        assert!(completions.items.iter().any(|item| item.insert_text == "return $result;"));
    }

    #[test]
    fn test_blank_line_after_comment_still_has_contextual_suggestions() {
        let provider = InlineCompletionProvider::new();
        let source = "use Test::More;\n\nsub helper {\n    my $result = 1;\n    # explain next step\n    \n}\n";
        let completions = provider.get_inline_completions(source, 5, 4);

        assert!(!completions.items.is_empty());
        assert!(completions.items.iter().any(|item| item.insert_text == "return $result;"));
        assert!(completions.items.iter().any(|item| item.insert_text == "done_testing();"));
    }

    #[test]
    fn test_normalize_items_orders_deduplicates_and_limits() {
        let provider = InlineCompletionProvider::new();
        let items = vec![
            RankedCompletionItem {
                priority: 2,
                order: 0,
                item: InlineCompletionItem {
                    insert_text: "late".into(),
                    filter_text: None,
                    range: None,
                    command: None,
                },
            },
            RankedCompletionItem {
                priority: 0,
                order: 1,
                item: InlineCompletionItem {
                    insert_text: "first".into(),
                    filter_text: None,
                    range: None,
                    command: None,
                },
            },
            RankedCompletionItem {
                priority: 0,
                order: 2,
                item: InlineCompletionItem {
                    insert_text: "first".into(),
                    filter_text: Some("duplicate".into()),
                    range: None,
                    command: None,
                },
            },
            RankedCompletionItem {
                priority: 1,
                order: 3,
                item: InlineCompletionItem {
                    insert_text: "second".into(),
                    filter_text: None,
                    range: None,
                    command: None,
                },
            },
            RankedCompletionItem {
                priority: 3,
                order: 4,
                item: InlineCompletionItem {
                    insert_text: "third".into(),
                    filter_text: None,
                    range: None,
                    command: None,
                },
            },
            RankedCompletionItem {
                priority: 4,
                order: 5,
                item: InlineCompletionItem {
                    insert_text: "fourth".into(),
                    filter_text: None,
                    range: None,
                    command: None,
                },
            },
            RankedCompletionItem {
                priority: 5,
                order: 6,
                item: InlineCompletionItem {
                    insert_text: "fifth".into(),
                    filter_text: None,
                    range: None,
                    command: None,
                },
            },
        ];

        let normalized = provider.normalize_items(items);

        assert_eq!(normalized.len(), MAX_INLINE_COMPLETION_ITEMS);
        assert_eq!(normalized[0].insert_text, "first");
        assert_eq!(normalized[1].insert_text, "second");
        assert_eq!(normalized[2].insert_text, "late");
        assert_eq!(normalized[3].insert_text, "third");
        assert_eq!(normalized[4].insert_text, "fourth");
    }
}