tonneau_build/
extern_paths.rs1use std::collections::BTreeMap;
2
3use quote::ToTokens;
4use syn::parse_quote;
5
6use crate::Mode;
7use crate::codegen::prost_sanatize::to_upper_camel;
8use crate::codegen::utils::{field_ident_from_str, type_ident_from_str};
9use crate::types::ProtoPath;
10
11#[derive(Clone)]
12pub(crate) struct ExternPaths {
13 paths: BTreeMap<ProtoPath, syn::Path>,
14}
15
16impl std::fmt::Debug for ExternPaths {
17 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18 let mut map = f.debug_map();
19
20 for (key, value) in &self.paths {
21 map.key(&key.as_ref());
22 map.value(&value.to_token_stream().to_string());
23 }
24
25 Ok(())
26 }
27}
28
29impl ExternPaths {
30 pub(crate) fn new(mode: Mode) -> Self {
31 let mut paths = BTreeMap::new();
32
33 paths.insert(
34 ProtoPath::new("google.protobuf"),
35 parse_quote!(::tonneau::well_known::#mode),
36 );
37 paths.insert(
38 ProtoPath::new("tonneau"),
39 parse_quote!(::tonneau::well_known::#mode::tonneau),
40 );
41
42 Self { paths }
43 }
44
45 pub(crate) fn resolve(&self, path: &str) -> Option<syn::Path> {
46 if let Some(path) = self.paths.get(path) {
47 return Some(path.clone());
48 }
49
50 for (idx, _) in path.rmatch_indices('.') {
51 if let Some(rust_path) = self.paths.get(&path[..idx]) {
52 let mut segments = path[idx + 1..].split('.');
53 let ident_type = segments
54 .next_back()
55 .map(to_upper_camel)
56 .map(type_ident_from_str);
57 let segments = segments.map(field_ident_from_str).chain(ident_type);
58
59 return Some(parse_quote!(
60 #rust_path::#(#segments)::*
61 ));
62 }
63 }
64
65 None
66 }
67
68 pub(crate) fn contains(&self, path: &str) -> bool {
69 if self.paths.contains_key(path) {
70 return true;
71 }
72
73 for (idx, _) in path.rmatch_indices('.') {
74 if self.paths.contains_key(&path[..idx]) {
75 return true;
76 }
77 }
78
79 false
80 }
81
82 pub(crate) fn paths(&self) -> std::collections::btree_map::Iter<'_, ProtoPath, syn::Path> {
83 self.paths.iter()
84 }
85}