1use proc_macro2::TokenStream;
31use quote::quote;
32
33use crate::resolve::ResolvedSchema;
34use crate::schema::types::UnionVariant;
35use crate::util::{to_snake_case, CapnpType};
36
37#[derive(Copy, Clone, Debug, PartialEq, Eq)]
41pub enum NodeKind {
42 File,
43 Dir,
44 Ctl,
45 Stream,
46 Query,
47}
48
49impl NodeKind {
50 fn parse(s: &str) -> Option<Self> {
52 match s {
53 "file" => Some(Self::File),
54 "dir" => Some(Self::Dir),
55 "ctl" => Some(Self::Ctl),
56 "stream" => Some(Self::Stream),
57 "query" => Some(Self::Query),
58 _ => None,
59 }
60 }
61
62 fn is_read_only(self) -> bool {
64 matches!(self, Self::File | Self::Dir | Self::Query)
65 }
66
67 fn to_tokens(self) -> TokenStream {
69 match self {
70 Self::File => quote! { hyprstream_rpc::metadata::VfsNodeKind::File },
71 Self::Dir => quote! { hyprstream_rpc::metadata::VfsNodeKind::Dir },
72 Self::Ctl => quote! { hyprstream_rpc::metadata::VfsNodeKind::Ctl },
73 Self::Stream => quote! { hyprstream_rpc::metadata::VfsNodeKind::Stream },
74 Self::Query => quote! { hyprstream_rpc::metadata::VfsNodeKind::Query },
75 }
76 }
77}
78
79fn scope_is_write_class(scope: &str) -> bool {
86 !matches!(scope, "" | "query" | "subscribe")
87}
88
89fn is_list_name(name: &str) -> bool {
91 let snake = to_snake_case(name);
92 snake == "list" || snake.starts_with("list_")
93}
94
95pub fn infer_kind(scope: &str, arg: &CapnpType, name: &str, is_streaming: bool) -> NodeKind {
99 if is_streaming {
100 return NodeKind::Stream;
101 }
102 if scope_is_write_class(scope) {
103 return NodeKind::Ctl;
104 }
105 match arg {
107 CapnpType::Void if is_list_name(name) => NodeKind::Dir,
109 arg if is_query_file_arg(arg) => NodeKind::Query,
113 _ => NodeKind::File,
114 }
115}
116
117fn is_query_file_arg(arg: &CapnpType) -> bool {
120 matches!(
121 arg,
122 CapnpType::Struct(_)
123 | CapnpType::Unknown(_)
124 | CapnpType::ListText
125 | CapnpType::ListData
126 | CapnpType::ListPrimitive(_)
127 | CapnpType::ListStruct(_)
128 | CapnpType::Data
129 )
130}
131
132pub fn resolve_kind(
136 v: &UnionVariant,
137 arg: &CapnpType,
138 is_streaming: bool,
139) -> Result<NodeKind, String> {
140 if v.vfs_kind.is_empty() {
141 Ok(infer_kind(&v.scope, arg, &v.name, is_streaming))
142 } else {
143 NodeKind::parse(&v.vfs_kind).ok_or_else(|| {
144 format!(
145 "method `{}`: `$vfsKind(\"{}\")` is not a valid VFS node kind \
146 (expected one of file/dir/ctl/stream/query)",
147 to_snake_case(&v.name),
148 v.vfs_kind
149 )
150 })
151 }
152}
153
154pub fn validate_node(method_snake: &str, scope: &str, kind: NodeKind) -> Result<(), String> {
162 let write_class = scope_is_write_class(scope);
163 if write_class && kind.is_read_only() {
164 return Err(format!(
165 "method `{method_snake}`: write/authority-class scope `{scope}` cannot project to a \
166 read-only VFS node (`{kind:?}`) — a 9P read must be side-effect-free; \
167 use `$vfsKind(ctl)` or `$vfsKind(stream)`"
168 ));
169 }
170 if !write_class && matches!(kind, NodeKind::Ctl) {
171 return Err(format!(
172 "method `{method_snake}`: read-class scope `{scope}` cannot project to a `ctl` node \
173 — a control-file write invokes the method; use a read kind \
174 (`$vfsKind(file|dir|query)`) or give the method a write scope"
175 ));
176 }
177 Ok(())
178}
179
180fn infer_path(
190 kind: NodeKind,
191 method_snake: &str,
192 arg: &CapnpType,
193 dir_is_sole_listing: bool,
194) -> String {
195 match kind {
196 NodeKind::Dir if dir_is_sole_listing => ".".to_owned(),
200 NodeKind::Dir => method_snake
201 .strip_prefix("list_")
202 .unwrap_or(method_snake)
203 .to_owned(),
204 NodeKind::File if !matches!(arg, CapnpType::Void) => "{arg}".to_owned(),
206 NodeKind::Ctl => "ctl".to_owned(),
208 NodeKind::Stream | NodeKind::Query | NodeKind::File => method_snake.to_owned(),
211 }
212}
213
214fn build_node_entries(
226 variants: &[UnionVariant],
227 scoped_names: &[&str],
228 response_variants: &[UnionVariant],
229 resolved: &ResolvedSchema,
230) -> Result<Vec<TokenStream>, TokenStream> {
231 struct Resolved<'a> {
232 variant: &'a UnionVariant,
233 method_snake: String,
234 arg: CapnpType,
235 kind: NodeKind,
236 }
237
238 let mut resolved_variants: Vec<Resolved> = Vec::new();
239 for v in variants {
240 if scoped_names.contains(&v.name.as_str()) || v.vfs_hidden {
243 continue;
244 }
245
246 let method_snake = to_snake_case(&v.name);
247 let arg = resolved.resolve_type(&v.type_name).capnp_type.clone();
248 let is_streaming = is_streaming_variant(&v.name, response_variants);
249
250 let kind = resolve_kind(v, &arg, is_streaming).map_err(|msg| compile_error(&msg))?;
252
253 if let Err(msg) = validate_node(&method_snake, &v.scope, kind) {
255 return Err(compile_error(&msg));
256 }
257
258 resolved_variants.push(Resolved {
259 variant: v,
260 method_snake,
261 arg,
262 kind,
263 });
264 }
265
266 let unannotated_dir_count = resolved_variants
269 .iter()
270 .filter(|r| r.kind == NodeKind::Dir && r.variant.vfs_path.is_empty())
271 .count();
272 let dir_is_sole_listing = unannotated_dir_count <= 1;
273
274 let mut node_entries: Vec<TokenStream> = Vec::new();
275 let mut seen_paths: Vec<(String, String)> = Vec::new();
280
281 for r in &resolved_variants {
282 let v = r.variant;
283 let path = if v.vfs_path.is_empty() {
284 infer_path(r.kind, &r.method_snake, &r.arg, dir_is_sole_listing)
285 } else {
286 v.vfs_path.clone()
287 };
288
289 if r.kind != NodeKind::Ctl {
293 if let Some((_, other)) = seen_paths.iter().find(|(p, _)| *p == path) {
294 return Err(compile_error(&format!(
295 "method `{}` and method `{other}` both project to VFS path `{path}` — set an explicit `$vfsPath` on at least one to disambiguate",
296 r.method_snake
297 )));
298 }
299 seen_paths.push((path.clone(), r.method_snake.clone()));
300 }
301
302 let kind_tokens = r.kind.to_tokens();
303 let method_snake = r.method_snake.as_str();
304 let scope = v.scope.as_str();
305 let bulk = v.vfs_bulk;
306 let mac = v.vfs_mac.as_str();
310
311 node_entries.push(quote! {
312 hyprstream_rpc::metadata::VfsNode {
313 method: #method_snake,
314 path: #path,
315 kind: #kind_tokens,
316 scope: #scope,
317 bulk: #bulk,
318 mac: #mac,
319 }
320 });
321 }
322
323 Ok(node_entries)
324}
325
326pub fn generate_mount(service_name: &str, resolved: &ResolvedSchema) -> TokenStream {
336 if resolved.raw.request_variants.is_empty() {
338 return TokenStream::new();
339 }
340
341 let scoped_names: Vec<&str> = resolved
342 .raw
343 .scoped_clients
344 .iter()
345 .map(|sc| sc.factory_name.as_str())
346 .collect();
347
348 let node_entries = match build_node_entries(
349 &resolved.raw.request_variants,
350 &scoped_names,
351 &resolved.raw.response_variants,
352 resolved,
353 ) {
354 Ok(entries) => entries,
355 Err(err) => return err,
356 };
357
358 let mut scoped_tables: Vec<TokenStream> = Vec::new();
364 for sc in &resolved.raw.scoped_clients {
365 let inner_scoped: Vec<&str> = sc
366 .nested_clients
367 .iter()
368 .map(|n| n.factory_name.as_str())
369 .collect();
370 let inner_entries = match build_node_entries(
371 &sc.inner_request_variants,
372 &inner_scoped,
373 &sc.inner_response_variants,
374 resolved,
375 ) {
376 Ok(entries) => entries,
377 Err(err) => return err,
378 };
379 let prefix = resolved
382 .raw
383 .request_variants
384 .iter()
385 .find(|v| v.name == sc.factory_name)
386 .filter(|v| !v.vfs_path.is_empty())
387 .map(|v| v.vfs_path.clone())
388 .unwrap_or_else(|| to_snake_case(&sc.factory_name));
389 let fn_ident = quote::format_ident!("vfs_nodes_{}", to_snake_case(&sc.factory_name));
390 let sub_doc = format!(
391 "Generated 9P/VFS subdir node table for the `{}` scope of the {service_name} service (epic #539). Mount-relative prefix returned alongside the nodes.",
392 sc.factory_name
393 );
394 scoped_tables.push(quote! {
395 #[doc = #sub_doc]
396 pub fn #fn_ident() -> (&'static str, &'static [hyprstream_rpc::metadata::VfsNode]) {
397 static NODES: &[hyprstream_rpc::metadata::VfsNode] = &[
398 #(#inner_entries,)*
399 ];
400 (#prefix, NODES)
401 }
402 });
403 }
404
405 let doc = format!("Generated 9P/VFS node table for the {service_name} service (epic #539).");
406
407 quote! {
408 #[doc = #doc]
409 pub fn vfs_nodes() -> (&'static str, &'static [hyprstream_rpc::metadata::VfsNode]) {
410 static NODES: &[hyprstream_rpc::metadata::VfsNode] = &[
411 #(#node_entries,)*
412 ];
413 (#service_name, NODES)
414 }
415
416 #[cfg(not(target_arch = "wasm32"))]
430 hyprstream_rpc::metadata::inventory::submit! {
431 hyprstream_rpc::metadata::VfsNodeTable {
432 name: #service_name,
433 nodes_fn: vfs_nodes,
434 }
435 }
436
437 #(#scoped_tables)*
438 }
439}
440
441fn compile_error(msg: &str) -> TokenStream {
443 quote! { ::core::compile_error!(#msg); }
444}
445
446fn is_streaming_variant(variant_name: &str, response_variants: &[UnionVariant]) -> bool {
449 let expected = format!("{variant_name}Result");
450 response_variants
451 .iter()
452 .find(|v| v.name == expected)
453 .map(|v| v.type_name == "StreamInfo")
454 .unwrap_or(false)
455}
456
457#[cfg(test)]
458#[allow(clippy::expect_used, clippy::unwrap_used)]
459mod tests {
460 use super::*;
461
462 #[test]
463 fn infers_dir_for_void_list_query() {
464 let k = infer_kind("query", &CapnpType::Void, "list", false);
465 assert_eq!(k, NodeKind::Dir);
466 }
467
468 #[test]
469 fn infers_file_for_void_query() {
470 let k = infer_kind("query", &CapnpType::Void, "healthCheck", false);
471 assert_eq!(k, NodeKind::File);
472 }
473
474 #[test]
475 fn infers_parameterized_file_for_text_query() {
476 let k = infer_kind("query", &CapnpType::Text, "getByName", false);
477 assert_eq!(k, NodeKind::File);
478 assert_eq!(
479 infer_path(k, "get_by_name", &CapnpType::Text, true),
480 "{arg}"
481 );
482 }
483
484 #[test]
485 fn infers_query_for_struct_query() {
486 let k = infer_kind(
487 "query",
488 &CapnpType::Struct("SearchRequest".into()),
489 "search",
490 false,
491 );
492 assert_eq!(k, NodeKind::Query);
493 }
494
495 #[test]
496 fn infers_ctl_for_write() {
497 let k = infer_kind(
498 "write",
499 &CapnpType::Struct("CloneRequest".into()),
500 "clone",
501 false,
502 );
503 assert_eq!(k, NodeKind::Ctl);
504 assert_eq!(
505 infer_path(k, "clone", &CapnpType::Struct("CloneRequest".into()), true),
506 "ctl"
507 );
508 }
509
510 #[test]
511 fn infers_stream_for_streaming() {
512 let k = infer_kind(
513 "write",
514 &CapnpType::Struct("CloneRequest".into()),
515 "cloneStream",
516 true,
517 );
518 assert_eq!(k, NodeKind::Stream);
519 }
520
521 #[test]
522 fn guard_rejects_write_scope_on_read_only_node() {
523 let err = validate_node("clone", "write", NodeKind::File).unwrap_err();
525 assert!(err.contains("clone"), "error names the method: {err}");
526 assert!(
527 err.contains("side-effect-free"),
528 "error explains why: {err}"
529 );
530 }
531
532 #[test]
533 fn guard_rejects_query_scope_on_ctl_node() {
534 let err = validate_node("get_by_name", "query", NodeKind::Ctl).unwrap_err();
535 assert!(err.contains("get_by_name"));
536 assert!(err.contains("ctl"));
537 }
538
539 #[test]
540 fn guard_permits_consistent_pairings() {
541 assert!(validate_node("clone", "write", NodeKind::Ctl).is_ok());
542 assert!(validate_node("list", "query", NodeKind::Dir).is_ok());
543 assert!(validate_node("get", "query", NodeKind::File).is_ok());
544 assert!(validate_node("search", "query", NodeKind::Query).is_ok());
545 assert!(validate_node("watch", "subscribe", NodeKind::Stream).is_ok());
546 assert!(validate_node("snapshot", "subscribe", NodeKind::File).is_ok());
547 assert!(validate_node("watch", "subscribe", NodeKind::Ctl).is_err());
548 assert!(validate_node("ping", "", NodeKind::File).is_ok());
550 assert!(validate_node("ping", "", NodeKind::Ctl).is_err());
551 }
552
553 #[test]
554 fn bad_vfs_kind_annotation_is_reported() {
555 let v = UnionVariant {
556 name: "clone".into(),
557 type_name: "CloneRequest".into(),
558 description: String::new(),
559 scope: "write".into(),
560 scope_exempt: false,
561 cli_hidden: false,
562 doc_example: String::new(),
563 vfs_path: String::new(),
564 vfs_kind: "bogus".into(),
565 vfs_bulk: false,
566 vfs_hidden: false,
567 vfs_mac: String::new(),
568 dispatch_mac: String::new(),
569 dispatch_public: String::new(),
570 mutation_semantics: String::new(),
571 dispatch_mac_present: false,
572 dispatch_public_present: false,
573 mutation_semantics_present: false,
574 };
575 let err = resolve_kind(&v, &CapnpType::Struct("CloneRequest".into()), false).unwrap_err();
576 assert!(err.contains("bogus"));
577 assert!(err.contains("clone"));
578 }
579
580 #[test]
581 fn vfs_kind_override_wins_over_inference() {
582 let v = UnionVariant {
584 name: "getByName".into(),
585 type_name: "Text".into(),
586 description: String::new(),
587 scope: "query".into(),
588 scope_exempt: false,
589 cli_hidden: false,
590 doc_example: String::new(),
591 vfs_path: String::new(),
592 vfs_kind: "query".into(),
593 vfs_bulk: false,
594 vfs_hidden: false,
595 vfs_mac: String::new(),
596 dispatch_mac: String::new(),
597 dispatch_public: String::new(),
598 mutation_semantics: String::new(),
599 dispatch_mac_present: false,
600 dispatch_public_present: false,
601 mutation_semantics_present: false,
602 };
603 let k = resolve_kind(&v, &CapnpType::Text, false).expect("valid kind");
604 assert_eq!(k, NodeKind::Query);
605 }
606
607 use crate::schema::types::{ParsedSchema, StructDef};
610
611 fn variant(name: &str, type_name: &str, scope: &str) -> UnionVariant {
612 UnionVariant {
613 name: name.into(),
614 type_name: type_name.into(),
615 description: String::new(),
616 scope: scope.into(),
617 scope_exempt: false,
618 cli_hidden: false,
619 doc_example: String::new(),
620 vfs_path: String::new(),
621 vfs_kind: String::new(),
622 vfs_bulk: false,
623 vfs_hidden: false,
624 vfs_mac: String::new(),
625 dispatch_mac: String::new(),
626 dispatch_public: String::new(),
627 mutation_semantics: String::new(),
628 dispatch_mac_present: false,
629 dispatch_public_present: false,
630 mutation_semantics_present: false,
631 }
632 }
633
634 fn empty_struct(name: &str) -> StructDef {
635 StructDef {
636 name: name.into(),
637 fields: vec![],
638 has_union: false,
639 domain_type: None,
640 origin_file: None,
641 data_words: 0,
642 pointer_words: 0,
643 discriminant_count: 0,
644 discriminant_offset: 0,
645 union_arms: vec![],
646 }
647 }
648
649 fn schema_with(request_variants: Vec<UnionVariant>, structs: Vec<StructDef>) -> ParsedSchema {
650 ParsedSchema {
651 request_variants,
652 response_variants: vec![],
653 structs,
654 scoped_clients: vec![],
655 enums: vec![],
656 request_struct: None,
657 response_struct: None,
658 }
659 }
660
661 #[test]
662 fn generates_a_sensible_node_table() {
663 let schema = schema_with(
666 vec![
667 variant("list", "Void", "query"),
668 variant("getByName", "Text", "query"),
669 variant("healthCheck", "Void", "query"),
670 variant("clone", "CloneRequest", "write"),
671 ],
672 vec![empty_struct("CloneRequest")],
673 );
674 let resolved = ResolvedSchema::from(&schema);
675 let out = generate_mount("registry", &resolved).to_string();
676
677 assert!(out.contains("fn vfs_nodes"), "emits vfs_nodes(): {out}");
678 assert!(out.contains("VfsNodeKind :: Dir"), "list is a Dir: {out}");
680 assert!(out.contains("\"{arg}\""), "param file binds {{arg}}: {out}");
682 assert!(out.contains("VfsNodeKind :: Ctl"), "clone is a Ctl: {out}");
684 assert!(out.contains("\"ctl\""), "ctl node path: {out}");
685 assert!(out.contains("\"health_check\""), "health file path: {out}");
687 assert!(!out.contains("compile_error"), "no guard error: {out}");
689 }
690
691 #[test]
692 fn contradiction_emits_compile_error() {
693 let mut bad = variant("clone", "CloneRequest", "write");
695 bad.vfs_kind = "file".into();
696 let schema = schema_with(vec![bad], vec![empty_struct("CloneRequest")]);
697 let resolved = ResolvedSchema::from(&schema);
698 let out = generate_mount("registry", &resolved).to_string();
699
700 assert!(out.contains("compile_error"), "emits compile_error: {out}");
701 assert!(out.contains("clone"), "names the offending method: {out}");
702 }
703
704 #[test]
705 fn vfs_mac_annotation_flows_onto_emitted_node() {
706 let mut health = variant("healthCheck", "Void", "query");
710 health.vfs_mac = "internal:pq-hybrid".into();
711 let mut clone = variant("clone", "CloneRequest", "write");
712 clone.vfs_mac = "secret:pq-hybrid:0".into();
713 let list = variant("list", "Void", "query");
715 let schema = schema_with(
716 vec![health, clone, list],
717 vec![empty_struct("CloneRequest")],
718 );
719 let resolved = ResolvedSchema::from(&schema);
720 let out = generate_mount("registry", &resolved).to_string();
721
722 assert!(
724 out.contains("mac : \"internal:pq-hybrid\""),
725 "health node carries its $vfsMac label: {out}"
726 );
727 assert!(
728 out.contains("mac : \"secret:pq-hybrid:0\""),
729 "clone node carries its $vfsMac label: {out}"
730 );
731 assert!(
733 out.contains("mac : \"\""),
734 "an unannotated node is emitted unlabeled (empty mac): {out}"
735 );
736 }
737
738 #[test]
739 fn vfs_hidden_excludes_a_method() {
740 let mut hidden = variant("internalPing", "Void", "query");
741 hidden.vfs_hidden = true;
742 let schema = schema_with(vec![variant("list", "Void", "query"), hidden], vec![]);
743 let resolved = ResolvedSchema::from(&schema);
744 let out = generate_mount("registry", &resolved).to_string();
745
746 assert!(out.contains("\"list\"") || out.contains("VfsNodeKind :: Dir"));
747 assert!(
748 !out.contains("internal_ping"),
749 "hidden method excluded: {out}"
750 );
751 }
752
753 #[test]
754 fn data_only_schema_emits_no_mount() {
755 let schema = schema_with(vec![], vec![empty_struct("SomeData")]);
756 let resolved = ResolvedSchema::from(&schema);
757 let out = generate_mount("dataonly", &resolved).to_string();
758 assert!(out.is_empty(), "data-only schema has no mount: {out}");
759 }
760
761 #[test]
764 fn multiple_listings_get_distinct_name_derived_paths() {
765 let schema = schema_with(
768 vec![
769 variant("listBranches", "Void", "query"),
770 variant("listTags", "Void", "query"),
771 variant("listRemotes", "Void", "query"),
772 variant("listWorktrees", "Void", "query"),
773 ],
774 vec![],
775 );
776 let resolved = ResolvedSchema::from(&schema);
777 let out = generate_mount("repo", &resolved).to_string();
778
779 assert!(
780 !out.contains("compile_error"),
781 "no collision guard error: {out}"
782 );
783 assert!(out.contains("\"branches\""), "list_ prefix stripped: {out}");
784 assert!(out.contains("\"tags\""), "list_ prefix stripped: {out}");
785 assert!(out.contains("\"remotes\""), "list_ prefix stripped: {out}");
786 assert!(
787 out.contains("\"worktrees\""),
788 "list_ prefix stripped: {out}"
789 );
790 assert!(
792 !out.contains("path : \".\""),
793 "no method landed on the bare root: {out}"
794 );
795 }
796
797 #[test]
798 fn single_listing_still_defaults_to_dot() {
799 let schema = schema_with(vec![variant("list", "Void", "query")], vec![]);
801 let resolved = ResolvedSchema::from(&schema);
802 let out = generate_mount("registry", &resolved).to_string();
803
804 assert!(!out.contains("compile_error"), "no guard error: {out}");
805 assert!(
806 out.contains("path : \".\""),
807 "sole listing is still the scope root: {out}"
808 );
809 }
810
811 #[test]
812 fn explicit_vfs_path_overrides_even_with_multiple_listings() {
813 let mut branches = variant("listBranches", "Void", "query");
819 branches.vfs_path = "custom-branches".into();
820 let mut remotes = variant("listRemotes", "Void", "query");
821 remotes.vfs_path = "custom-remotes".into();
822 let schema = schema_with(
823 vec![branches, remotes, variant("listTags", "Void", "query")],
824 vec![],
825 );
826 let resolved = ResolvedSchema::from(&schema);
827 let out = generate_mount("repo", &resolved).to_string();
828
829 assert!(!out.contains("compile_error"), "no guard error: {out}");
830 assert!(
831 out.contains("\"custom-branches\""),
832 "explicit path wins: {out}"
833 );
834 assert!(
835 out.contains("\"custom-remotes\""),
836 "explicit path wins: {out}"
837 );
838 assert!(
839 out.contains("path : \".\""),
840 "the sole un-annotated listing still gets the root: {out}"
841 );
842 }
843
844 #[test]
845 fn collision_guard_fires_on_same_path() {
846 let mut a = variant("getByName", "Text", "query");
848 a.vfs_path = "dup".into();
849 let mut b = variant("getById", "Text", "query");
850 b.vfs_path = "dup".into();
851 let schema = schema_with(vec![a, b], vec![]);
852 let resolved = ResolvedSchema::from(&schema);
853 let out = generate_mount("registry", &resolved).to_string();
854
855 assert!(
856 out.contains("compile_error"),
857 "collision is a build error: {out}"
858 );
859 assert!(
860 out.contains("get_by_name") && out.contains("get_by_id"),
861 "names both methods: {out}"
862 );
863 assert!(out.contains("dup"), "names the colliding path: {out}");
864 }
865}