php-lsp 0.10.0

A PHP Language Server Protocol implementation
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
use tower_lsp::lsp_types::{Location, Position, Range, Url};

/// A fuzzy-match query with its lowercase form computed once.
///
/// Matching loops over thousands of candidates (workspace symbols, completion
/// filtering) previously lowercased the query — and the candidate, into fresh
/// `String`s — per candidate. Build a `FuzzyQuery` once per request instead;
/// the per-candidate checks below allocate nothing (char-iterator comparisons,
/// Unicode-lowercase-correct like the old code).
pub(crate) struct FuzzyQuery {
    lower: String,
}

impl FuzzyQuery {
    pub(crate) fn new(query: &str) -> Self {
        FuzzyQuery {
            lower: query.to_lowercase(),
        }
    }

    /// Returns `true` if the query matches `candidate` using
    /// camelCase/underscore abbreviation rules (no substring fallback).
    ///
    /// Rules (applied in order, first match wins):
    /// 1. `candidate` starts with the query (case-insensitive prefix match).
    /// 2. Every character of the query matches a camelCase word boundary or
    ///    character after `_` / `$` in the candidate.
    ///
    /// Examples:
    /// - `"GRF"` matches `"getRecentFiles"`
    /// - `"str_r"` matches `"str_replace"` (boundary after `_`)
    ///
    /// See [`Self::symbol_match`] for the variant that also accepts
    /// substrings, which is appropriate for workspace symbol search but not
    /// for completions.
    pub(crate) fn camel_match(&self, candidate: &str) -> bool {
        if self.lower.is_empty() {
            return true;
        }
        // Rule 1: plain prefix
        if starts_with_at(candidate, &self.lower, 0) {
            return true;
        }
        // Rule 2: camel / underscore abbreviation
        self.camel_abbrev(candidate)
    }

    /// Like [`Self::camel_match`] but also accepts contiguous substrings as a
    /// fallback.  Use for workspace symbol search (where "Controller" should
    /// match "BlogController") but NOT for completions (substring produces too
    /// many hits).
    pub(crate) fn symbol_match(&self, candidate: &str) -> bool {
        if self.camel_match(candidate) {
            return true;
        }
        // Substring fallback: "Controller" matches "BlogController".
        // char_indices keeps the scan allocation-free; candidates are short
        // identifiers, so the O(n·m) window walk beats two String allocations.
        candidate
            .char_indices()
            .any(|(i, _)| starts_with_at(candidate, &self.lower, i))
    }

    /// Core camel/underscore abbreviation check against the lowercased query.
    fn camel_abbrev(&self, candidate: &str) -> bool {
        let mut query = self.lower.chars().peekable();
        let mut prev: Option<char> = None;
        for cc in candidate.chars() {
            let Some(&qc) = query.peek() else {
                return true;
            };
            // A "word boundary" in the candidate is: position 0, after '_' or
            // '$', or an uppercase letter after a lowercase letter (camelCase
            // transition).
            let is_boundary = match prev {
                None => true,
                Some('_') | Some('$') => true,
                Some(p) => cc.is_uppercase() && p.is_lowercase(),
            };
            if is_boundary && cc.to_lowercase().next() == Some(qc) {
                query.next();
            }
            prev = Some(cc);
        }
        query.peek().is_none()
    }
}

/// Case-insensitive (Unicode-lowercase) test that `candidate[at..]` starts
/// with the already-lowercased `query_lower`, without allocating.
fn starts_with_at(candidate: &str, query_lower: &str, at: usize) -> bool {
    let mut c = candidate[at..].chars().flat_map(char::to_lowercase);
    let mut q = query_lower.chars();
    loop {
        match (q.next(), c.next()) {
            (None, _) => return true,
            (Some(qc), Some(cc)) if qc == cc => continue,
            _ => return false,
        }
    }
}

/// One-shot wrapper around [`FuzzyQuery::camel_match`]. Prefer building a
/// [`FuzzyQuery`] outside the loop when matching many candidates.
pub(crate) fn fuzzy_camel_match(query: &str, candidate: &str) -> bool {
    FuzzyQuery::new(query).camel_match(candidate)
}

/// One-shot wrapper around [`FuzzyQuery::symbol_match`]. Prefer building a
/// [`FuzzyQuery`] outside the loop when matching many candidates.
pub(crate) fn fuzzy_symbol_match(query: &str, candidate: &str) -> bool {
    FuzzyQuery::new(query).symbol_match(candidate)
}

/// Compute a sort key so prefix matches sort before camel-abbreviation matches.
/// Lower string = higher priority.  Only called on items that passed
/// [`fuzzy_camel_match`], so the `else` branch (substring) is unreachable here.
pub(crate) fn camel_sort_key(query: &str, label: &str) -> String {
    let lq = query.to_lowercase();
    let ll = label.to_lowercase();
    if ll.starts_with(&lq) {
        format!("0{}", ll)
    } else {
        format!("1{}", ll)
    }
}

/// Return `true` if `name` is a known PHP built-in function.
/// Used by hover to generate php.net links.
pub(crate) fn is_php_builtin(name: &str) -> bool {
    // Sorted for binary search.
    const BUILTINS: &[&str] = &[
        "abs",
        "acos",
        "addslashes",
        "array_chunk",
        "array_combine",
        "array_diff",
        "array_fill",
        "array_fill_keys",
        "array_filter",
        "array_flip",
        "array_intersect",
        "array_key_exists",
        "array_keys",
        "array_map",
        "array_merge",
        "array_pad",
        "array_pop",
        "array_push",
        "array_reduce",
        "array_replace",
        "array_reverse",
        "array_search",
        "array_shift",
        "array_slice",
        "array_splice",
        "array_unique",
        "array_unshift",
        "array_values",
        "array_walk",
        "array_walk_recursive",
        "arsort",
        "asin",
        "asort",
        "atan",
        "atan2",
        "base64_decode",
        "base64_encode",
        "basename",
        "boolval",
        "call_user_func",
        "call_user_func_array",
        "ceil",
        "checkdate",
        "class_exists",
        "closedir",
        "compact",
        "constant",
        "copy",
        "cos",
        "date",
        "date_add",
        "date_create",
        "date_diff",
        "date_format",
        "date_sub",
        "define",
        "defined",
        "die",
        "dirname",
        "empty",
        "exit",
        "exp",
        "explode",
        "extract",
        "fclose",
        "feof",
        "fgets",
        "file_exists",
        "file_get_contents",
        "file_put_contents",
        "floatval",
        "floor",
        "fmod",
        "fopen",
        "fputs",
        "fread",
        "fseek",
        "ftell",
        "function_exists",
        "get_class",
        "get_parent_class",
        "gettype",
        "glob",
        "hash",
        "header",
        "headers_sent",
        "htmlentities",
        "htmlspecialchars",
        "http_build_query",
        "implode",
        "in_array",
        "intdiv",
        "interface_exists",
        "intval",
        "is_a",
        "is_array",
        "is_bool",
        "is_callable",
        "is_dir",
        "is_double",
        "is_file",
        "is_finite",
        "is_float",
        "is_infinite",
        "is_int",
        "is_integer",
        "is_long",
        "is_nan",
        "is_null",
        "is_numeric",
        "is_object",
        "is_readable",
        "is_string",
        "is_subclass_of",
        "is_writable",
        "isset",
        "join",
        "json_decode",
        "json_encode",
        "krsort",
        "ksort",
        "lcfirst",
        "list",
        "log",
        "ltrim",
        "max",
        "md5",
        "method_exists",
        "microtime",
        "min",
        "mkdir",
        "mktime",
        "mt_rand",
        "nl2br",
        "number_format",
        "ob_end_clean",
        "ob_get_clean",
        "ob_start",
        "opendir",
        "parse_str",
        "parse_url",
        "pathinfo",
        "pi",
        "pow",
        "preg_match",
        "preg_match_all",
        "preg_quote",
        "preg_replace",
        "preg_split",
        "print_r",
        "printf",
        "property_exists",
        "rand",
        "random_int",
        "rawurldecode",
        "rawurlencode",
        "readdir",
        "realpath",
        "rename",
        "rewind",
        "rmdir",
        "round",
        "rsort",
        "rtrim",
        "scandir",
        "serialize",
        "session_destroy",
        "session_start",
        "setcookie",
        "settype",
        "sha1",
        "sin",
        "sleep",
        "sort",
        "sprintf",
        "sqrt",
        "str_contains",
        "str_ends_with",
        "str_pad",
        "str_repeat",
        "str_replace",
        "str_split",
        "str_starts_with",
        "str_word_count",
        "strcasecmp",
        "strcmp",
        "strip_tags",
        "stripslashes",
        "stristr",
        "strlen",
        "strncasecmp",
        "strncmp",
        "strpos",
        "strrpos",
        "strstr",
        "strtolower",
        "strtotime",
        "strtoupper",
        "strval",
        "substr",
        "substr_count",
        "substr_replace",
        "tan",
        "time",
        "trim",
        "uasort",
        "ucfirst",
        "ucwords",
        "uksort",
        "unlink",
        "unserialize",
        "unset",
        "urldecode",
        "urlencode",
        "usleep",
        "usort",
        "var_dump",
        "var_export",
        "vsprintf",
    ];
    debug_assert!(
        BUILTINS.windows(2).all(|w| w[0] <= w[1]),
        "BUILTINS must be sorted for binary_search"
    );
    BUILTINS.binary_search(&name).is_ok()
}

/// Build the php.net documentation URL for a built-in function name.
pub(crate) fn php_doc_url(name: &str) -> String {
    // php.net uses underscores replaced with dashes in the URL path.
    let slug = name.replace('_', "-");
    format!("https://www.php.net/function.{}", slug)
}

/// Convert a UTF-16 code unit offset into a UTF-8 byte offset for `s`.
///
/// LSP positions use UTF-16 code units; Rust strings are UTF-8.  This helper
/// walks the string's `char_indices`, accumulating UTF-16 units, and returns
/// the byte index of the character at the given UTF-16 offset.  If the offset
/// is past the end of the string, `s.len()` is returned.
pub(crate) fn utf16_offset_to_byte(s: &str, utf16_offset: usize) -> usize {
    let mut utf16_count = 0usize;
    for (byte_idx, ch) in s.char_indices() {
        if utf16_count >= utf16_offset {
            return byte_idx;
        }
        utf16_count += ch.len_utf16();
    }
    s.len()
}

/// Convert an LSP `Position` (line + UTF-16 character column) into a byte
/// offset in `text`. Out-of-range lines clamp to `text.len()`; out-of-range
/// columns clamp to the end of the line (before its `\n`). Used by
/// incremental text sync.
pub(crate) fn position_to_byte_offset(text: &str, pos: Position) -> usize {
    let mut line_start = 0usize;
    for _ in 0..pos.line {
        match text[line_start..].find('\n') {
            Some(i) => line_start += i + 1,
            None => return text.len(),
        }
    }
    let line_end = text[line_start..]
        .find('\n')
        .map_or(text.len(), |i| line_start + i);
    line_start + utf16_offset_to_byte(&text[line_start..line_end], pos.character as usize)
}

/// Apply one LSP incremental content change (replace `range` with `new_text`)
/// to `text`. A malformed range whose end precedes its start degrades to an
/// insertion at `start`.
pub(crate) fn apply_content_change(text: &mut String, range: Range, new_text: &str) {
    let start = position_to_byte_offset(text, range.start);
    let end = position_to_byte_offset(text, range.end).max(start);
    text.replace_range(start..end, new_text);
}

/// Convert a UTF-8 byte offset into a UTF-16 code unit count.
///
/// LSP `Position.character` is measured in UTF-16 code units.  Given a string
/// and a byte offset into it, this returns how many UTF-16 units precede that
/// offset — which is the correct LSP character value.
pub(crate) fn byte_to_utf16(s: &str, byte_offset: usize) -> u32 {
    s[..byte_offset.min(s.len())]
        .chars()
        .map(|c| c.len_utf16() as u32)
        .sum()
}

/// Split a parameter list string on commas, respecting bracket nesting.
///
/// This avoids splitting inside default values like `array $x = [1, 2, 3]`.
/// Each returned slice is trimmed of leading/trailing whitespace.
pub(crate) fn split_params(s: &str) -> Vec<&str> {
    let mut parts = Vec::new();
    let mut depth = 0i32;
    let mut start = 0;
    for (i, ch) in s.char_indices() {
        match ch {
            '(' | '[' | '{' => depth += 1,
            ')' | ']' | '}' => depth -= 1,
            ',' if depth == 0 => {
                parts.push(s[start..i].trim());
                start = i + 1;
            }
            _ => {}
        }
    }
    let last = s[start..].trim();
    if !last.is_empty() {
        parts.push(last);
    }
    parts
}

/// Extract the word (identifier) under the cursor, handling UTF-16 offsets.
fn char_range_for_word(line: &str, char_offset: usize) -> Option<(usize, usize)> {
    let chars: Vec<char> = line.chars().collect();
    let mut utf16_len = 0usize;
    let mut char_pos = 0usize;
    for ch in &chars {
        if utf16_len >= char_offset {
            break;
        }
        utf16_len += ch.len_utf16();
        char_pos += 1;
    }
    let total_utf16: usize = chars.iter().map(|c| c.len_utf16()).sum();
    if char_offset > total_utf16 {
        return None;
    }
    let is_word = |c: char| c.is_alphanumeric() || c == '_' || c == '$' || c == '\\';
    let mut left = char_pos;
    while left > 0 && is_word(chars[left - 1]) {
        left -= 1;
    }
    let mut right = char_pos;
    while right < chars.len() && is_word(chars[right]) {
        right += 1;
    }
    if left == right {
        None
    } else {
        Some((left, right))
    }
}

pub(crate) fn word_at_position(source: &str, position: Position) -> Option<String> {
    // Use split('\n') rather than lines() so that a trailing newline produces a
    // final empty entry — lines() silently drops it, causing word_at_position to return
    // None for any cursor on the last line of a normally-saved PHP file.
    let raw = source.split('\n').nth(position.line as usize)?;
    let line = raw.strip_suffix('\r').unwrap_or(raw);
    let char_offset = position.character as usize;
    let chars: Vec<char> = line.chars().collect();
    let (left, right) = char_range_for_word(line, char_offset)?;
    let word: String = chars[left..right].iter().collect();
    if word.is_empty() { None } else { Some(word) }
}

/// Return the LSP `Range` of the word (identifier) under the cursor.
/// Uses the same word-boundary rules as `word_at_position`.
pub(crate) fn word_range_at(source: &str, position: Position) -> Option<Range> {
    let raw = source.split('\n').nth(position.line as usize)?;
    let line = raw.strip_suffix('\r').unwrap_or(raw);
    let char_offset = position.character as usize;
    let chars: Vec<char> = line.chars().collect();
    let (left, right) = char_range_for_word(line, char_offset)?;
    let start_col = chars[..left]
        .iter()
        .map(|c| c.len_utf16() as u32)
        .sum::<u32>();
    let end_col = chars[..right]
        .iter()
        .map(|c| c.len_utf16() as u32)
        .sum::<u32>();
    Some(Range {
        start: Position {
            line: position.line,
            character: start_col,
        },
        end: Position {
            line: position.line,
            character: end_col,
        },
    })
}

/// Extract the source text covered by an LSP `Range`.
///
/// `Range` positions use UTF-16 code-unit offsets; this function converts them
/// correctly before slicing the UTF-8 source string.
pub(crate) fn selected_text_range(source: &str, range: tower_lsp::lsp_types::Range) -> String {
    let lines: Vec<&str> = source.lines().collect();
    if range.start.line == range.end.line {
        let line = match lines.get(range.start.line as usize) {
            Some(l) => l,
            None => return String::new(),
        };
        let start = utf16_offset_to_byte(line, range.start.character as usize);
        let end = utf16_offset_to_byte(line, range.end.character as usize);
        line[start..end].to_string()
    } else {
        let mut result = String::new();
        for i in range.start.line..=range.end.line {
            let line = match lines.get(i as usize) {
                Some(l) => *l,
                None => break,
            };
            if i == range.start.line {
                let start = utf16_offset_to_byte(line, range.start.character as usize);
                result.push_str(&line[start..]);
            } else if i == range.end.line {
                let end = utf16_offset_to_byte(line, range.end.character as usize);
                result.push_str(&line[..end]);
            } else {
                result.push_str(line);
            }
            if i < range.end.line {
                result.push('\n');
            }
        }
        result
    }
}

/// Count the UTF-16 code units in a string.
/// Needed for LSP `Position.character` calculations, which use UTF-16 offsets.
pub fn utf16_code_units(s: &str) -> u32 {
    s.chars().map(|c| c.len_utf16() as u32).sum()
}

/// Strip the leading `$` sigil from a variable name, if present.
/// Variables are stored both ways: `$var` in source, `var` in symbol tables.
pub fn strip_variable_sigil(word: &str) -> &str {
    word.strip_prefix('$').unwrap_or(word)
}

/// Return the unqualified short name from a PHP fully-qualified name.
/// `"\App\Service\Foo"` → `"Foo"`, `"Foo"` → `"Foo"`, `""` → `""`.
pub(crate) fn fqn_short_name(fqn: &str) -> &str {
    fqn.rsplit('\\').next().unwrap_or(fqn)
}

/// Build a zero-width LSP `Range` at the start of `line` (character 0).
/// Used for index-backed features where only line-level precision is available.
pub(crate) fn zero_width_range(line: u32) -> Range {
    let pos = Position { line, character: 0 };
    Range {
        start: pos,
        end: pos,
    }
}

/// Build a `Location` pointing to the start of `line` in `uri` (character 0).
pub(crate) fn zero_width_location(uri: &Url, line: u32) -> Location {
    Location {
        uri: uri.clone(),
        range: zero_width_range(line),
    }
}

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

    #[test]
    fn byte_to_utf16_ascii() {
        assert_eq!(byte_to_utf16("hello", 3), 3);
    }

    #[test]
    fn byte_to_utf16_multibyte_bmp() {
        // "é" is U+00E9: 2 bytes in UTF-8, 1 code unit in UTF-16.
        let s = "café";
        assert_eq!(byte_to_utf16(s, 0), 0);
        assert_eq!(byte_to_utf16(s, 3), 3); // up to "caf" (all ASCII)
        assert_eq!(byte_to_utf16(s, 5), 4); // full string (é = 2 bytes → 1 UTF-16 unit)
    }

    #[test]
    fn byte_to_utf16_surrogate_pair() {
        // "😀" is U+1F600: 4 bytes in UTF-8, 2 code units in UTF-16 (surrogate pair).
        let s = "a😀b";
        assert_eq!(byte_to_utf16(s, 1), 1); // after "a"
        assert_eq!(byte_to_utf16(s, 5), 3); // after "a😀" (emoji = 4 bytes → 2 UTF-16 units)
        assert_eq!(byte_to_utf16(s, 6), 4); // full string
    }

    #[test]
    fn byte_to_utf16_past_end_clamps() {
        assert_eq!(byte_to_utf16("hi", 100), 2);
    }

    #[test]
    fn utf16_offset_to_byte_ascii() {
        assert_eq!(utf16_offset_to_byte("hello", 3), 3);
    }

    #[test]
    fn utf16_offset_to_byte_surrogate_pair() {
        // "a😀b": UTF-16 offset 1 → byte 1 (start of emoji), offset 3 → byte 5 (after emoji)
        let s = "a😀b";
        assert_eq!(utf16_offset_to_byte(s, 1), 1);
        assert_eq!(utf16_offset_to_byte(s, 3), 5);
    }

    #[test]
    fn position_to_byte_offset_basic() {
        let s = "<?php\necho 1;\n";
        let p = |line, character| Position { line, character };
        assert_eq!(position_to_byte_offset(s, p(0, 0)), 0);
        assert_eq!(position_to_byte_offset(s, p(0, 5)), 5);
        assert_eq!(position_to_byte_offset(s, p(1, 0)), 6);
        assert_eq!(position_to_byte_offset(s, p(1, 4)), 10);
        // Column past end of line clamps to before the newline.
        assert_eq!(position_to_byte_offset(s, p(0, 99)), 5);
        // Line past end of text clamps to text length.
        assert_eq!(position_to_byte_offset(s, p(9, 0)), s.len());
    }

    #[test]
    fn position_to_byte_offset_multibyte() {
        // 😀 is one char, 4 UTF-8 bytes, 2 UTF-16 units.
        let s = "a😀b\nx";
        let p = |line, character| Position { line, character };
        assert_eq!(position_to_byte_offset(s, p(0, 1)), 1);
        assert_eq!(position_to_byte_offset(s, p(0, 3)), 5);
        assert_eq!(position_to_byte_offset(s, p(1, 0)), 7);
        assert_eq!(position_to_byte_offset(s, p(1, 1)), 8);
    }

    #[test]
    fn apply_content_change_replaces_inserts_deletes() {
        let r = |sl, sc, el, ec| Range {
            start: Position {
                line: sl,
                character: sc,
            },
            end: Position {
                line: el,
                character: ec,
            },
        };
        // Replacement within a line.
        let mut s = String::from("<?php\necho one;\n");
        apply_content_change(&mut s, r(1, 5, 1, 8), "two");
        assert_eq!(s, "<?php\necho two;\n");
        // Pure insertion (empty range).
        let mut s = String::from("ab\ncd\n");
        apply_content_change(&mut s, r(1, 1, 1, 1), "X");
        assert_eq!(s, "ab\ncXd\n");
        // Deletion spanning a newline (end position at start of next line).
        let mut s = String::from("ab\ncd\nef\n");
        apply_content_change(&mut s, r(0, 2, 1, 0), "");
        assert_eq!(s, "abcd\nef\n");
        // Malformed range (end before start) degrades to insertion.
        let mut s = String::from("abc");
        apply_content_change(&mut s, r(0, 2, 0, 1), "X");
        assert_eq!(s, "abXc");
    }

    #[test]
    fn byte_to_utf16_and_back_roundtrip() {
        let s = "café 😀 world";
        for (byte_idx, _) in s.char_indices() {
            let utf16 = byte_to_utf16(s, byte_idx) as usize;
            assert_eq!(utf16_offset_to_byte(s, utf16), byte_idx);
        }
    }

    #[test]
    fn word_at_last_line_with_trailing_newline() {
        // Editors save files with a trailing newline; lines() drops the final
        // empty entry, making word_at return None for cursors on the last line.
        let src = "<?php\necho strlen($x);\n";
        let pos = Position {
            line: 1,
            character: 6,
        }; // "strlen" on line 1
        let w = word_at_position(src, pos);
        assert_eq!(
            w.as_deref(),
            Some("strlen"),
            "word_at_position must work on lines before the trailing newline"
        );
        // Position on the final empty line produced by the trailing newline.
        let last_line = Position {
            line: 2,
            character: 0,
        };
        // Should return None (empty line), but must not panic.
        let _ = word_at_position(src, last_line);
    }

    #[test]
    fn word_at_crlf_line_endings() {
        let src = "<?php\r\nfunction foo() {}\r\n";
        let pos = Position {
            line: 1,
            character: 9,
        }; // "foo"
        let w = word_at_position(src, pos);
        assert_eq!(
            w.as_deref(),
            Some("foo"),
            "word_at_position must handle CRLF line endings"
        );
    }

    #[test]
    fn is_php_builtin_asin_recognized() {
        // asin was out of order in BUILTINS, causing binary_search to miss it.
        assert!(
            is_php_builtin("asin"),
            "asin must be recognised as a PHP builtin"
        );
        assert!(
            is_php_builtin("atan"),
            "atan must be recognised as a PHP builtin"
        );
        assert!(
            is_php_builtin("krsort"),
            "krsort must be recognised as a PHP builtin"
        );
        assert!(
            is_php_builtin("strcasecmp"),
            "strcasecmp must be recognised as a PHP builtin"
        );
        assert!(
            is_php_builtin("strncasecmp"),
            "strncasecmp must be recognised as a PHP builtin"
        );
        assert!(
            is_php_builtin("strip_tags"),
            "strip_tags must be recognised as a PHP builtin"
        );
    }

    #[test]
    fn fuzzy_camel_match_prefix() {
        assert!(fuzzy_camel_match("Blog", "BlogController"));
        assert!(fuzzy_camel_match("blog", "BlogController"));
    }

    #[test]
    fn fuzzy_camel_match_abbreviation() {
        assert!(fuzzy_camel_match("BC", "BlogController"));
        assert!(fuzzy_camel_match("GRF", "getRecentFiles"));
        assert!(fuzzy_camel_match("str_r", "str_replace")); // boundary after '_'
    }

    #[test]
    fn fuzzy_camel_match_no_substring() {
        // fuzzy_camel_match (used for completions) must NOT match substrings
        assert!(!fuzzy_camel_match("Controller", "BlogController"));
        assert!(!fuzzy_camel_match("xyz", "BlogController"));
    }

    #[test]
    fn fuzzy_symbol_match_substring_fallback() {
        // fuzzy_symbol_match (used for workspace symbols) DOES match substrings
        assert!(fuzzy_symbol_match("Controller", "BlogController"));
        assert!(fuzzy_symbol_match("controller", "BlogController"));
        assert!(fuzzy_symbol_match("controller", "UserController"));
        // prefix and camel still work
        assert!(fuzzy_symbol_match("Blog", "BlogController"));
        assert!(fuzzy_symbol_match("BC", "BlogController"));
        // no match
        assert!(!fuzzy_symbol_match("xyz", "BlogController"));
    }
}