capnprotols 0.1.3

Language server and formatter (capnpfmt) for Cap'n Proto schema files
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
//! Integration tests for the capnprotols LSP server.
//!
//! Each test spins up a real binary, drives it through the LSP protocol over stdio, and
//! asserts on the JSON responses. Tests share a small client harness in `common/`.
//!
//! `cargo test --test integration` runs them.

mod common;

use std::process::Command;

use serde_json::{json, Value};

use crate::common::{LspClient, TempProject};

/// Build a TempProject that contains user.capnp + types.capnp (since user imports types).
fn user_project() -> TempProject {
  TempProject::with_fixtures(&["user.capnp", "types.capnp"])
}

/// Find the column right after the first occurrence of `needle` on lines that contain
/// `line_match`. Returns (line, column).
fn locate(text: &str, line_match: &str, needle: &str) -> (u32, u32) {
  for (i, line) in text.lines().enumerate() {
    if line.contains(line_match) {
      if let Some(c) = line.find(needle) {
        return (i as u32, (c + needle.len()) as u32);
      }
    }
  }
  panic!("locate: line containing {line_match:?} with {needle:?} not found");
}

/// Position the cursor inside `needle` (one byte past its start) on the first line that
/// contains `line_match`.
fn locate_inside(text: &str, line_match: &str, needle: &str) -> (u32, u32) {
  for (i, line) in text.lines().enumerate() {
    if line.contains(line_match) {
      if let Some(c) = line.find(needle) {
        return (i as u32, (c + 1) as u32);
      }
    }
  }
  panic!(
    "locate_inside: line containing {line_match:?} with {needle:?} not found"
  );
}

fn pos(line: u32, character: u32) -> Value {
  json!({ "line": line, "character": character })
}

#[test]
fn initialize_advertises_capabilities() {
  let mut c = LspClient::start();
  // initialize already happened; ask for the result by triggering one method that
  // requires a capability and checking it doesn't error.
  let r = c.request_no_params("shutdown");
  assert!(r.get("error").is_none(), "shutdown error: {r}");
  c.notify_no_params("exit");
}

#[test]
fn diagnostics_published_on_open() {
  let mut c = LspClient::start();
  let proj = user_project();
  let diags = c.open(&proj.uri("user.capnp"), &proj.text("user.capnp"));
  assert!(diags.is_empty(), "expected no diagnostics, got {diags:?}");
  c.shutdown();
}

#[test]
fn diagnostics_have_ranges_and_messages() {
  let mut c = LspClient::start();
  let proj = TempProject::with_fixtures(&[]);
  let path = proj.path("bad.capnp");
  let text = "@0xeaf06436acd04fc9;\nstruct Foo { foo @0 :NoSuchType; }\n";
  std::fs::write(&path, text).unwrap();
  let uri = format!("file://{}", path.display());

  let diags = c.open(&uri, text);
  assert!(!diags.is_empty(), "expected diagnostics");
  let d = &diags[0];
  assert_eq!(d["source"], "capnp");
  let msg = d["message"].as_str().unwrap();
  assert!(msg.contains("NoSuchType"), "msg: {msg}");
  let range = &d["range"];
  assert_eq!(
    range["start"]["line"], 1,
    "should land on line 2 (0-indexed 1)"
  );
  let start_char = range["start"]["character"].as_u64().unwrap();
  let end_char = range["end"]["character"].as_u64().unwrap();
  assert!(
    end_char > start_char,
    "expected non-empty range, got {start_char}..{end_char}"
  );
  c.shutdown();
}

#[test]
fn diagnostics_report_syntax_errors() {
  let mut c = LspClient::start();
  let proj = user_project();
  let uri = proj.uri("user.capnp");
  let text = proj.text("user.capnp");
  c.open(&uri, &text);

  let broken = format!("{}\nGARBAGE_TOKEN!!!\n", text);
  let diags = c.change(&uri, 2, &broken);
  assert!(!diags.is_empty(), "expected diagnostics for broken file");
  c.shutdown();
}

#[test]
fn goto_definition_resolves_imported_alias() {
  let mut c = LspClient::start();
  let proj = user_project();
  let uri = proj.uri("user.capnp");
  let text = proj.text("user.capnp");
  c.open(&uri, &text);

  // Cursor inside `UUID` of `Types.UUID` on the organisationId line.
  let (line, col) =
    locate_inside(&text, "organisationId @0 :Types.UUID", "UUID");
  let r = c.request(
    "textDocument/definition",
    json!({ "textDocument": { "uri": uri }, "position": pos(line, col) }),
  );
  let result = &r["result"];
  assert!(result.is_object(), "expected definition result, got {r}");
  let target = result["uri"].as_str().expect("target uri");
  assert!(target.ends_with("/types.capnp"), "got {target}");
  let line0 = result["range"]["start"]["line"].as_u64().unwrap();
  assert!(
    line0 < 5,
    "should land on the `using UUID` line near top, got {line0}"
  );
  c.shutdown();
}

#[test]
fn goto_definition_resolves_local_alias() {
  let mut c = LspClient::start();
  let proj = user_project();
  let uri = proj.uri("user.capnp");
  let text = proj.text("user.capnp");
  c.open(&uri, &text);

  // Cursor inside `Types` of `Types.UUID`.
  let (line, col) =
    locate_inside(&text, "organisationId @0 :Types.UUID", "Types");
  let r = c.request(
    "textDocument/definition",
    json!({ "textDocument": { "uri": uri }, "position": pos(line, col) }),
  );
  let result = &r["result"];
  let target = result["uri"].as_str().expect("uri");
  assert!(target.ends_with("/user.capnp"));
  let target_line = result["range"]["start"]["line"].as_u64().unwrap();
  assert_eq!(target_line, 2, "should land on `using Types = ...`");
  c.shutdown();
}

#[test]
fn goto_definition_falls_back_for_nested_type_in_generic() {
  // The type parameter of `List(Inner)` is a nested struct — capnp's FSI doesn't
  // record the inner position, so this exercises the name-based fallback resolving
  // a nested (dotted displayName) target.
  let mut c = LspClient::start();
  let proj = user_project();
  let uri = proj.uri("user.capnp");
  let text = proj.text("user.capnp");
  c.open(&uri, &text);

  let (line, col) = locate_inside(&text, "List(Inner)", "Inner");
  let r = c.request(
    "textDocument/definition",
    json!({ "textDocument": { "uri": uri }, "position": pos(line, col) }),
  );
  let result = &r["result"];
  assert!(result.is_object(), "expected definition, got {r}");
  let target = result["uri"].as_str().unwrap();
  assert!(target.ends_with("/user.capnp"), "got {target}");
  let target_text = std::fs::read_to_string(proj.path("user.capnp")).unwrap();
  let target_line = result["range"]["start"]["line"].as_u64().unwrap() as usize;
  let decl = target_text.lines().nth(target_line).unwrap_or("");
  assert!(
    decl.contains("struct Inner"),
    "expected to land on `struct Inner`, got line: {:?}",
    decl
  );
  c.shutdown();
}

#[test]
fn goto_definition_for_self_nested_in_generic() {
  // Mirrors the real-world case: `struct UserLike { struct SamlIdentity {...};
  // samlIdentities @0 :List(SamlIdentity); }` — the cursor on SamlIdentity inside
  // the List should land on the nested struct declaration.
  let mut c = LspClient::start();
  let proj = user_project();
  let uri = proj.uri("user.capnp");
  let text = proj.text("user.capnp");
  c.open(&uri, &text);

  let (line, col) = locate_inside(&text, "List(SamlIdentity)", "SamlIdentity");
  let r = c.request(
    "textDocument/definition",
    json!({ "textDocument": { "uri": uri }, "position": pos(line, col) }),
  );
  let result = &r["result"];
  assert!(result.is_object(), "expected definition, got {r}");
  let target_line = result["range"]["start"]["line"].as_u64().unwrap() as usize;
  let target_text = std::fs::read_to_string(proj.path("user.capnp")).unwrap();
  let decl = target_text.lines().nth(target_line).unwrap_or("");
  assert!(
    decl.contains("struct SamlIdentity"),
    "expected `struct SamlIdentity`, got {:?}",
    decl
  );
  // Range should point at the name `SamlIdentity` itself, not the `struct` keyword.
  let start_col =
    result["range"]["start"]["character"].as_u64().unwrap() as usize;
  let end_col = result["range"]["end"]["character"].as_u64().unwrap() as usize;
  assert_eq!(
    &decl[start_col..end_col],
    "SamlIdentity",
    "expected target range to span the name token; line was {decl:?}"
  );
  c.shutdown();
}

#[test]
fn goto_definition_falls_back_for_generic_parameters() {
  // CGR's FSI has no entry for `AuthToken` inside `List(AuthToken)`, so we exercise the
  // name-based fallback.
  let mut c = LspClient::start();
  let proj = user_project();
  let uri = proj.uri("user.capnp");
  let text = proj.text("user.capnp");
  c.open(&uri, &text);

  let (line, col) = locate_inside(&text, "List(AuthToken)", "AuthToken");
  let r = c.request(
    "textDocument/definition",
    json!({ "textDocument": { "uri": uri }, "position": pos(line, col) }),
  );
  let result = &r["result"];
  assert!(result.is_object(), "expected definition, got {r}");
  let target = result["uri"].as_str().unwrap();
  assert!(target.ends_with("/user.capnp"));
  c.shutdown();
}

#[test]
fn hover_returns_doc_comment() {
  let mut c = LspClient::start();
  let proj = user_project();
  let uri = proj.uri("user.capnp");
  let text = proj.text("user.capnp");
  c.open(&uri, &text);

  // Hover on AuthToken in `List(AuthToken)` to exercise hover via name fallback.
  let (line, col) = locate_inside(&text, "List(AuthToken)", "AuthToken");
  let r = c.request(
    "textDocument/hover",
    json!({ "textDocument": { "uri": uri }, "position": pos(line, col) }),
  );
  let value = r["result"]["contents"]["value"]
    .as_str()
    .expect("hover markup");
  assert!(value.contains("AuthToken"), "hover label missing: {value}");
  assert!(
    value.contains("Opaque session token"),
    "doc comment missing: {value}"
  );
  c.shutdown();
}

#[test]
fn completion_after_colon_includes_builtins_and_user_types() {
  let mut c = LspClient::start();
  let proj = user_project();
  let uri = proj.uri("user.capnp");
  let text = proj.text("user.capnp");
  c.open(&uri, &text);

  // Right after `:` in `organisationId @0 :Types.UUID`.
  let (line, col) = locate(&text, "organisationId @0 :Types.UUID", ":");
  let r = c.request(
    "textDocument/completion",
    json!({ "textDocument": { "uri": uri }, "position": pos(line, col) }),
  );
  let items = r["result"].as_array().expect("array of items");
  let labels: Vec<&str> =
    items.iter().map(|i| i["label"].as_str().unwrap()).collect();
  for builtin in ["Text", "UInt32", "Bool", "List"] {
    assert!(
      labels.contains(&builtin),
      "missing builtin {builtin}: {labels:?}"
    );
  }
  assert!(labels.contains(&"AuthToken"), "missing user type AuthToken");
  c.shutdown();
}

#[test]
fn completion_after_dollar_only_annotations() {
  let mut c = LspClient::start();
  let proj = user_project();
  let uri = proj.uri("user.capnp");
  let text = proj.text("user.capnp");
  c.open(&uri, &text);

  let (line, col) = locate(&text, "$Json.hex", "$");
  let r = c.request(
    "textDocument/completion",
    json!({ "textDocument": { "uri": uri }, "position": pos(line, col) }),
  );
  let items = r["result"].as_array().expect("items");
  let labels: Vec<&str> =
    items.iter().map(|i| i["label"].as_str().unwrap()).collect();
  // pii is a local annotation; hex/base64 come from json.capnp.
  assert!(labels.contains(&"pii"), "want pii, got {labels:?}");
  assert!(labels.contains(&"hex"), "want hex");
  // No built-in primitives in annotation slot.
  assert!(!labels.contains(&"Text"));
  assert!(!labels.contains(&"UInt32"));
  c.shutdown();
}

#[test]
fn completion_dotted_namespace_of_local_struct_offers_nested_children() {
  // Reported: `:Service.` should suggest only `Kind` (the nested enum), not every
  // type in the index. Local struct/interface namespace resolution.
  let mut c = LspClient::start();
  let proj = TempProject::with_fixtures(&[]);
  let path = proj.path("svc.capnp");
  // First open a valid version so the CGR populates the index, then simulate the
  // user typing `Service.` (which leaves the buffer temporarily unparseable — the
  // cached-index-on-failure behaviour keeps completion working).
  let valid = "@0xeaf06436acd04fe6;\nstruct Service {\n  enum Kind {\n    orderbook @0;\n    user @1;\n  }\n  name @0 :Text;\n  kind @1 :Kind;\n}\n\nstruct ShardTable {\n  kind @0 :Service.Kind;\n}\n";
  std::fs::write(&path, valid).unwrap();
  let uri = format!("file://{}", path.display());
  c.open(&uri, valid);

  let editing = valid.replace(":Service.Kind;", ":Service.;");
  c.change(&uri, 2, &editing);

  let lines: Vec<&str> = editing.lines().collect();
  let line = lines.iter().position(|l| l.contains(":Service.")).unwrap() as u32;
  let col = (lines[line as usize].find(":Service.").unwrap()
    + ":Service.".len()) as u32;
  let r = c.request(
    "textDocument/completion",
    json!({ "textDocument": { "uri": uri }, "position": pos(line, col) }),
  );
  let items = r["result"].as_array().expect("items");
  let labels: Vec<&str> =
    items.iter().map(|i| i["label"].as_str().unwrap()).collect();
  assert!(labels.contains(&"Kind"), "missing Kind, got {labels:?}");
  // Should NOT contain unrelated top-level types like ShardTable / Service itself.
  assert!(
    !labels.contains(&"ShardTable"),
    "leaked unrelated type: {labels:?}"
  );
  assert!(
    !labels.contains(&"Service"),
    "leaked parent itself: {labels:?}"
  );
  c.shutdown();
}

#[test]
fn completion_after_dotted_namespace() {
  let mut c = LspClient::start();
  let proj = user_project();
  let uri = proj.uri("user.capnp");
  let text = proj.text("user.capnp");
  c.open(&uri, &text);

  let (line, col) = locate(&text, "organisationId @0 :Types.UUID", "Types.");
  let r = c.request(
    "textDocument/completion",
    json!({ "textDocument": { "uri": uri }, "position": pos(line, col) }),
  );
  let items = r["result"].as_array().expect("items");
  let labels: Vec<&str> =
    items.iter().map(|i| i["label"].as_str().unwrap()).collect();
  for want in ["UUID", "UTCSecondsSinceEpoch", "Side", "Date"] {
    assert!(labels.contains(&want), "want {want}, got {labels:?}");
  }
  c.shutdown();
}

#[test]
fn completion_field_ordinal_sequence() {
  let mut c = LspClient::start();
  let uri = "file:///tmp/capnprotols-test-ord.capnp".to_string();
  let text = "@0xeaf06436acd04fc5;\nstruct A {\n  foo @0 :Text;\n  bar @1 :UInt8;\n  baz @\n}\n";
  std::fs::write("/tmp/capnprotols-test-ord.capnp", text).unwrap();
  c.open(&uri, text);

  let r = c.request(
    "textDocument/completion",
    json!({ "textDocument": { "uri": uri }, "position": pos(4, 7) }),
  );
  let items = r["result"].as_array().expect("items");
  // Dense sequence (0, 1) -> only one candidate: the next-after-max.
  assert_eq!(items.len(), 1);
  assert_eq!(items[0]["label"], "2");
  assert_eq!(items[0]["detail"], "next field ordinal");
  c.shutdown();
}

#[test]
fn completion_field_ordinal_offers_gaps_first() {
  let mut c = LspClient::start();
  let uri = "file:///tmp/capnprotols-test-ord-gap.capnp".to_string();
  // Ordinals present: 0, 2, 3, 5. Gaps: 1, 4. Next: 6.
  let text = "@0xeaf06436acd04fca;\nstruct A {\n  a @0 :Text;\n  c @2 :Text;\n  d @3 :Text;\n  e @5 :Text;\n  f @\n}\n";
  std::fs::write("/tmp/capnprotols-test-ord-gap.capnp", text).unwrap();
  c.open(&uri, text);

  let r = c.request(
    "textDocument/completion",
    json!({ "textDocument": { "uri": uri }, "position": pos(6, 5) }),
  );
  let items = r["result"].as_array().expect("items");
  let labels: Vec<&str> =
    items.iter().map(|i| i["label"].as_str().unwrap()).collect();
  assert_eq!(labels, vec!["1", "4", "6"], "got {labels:?}");
  assert_eq!(items[0]["preselect"], true);
  c.shutdown();
}

#[test]
fn completion_top_level_at_generates_capnp_id() {
  let mut c = LspClient::start();
  let uri = "file:///tmp/capnprotols-test-id.capnp".to_string();
  let text = "@\n";
  std::fs::write("/tmp/capnprotols-test-id.capnp", text).unwrap();
  c.open(&uri, text);

  let r = c.request(
    "textDocument/completion",
    json!({ "textDocument": { "uri": uri }, "position": pos(0, 1) }),
  );
  let items = r["result"].as_array().expect("items");
  assert_eq!(items.len(), 1);
  let label = items[0]["label"].as_str().unwrap();
  assert!(
    label.starts_with("@0x") && label.len() == 19,
    "expected @0x... id, got {label}"
  );
  assert_eq!(items[0]["detail"], "freshly generated capnp ID");
  c.shutdown();
}

#[test]
fn signature_help_for_annotation() {
  let mut c = LspClient::start();
  let uri = "file:///tmp/capnprotols-test-sig.capnp".to_string();
  let text = "@0xeaf06436acd04fc6;\nusing Json = import \"/capnp/compat/json.capnp\";\nstruct Foo $Json.discriminator() {}\n";
  std::fs::write("/tmp/capnprotols-test-sig.capnp", text).unwrap();
  c.open(&uri, text);

  // Cursor right after `(` in `discriminator(`.
  let lines: Vec<&str> = text.lines().collect();
  let col = lines[2].find("discriminator(").unwrap() + "discriminator(".len();
  let r = c.request(
    "textDocument/signatureHelp",
    json!({ "textDocument": { "uri": uri }, "position": pos(2, col as u32) }),
  );
  let sig = &r["result"]["signatures"][0];
  let label = sig["label"].as_str().unwrap();
  assert!(label.contains("name"), "label missing `name`: {label}");
  assert!(label.contains(":Text"), "label missing :Text: {label}");
  assert_eq!(r["result"]["activeParameter"], 0);
  c.shutdown();
}

#[test]
fn signature_help_for_list() {
  let mut c = LspClient::start();
  let uri = "file:///tmp/capnprotols-test-list.capnp".to_string();
  let text = "@0xeaf06436acd04fc7;\nstruct A { xs @0 :List() ; }\n";
  std::fs::write("/tmp/capnprotols-test-list.capnp", text).unwrap();
  c.open(&uri, text);

  let col = text.lines().nth(1).unwrap().find("List(").unwrap() + "List(".len();
  let r = c.request(
    "textDocument/signatureHelp",
    json!({ "textDocument": { "uri": uri }, "position": pos(1, col as u32) }),
  );
  let sig = &r["result"]["signatures"][0];
  assert_eq!(sig["label"], "List(T)");
  c.shutdown();
}

#[test]
fn formatting_emits_minimal_per_line_edits() {
  // Only one line is dirty; the formatter should return a TextEdit covering just that
  // line range, not the whole file. This keeps editor cursors stable on save-format.
  let mut c = LspClient::start();
  let proj = TempProject::with_fixtures(&[]);
  let path = proj.path("partial.capnp");
  // Lines 1, 2, 4, 5 are clean; line 3 has the bad indent.
  let dirty = "@0xeaf06436acd04fdd;\nstruct A {\n        foo @0 :Text;\n  bar @1 :UInt8;\n}\n";
  std::fs::write(&path, dirty).unwrap();
  let uri = format!("file://{}", path.display());
  c.open(&uri, dirty);

  let r = c.request(
    "textDocument/formatting",
    json!({
        "textDocument": { "uri": uri },
        "options": { "tabSize": 2, "insertSpaces": true },
    }),
  );
  let edits = r["result"].as_array().expect("array of edits");
  assert!(!edits.is_empty(), "expected at least one edit");
  // No edit should cover the whole document. The first clean line is line 0
  // (`@0x...;`), so a 0-length edit at start is fine, but a single edit spanning
  // line 0 to past line 3 would mean we did a full-doc rewrite.
  for edit in edits {
    let start_line = edit["range"]["start"]["line"].as_u64().unwrap();
    let end_line = edit["range"]["end"]["line"].as_u64().unwrap();
    assert!(
      !(start_line == 0 && end_line >= 4),
      "edit covers the whole document: {edit:?}"
    );
  }
  c.shutdown();
}

#[test]
fn formatting_returns_text_edit_for_dirty_file() {
  let mut c = LspClient::start();
  let proj = TempProject::with_fixtures(&[]);
  let path = proj.path("dirty.capnp");
  let dirty = "@0xeaf06436acd04fd4;\nstruct A {\n        foo @0:Text;\n}\n";
  std::fs::write(&path, dirty).unwrap();
  let uri = format!("file://{}", path.display());
  c.open(&uri, dirty);

  let r = c.request(
    "textDocument/formatting",
    json!({
        "textDocument": { "uri": uri },
        "options": { "tabSize": 2, "insertSpaces": true },
    }),
  );
  let edits = r["result"].as_array().expect("array of edits");
  assert!(!edits.is_empty(), "expected at least one edit");
  let combined: String = edits
    .iter()
    .map(|e| e["newText"].as_str().unwrap_or(""))
    .collect();
  assert!(
    combined.contains("  foo @0 :Text;"),
    "got combined:\n{combined}"
  );
  c.shutdown();
}

#[test]
fn formatting_returns_empty_for_clean_file() {
  let mut c = LspClient::start();
  let proj = TempProject::with_fixtures(&["types.capnp"]);
  let uri = proj.uri("types.capnp");
  let text = proj.text("types.capnp");
  c.open(&uri, &text);

  // First normalise via our own formatter so the assertion is stable regardless of
  // how the fixture was authored.
  let pre = c.request(
    "textDocument/formatting",
    json!({
        "textDocument": { "uri": uri },
        "options": { "tabSize": 2, "insertSpaces": true },
    }),
  );
  if let Some(edits) = pre["result"].as_array() {
    if let Some(first) = edits.first() {
      let formatted = first["newText"].as_str().unwrap().to_string();
      std::fs::write(proj.path("types.capnp"), &formatted).unwrap();
      c.change(&uri, 2, &formatted);
    }
  }

  let r = c.request(
    "textDocument/formatting",
    json!({
        "textDocument": { "uri": uri },
        "options": { "tabSize": 2, "insertSpaces": true },
    }),
  );
  let edits = r["result"].as_array().expect("array of edits");
  assert!(
    edits.is_empty(),
    "expected no edits on clean file, got {edits:?}"
  );
  c.shutdown();
}

#[test]
fn formatting_skipped_on_parse_error() {
  let mut c = LspClient::start();
  let proj = TempProject::with_fixtures(&[]);
  let path = proj.path("broken.capnp");
  let broken = "@0xeaf06436acd04fd5;\nstruct A { BROKEN_TOKEN!!! }\n";
  std::fs::write(&path, broken).unwrap();
  let uri = format!("file://{}", path.display());
  c.open(&uri, broken);

  let r = c.request(
    "textDocument/formatting",
    json!({
        "textDocument": { "uri": uri },
        "options": { "tabSize": 2, "insertSpaces": true },
    }),
  );
  let edits = r["result"].as_array().expect("array");
  assert!(
    edits.is_empty(),
    "expected no edits on broken file, got {edits:?}"
  );
  c.shutdown();
}

#[test]
fn formatting_skipped_when_capnpfmtignore_matches() {
  let mut c = LspClient::start();
  let proj = TempProject::with_fixtures(&[]);
  // Plant a fake repo root so .capnpfmtignore discovery stops in the tempdir.
  std::fs::create_dir_all(proj.path(".git")).unwrap();
  std::fs::write(proj.path(".capnpfmtignore"), "vendor/\n").unwrap();
  std::fs::create_dir_all(proj.path("vendor")).unwrap();

  // Same dirty content in two files; one matches the ignore, one doesn't.
  let dirty = "@0xeaf06436acd04fd4;\nstruct A {\n        foo @0:Text;\n}\n";
  let vendored = proj.path("vendor/foo.capnp");
  let normal = proj.path("normal.capnp");
  std::fs::write(&vendored, dirty).unwrap();
  std::fs::write(&normal, dirty).unwrap();

  let vendored_uri = format!("file://{}", vendored.display());
  let normal_uri = format!("file://{}", normal.display());
  c.open(&vendored_uri, dirty);
  c.open(&normal_uri, dirty);

  let v = c.request(
    "textDocument/formatting",
    json!({
        "textDocument": { "uri": vendored_uri },
        "options": { "tabSize": 2, "insertSpaces": true },
    }),
  );
  assert!(
    v["result"].as_array().expect("array").is_empty(),
    "expected no edits on ignored file, got {:?}",
    v["result"]
  );

  // The non-ignored file with identical content must still produce edits.
  let n = c.request(
    "textDocument/formatting",
    json!({
        "textDocument": { "uri": normal_uri },
        "options": { "tabSize": 2, "insertSpaces": true },
    }),
  );
  assert!(
    !n["result"].as_array().expect("array").is_empty(),
    "expected edits on non-ignored file"
  );

  c.shutdown();
}

#[test]
fn semantic_tokens_returns_data() {
  let mut c = LspClient::start();
  let proj = user_project();
  let uri = proj.uri("user.capnp");
  let text = proj.text("user.capnp");
  c.open(&uri, &text);

  let r = c.request(
    "textDocument/semanticTokens/full",
    json!({ "textDocument": { "uri": uri } }),
  );
  let data = r["result"]["data"].as_array().expect("data array");
  assert!(!data.is_empty(), "expected semantic tokens");
  assert_eq!(data.len() % 5, 0, "encoded as 5-tuples");
  c.shutdown();
}

#[test]
fn cached_index_survives_compile_failure() {
  let mut c = LspClient::start();
  let proj = user_project();
  let uri = proj.uri("user.capnp");
  let text = proj.text("user.capnp");
  c.open(&uri, &text);

  // Break the file with a syntax error so the next compile fails.
  let broken = format!("{}\nGARBAGE_TOKEN!!!\n", text);
  c.change(&uri, 2, &broken);

  // Completion in a type slot should still see user types from the cached index.
  let (line, col) = locate(&broken, "organisationId @0 :Types.UUID", ":");
  let r = c.request(
    "textDocument/completion",
    json!({ "textDocument": { "uri": uri }, "position": pos(line, col) }),
  );
  let items = r["result"].as_array().expect("items");
  let labels: Vec<&str> =
    items.iter().map(|i| i["label"].as_str().unwrap()).collect();
  assert!(labels.contains(&"AuthToken"), "lost user types: {labels:?}");
  c.shutdown();
}

#[test]
fn live_buffer_changes_visible_to_hover() {
  let mut c = LspClient::start();
  let proj = user_project();
  let uri = proj.uri("user.capnp");
  let text = proj.text("user.capnp");
  c.open(&uri, &text);

  let new_text = text.replace(
    "# Opaque session token used in subsequent requests.",
    "# Opaque session token used in subsequent requests.\n  # ADDED LIVE",
  );
  c.change(&uri, 2, &new_text);

  let (line, col) = locate_inside(&new_text, "List(AuthToken)", "AuthToken");
  let r = c.request(
    "textDocument/hover",
    json!({ "textDocument": { "uri": uri }, "position": pos(line, col) }),
  );
  let value = r["result"]["contents"]["value"].as_str().unwrap();
  assert!(
    value.contains("ADDED LIVE"),
    "live edit not reflected: {value}"
  );
  c.shutdown();
}

/// Apply LSP text edits (sorted by range) to a document string, producing the formatted result.
fn apply_edits(text: &str, edits: &[Value]) -> String {
  let lines: Vec<&str> = text.lines().collect();
  let mut result = String::new();
  let mut cur_line: usize = 0;

  // LSP edits from the formatter are line-granularity replacements, sorted by range.
  for edit in edits {
    let start_line = edit["range"]["start"]["line"].as_u64().unwrap() as usize;
    let start_char =
      edit["range"]["start"]["character"].as_u64().unwrap() as usize;
    let end_line = edit["range"]["end"]["line"].as_u64().unwrap() as usize;
    let end_char = edit["range"]["end"]["character"].as_u64().unwrap() as usize;
    let new_text = edit["newText"].as_str().unwrap();

    // Copy unchanged lines before this edit.
    while cur_line < start_line {
      result.push_str(lines[cur_line]);
      result.push('\n');
      cur_line += 1;
    }

    // Partial start line (chars before start_char).
    if cur_line < lines.len() {
      let line = lines[cur_line];
      let byte_start = line
        .char_indices()
        .nth(start_char)
        .map(|(i, _)| i)
        .unwrap_or(line.len());
      result.push_str(&line[..byte_start]);
    }

    // Insert replacement text.
    result.push_str(new_text);

    // Skip over replaced lines.
    if end_line < lines.len() {
      let end_line_text = lines[end_line];
      let byte_end = end_line_text
        .char_indices()
        .nth(end_char)
        .map(|(i, _)| i)
        .unwrap_or(end_line_text.len());
      result.push_str(&end_line_text[byte_end..]);
      result.push('\n');
      cur_line = end_line + 1;
    } else {
      cur_line = lines.len();
    }
  }

  // Copy remaining lines.
  while cur_line < lines.len() {
    result.push_str(lines[cur_line]);
    result.push('\n');
    cur_line += 1;
  }
  result
}

/// Upstream capnproto schema files copied into tests/fixtures/upstream-*.capnp.
/// These cover annotations, generics, interfaces, enums, and large nested schemas.
const UPSTREAM_FIXTURES: &[&str] = &[
  "upstream-c++.capnp",
  "upstream-persistent.capnp",
  "upstream-schema.capnp",
  "upstream-stream.capnp",
  "upstream-addressbook.capnp",
];

#[test]
fn formatting_upstream_schemas_produces_valid_output() {
  let proj = TempProject::with_fixtures(UPSTREAM_FIXTURES);
  let mut c = LspClient::start();
  let mut failures: Vec<String> = Vec::new();

  for &name in UPSTREAM_FIXTURES {
    let text = proj.text(name);
    let path = proj.path(name);
    let uri = proj.uri(name);
    c.open(&uri, &text);

    let r = c.request(
      "textDocument/formatting",
      json!({
          "textDocument": { "uri": uri },
          "options": { "tabSize": 2, "insertSpaces": true },
      }),
    );

    let formatted = if let Some(edits) = r["result"].as_array() {
      if edits.is_empty() {
        text.clone()
      } else {
        apply_edits(&text, edits)
      }
    } else {
      failures.push(format!("{name}: formatter returned null (parse error)"));
      continue;
    };

    if !validate_capnp(&formatted, &path) {
      failures.push(format!("{name}: formatted output fails capnp compile",));
    }

    // Idempotency: formatting again should produce no edits.
    c.change(&uri, 2, &formatted);
    let r2 = c.request(
      "textDocument/formatting",
      json!({
          "textDocument": { "uri": uri },
          "options": { "tabSize": 2, "insertSpaces": true },
      }),
    );
    if let Some(edits2) = r2["result"].as_array() {
      if !edits2.is_empty() {
        let re_formatted = apply_edits(&formatted, edits2);
        let diff: String = formatted
          .lines()
          .zip(re_formatted.lines())
          .enumerate()
          .filter(|(_, (a, b))| a != b)
          .map(|(i, (a, b))| {
            format!("  line {i}:\n    pass1: {a:?}\n    pass2: {b:?}")
          })
          .take(10)
          .collect::<Vec<_>>()
          .join("\n");
        failures.push(format!("{name}: formatting is not idempotent\n{diff}"));
      }
    }
  }

  c.shutdown();

  if !failures.is_empty() {
    panic!(
      "{} formatting failure(s):\n\n{}",
      failures.len(),
      failures.join("\n\n---\n\n")
    );
  }
}

/// Write text to a temp file alongside the original and run `capnp compile -o-` to validate it.
fn validate_capnp(text: &str, original_path: &std::path::Path) -> bool {
  let dir = original_path.parent().unwrap();
  let tmp = dir.join("__capnprotols_format_check__.capnp");
  std::fs::write(&tmp, text).expect("write temp file");

  let output = Command::new("capnp")
    .arg("compile")
    .arg("-o-")
    .arg(&tmp)
    .stdout(std::process::Stdio::null())
    .stderr(std::process::Stdio::piped())
    .output()
    .expect("failed to run capnp compile");

  let _ = std::fs::remove_file(&tmp);

  if !output.status.success() {
    let stderr = String::from_utf8_lossy(&output.stderr);
    eprintln!(
      "  capnp compile failed for {}:\n{}",
      original_path.display(),
      stderr
    );
  }
  output.status.success()
}