#![recursion_limit = "256"]
#![warn(
missing_debug_implementations,
missing_docs,
rust_2018_idioms,
unreachable_pub
)]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/tokio-rs/website/master/public/img/icons/tonic.svg"
)]
#![deny(rustdoc::broken_intra_doc_links)]
#![doc(html_root_url = "https://docs.rs/tonic-build/0.8.4")]
#![doc(issue_tracker_base_url = "https://github.com/hyperium/tonic/issues/")]
#![doc(test(no_crate_inject, attr(deny(rust_2018_idioms))))]
#![cfg_attr(docsrs, feature(doc_cfg))]
use proc_macro2::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream};
use quote::TokenStreamExt;
#[cfg(feature = "prost")]
#[cfg_attr(docsrs, doc(cfg(feature = "prost")))]
mod prost;
#[cfg(feature = "prost")]
#[cfg_attr(docsrs, doc(cfg(feature = "prost")))]
pub use prost::{compile_protos, configure, Builder};
pub mod manual;
pub mod client;
pub mod server;
mod code_gen;
pub use code_gen::CodeGenBuilder;
pub trait Service {
type Comment: AsRef<str>;
type Method: Method;
fn name(&self) -> &str;
fn package(&self) -> &str;
fn identifier(&self) -> &str;
fn methods(&self) -> &[Self::Method];
fn comment(&self) -> &[Self::Comment];
}
pub trait Method {
type Comment: AsRef<str>;
fn name(&self) -> &str;
fn identifier(&self) -> &str;
fn codec_path(&self) -> &str;
fn client_streaming(&self) -> bool;
fn server_streaming(&self) -> bool;
fn comment(&self) -> &[Self::Comment];
fn request_response_name(
&self,
proto_path: &str,
compile_well_known_types: bool,
) -> (TokenStream, TokenStream);
}
#[derive(Debug, Default, Clone)]
pub struct Attributes {
module: Vec<(String, String)>,
structure: Vec<(String, String)>,
}
impl Attributes {
fn for_mod(&self, name: &str) -> Vec<syn::Attribute> {
generate_attributes(name, &self.module)
}
fn for_struct(&self, name: &str) -> Vec<syn::Attribute> {
generate_attributes(name, &self.structure)
}
pub fn push_mod(&mut self, pattern: impl Into<String>, attr: impl Into<String>) {
self.module.push((pattern.into(), attr.into()));
}
pub fn push_struct(&mut self, pattern: impl Into<String>, attr: impl Into<String>) {
self.structure.push((pattern.into(), attr.into()));
}
}
fn generate_attributes<'a>(
name: &str,
attrs: impl IntoIterator<Item = &'a (String, String)>,
) -> Vec<syn::Attribute> {
attrs
.into_iter()
.filter(|(matcher, _)| match_name(matcher, name))
.flat_map(|(_, attr)| {
syn::parse_str::<syn::DeriveInput>(&format!("{}\nstruct fake;", attr))
.unwrap()
.attrs
})
.collect::<Vec<_>>()
}
fn generate_doc_comment<S: AsRef<str>>(comment: S) -> TokenStream {
let comment = comment.as_ref();
let comment = if !comment.starts_with(" ") {
format!(" {}", comment)
} else {
comment.to_string()
};
let mut doc_stream = TokenStream::new();
doc_stream.append(Ident::new("doc", Span::call_site()));
doc_stream.append(Punct::new('=', Spacing::Alone));
doc_stream.append(Literal::string(comment.as_ref()));
let group = Group::new(Delimiter::Bracket, doc_stream);
let mut stream = TokenStream::new();
stream.append(Punct::new('#', Spacing::Alone));
stream.append(group);
stream
}
fn generate_doc_comments<T: AsRef<str>>(comments: &[T]) -> TokenStream {
let mut stream = TokenStream::new();
for comment in comments {
stream.extend(generate_doc_comment(comment));
}
stream
}
pub(crate) fn match_name(pattern: &str, path: &str) -> bool {
if pattern.is_empty() {
false
} else if pattern == "." || pattern == path {
true
} else {
let pattern_segments = pattern.split('.').collect::<Vec<_>>();
let path_segments = path.split('.').collect::<Vec<_>>();
if &pattern[..1] == "." {
if pattern_segments.len() > path_segments.len() {
false
} else {
pattern_segments[..] == path_segments[..pattern_segments.len()]
}
} else if pattern_segments.len() > path_segments.len() {
false
} else {
pattern_segments[..] == path_segments[path_segments.len() - pattern_segments.len()..]
}
}
}
fn naive_snake_case(name: &str) -> String {
let mut s = String::new();
let mut it = name.chars().peekable();
while let Some(x) = it.next() {
s.push(x.to_ascii_lowercase());
if let Some(y) = it.peek() {
if y.is_uppercase() {
s.push('_');
}
}
}
s
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_match_name() {
assert!(match_name(".", ".my.protos"));
assert!(match_name(".", ".protos"));
assert!(match_name(".my", ".my"));
assert!(match_name(".my", ".my.protos"));
assert!(match_name(".my.protos.Service", ".my.protos.Service"));
assert!(match_name("Service", ".my.protos.Service"));
assert!(!match_name(".m", ".my.protos"));
assert!(!match_name(".p", ".protos"));
assert!(!match_name(".my", ".myy"));
assert!(!match_name(".protos", ".my.protos"));
assert!(!match_name(".Service", ".my.protos.Service"));
assert!(!match_name("service", ".my.protos.Service"));
}
#[test]
fn test_snake_case() {
for case in &[
("Service", "service"),
("ThatHasALongName", "that_has_a_long_name"),
("greeter", "greeter"),
("ABCServiceX", "a_b_c_service_x"),
] {
assert_eq!(naive_snake_case(case.0), case.1)
}
}
}