protobuf-codegen-pure-2.27.1/.cargo_vcs_info.json0000644000000001630000000000100153400ustar { "git": { "sha1": "ec31ce829473039ac598ca6fdcb245cbd6fa82ba" }, "path_in_vcs": "protobuf-codegen-pure" }protobuf-codegen-pure-2.27.1/Cargo.lock0000644000000012050000000000100133110ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "protobuf" version = "2.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf7e6d18738ecd0902d30d1ad232c9125985a3422929b16c65517b38adc14f96" [[package]] name = "protobuf-codegen" version = "2.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aec1632b7c8f2e620343439a7dfd1f3c47b18906c4be58982079911482b5d707" dependencies = [ "protobuf", ] [[package]] name = "protobuf-codegen-pure" version = "2.27.1" dependencies = [ "protobuf", "protobuf-codegen", ] protobuf-codegen-pure-2.27.1/Cargo.toml0000644000000021710000000000100133370ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] name = "protobuf-codegen-pure" version = "2.27.1" authors = ["Stepan Koltsov "] description = """ Pure-rust codegen for protobuf using protobuf-parser crate WIP """ homepage = "https://github.com/stepancheg/rust-protobuf/tree/master/protobuf-codegen-pure/" license = "MIT" repository = "https://github.com/stepancheg/rust-protobuf/tree/master/protobuf-codegen-pure/" [package.metadata.docs.rs] all-features = true [lib] doctest = false bench = false [[bin]] name = "parse-and-typecheck" path = "src/bin/parse-and-typecheck.rs" test = false [dependencies.protobuf] version = "=2.27.1" [dependencies.protobuf-codegen] version = "=2.27.1" protobuf-codegen-pure-2.27.1/Cargo.toml.orig000064400000000000000000000013270072674642500170520ustar 00000000000000[package] name = "protobuf-codegen-pure" version = "2.27.1" authors = ["Stepan Koltsov "] license = "MIT" homepage = "https://github.com/stepancheg/rust-protobuf/tree/master/protobuf-codegen-pure/" repository = "https://github.com/stepancheg/rust-protobuf/tree/master/protobuf-codegen-pure/" description = """ Pure-rust codegen for protobuf using protobuf-parser crate WIP """ [lib] doctest = false bench = false [dependencies] protobuf = { path = "../protobuf", version = "=2.27.1" } protobuf-codegen = { path = "../protobuf-codegen", version = "=2.27.1" } [[bin]] name = "parse-and-typecheck" path = "src/bin/parse-and-typecheck.rs" test = false [package.metadata.docs.rs] all-features = true protobuf-codegen-pure-2.27.1/LICENSE.txt000064400000000000000000000020420072674642500160010ustar 00000000000000Copyright (c) 2019 Stepan Koltsov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. protobuf-codegen-pure-2.27.1/README.md000064400000000000000000000017370072674642500154470ustar 00000000000000 # API to generate `.rs` files This API does not require `protoc` command present in `$PATH`. ```rust extern crate protoc_rust; fn main() { protobuf_codegen_pure::Codegen::new() .out_dir("src/protos") .inputs(&["protos/a.proto", "protos/b.proto"]) .include("protos") .run() .expect("Codegen failed."); } ``` And in `Cargo.toml`: ```toml [build-dependencies] protobuf-codegen-pure = "2" ``` It is advisable that `protobuf-codegen-pure` build-dependecy version be the same as `protobuf` dependency. The alternative is to use [`protoc-rust`](https://docs.rs/protoc-rust/=2) crate which uses `protoc` command for parsing (so it uses the same parser Google is using in their protobuf implementations). # Version 2 This is documentation for version 2 of the crate. In version 3, this API is moved to [`protobuf-codegen` crate](https://docs.rs/protobuf-codegen/%3E=3.0.0-alpha). protobuf-codegen-pure-2.27.1/src/bin/parse-and-typecheck.rs000064400000000000000000000013300072674642500217110ustar 00000000000000extern crate protobuf_codegen_pure; use std::env; use std::path::Path; use std::process::exit; fn main() { let args: Vec = env::args().skip(1).collect(); if args.len() != 2 { eprintln!( "usage: {} ", env::args().next().unwrap() ); exit(1); } eprintln!( "{} is not a part of public interface", env::args().next().unwrap() ); let input = vec![Path::new(&args[0][..])]; let includes = vec![Path::new(&args[1][..])]; let t = protobuf_codegen_pure::parse_and_typecheck(&includes, &input).expect("parse_and_typecheck"); for fd in t.file_descriptors { println!("{:#?}", fd); } } protobuf-codegen-pure-2.27.1/src/convert.rs000064400000000000000000000677610072674642500170160ustar 00000000000000//! Convert parser model to rust-protobuf model use std::iter; use model; use protobuf; use protobuf::json::json_name; use protobuf::text_format::lexer::StrLitDecodeError; use protobuf::text_format::quote_bytes_to; use protobuf::Message; use protobuf_codegen::ProtobufAbsolutePath; use protobuf_codegen::ProtobufIdent; use protobuf_codegen::ProtobufRelativePath; use crate::model::FieldOrOneOf; #[derive(Debug)] pub enum ConvertError { UnsupportedOption(String), ExtensionNotFound(String), WrongExtensionType(String, &'static str), UnsupportedExtensionType(String, String), StrLitDecodeError(StrLitDecodeError), DefaultValueIsNotStringLiteral, WrongOptionType, } impl From for ConvertError { fn from(e: StrLitDecodeError) -> Self { ConvertError::StrLitDecodeError(e) } } pub type ConvertResult = Result; trait ProtobufOptions { fn by_name(&self, name: &str) -> Option<&model::ProtobufConstant>; fn by_name_bool(&self, name: &str) -> ConvertResult> { match self.by_name(name) { Some(model::ProtobufConstant::Bool(b)) => Ok(Some(*b)), Some(_) => Err(ConvertError::WrongOptionType), None => Ok(None), } } fn by_name_string(&self, name: &str) -> ConvertResult> { match self.by_name(name) { Some(model::ProtobufConstant::String(s)) => s .decode_utf8() .map(Some) .map_err(ConvertError::StrLitDecodeError), Some(_) => Err(ConvertError::WrongOptionType), None => Ok(None), } } } impl<'a> ProtobufOptions for &'a [model::ProtobufOption] { fn by_name(&self, name: &str) -> Option<&model::ProtobufConstant> { let option_name = name; for model::ProtobufOption { name, value } in *self { if name == option_name { return Some(&value); } } None } } enum MessageOrEnum { Message, Enum, } impl MessageOrEnum { fn descriptor_type(&self) -> protobuf::descriptor::FieldDescriptorProto_Type { match *self { MessageOrEnum::Message => protobuf::descriptor::FieldDescriptorProto_Type::TYPE_MESSAGE, MessageOrEnum::Enum => protobuf::descriptor::FieldDescriptorProto_Type::TYPE_ENUM, } } } enum LookupScope<'a> { File(&'a model::FileDescriptor), Message(&'a model::Message), } impl<'a> LookupScope<'a> { fn messages(&self) -> &[model::Message] { match self { &LookupScope::File(file) => &file.messages, &LookupScope::Message(messasge) => &messasge.messages, } } fn find_message(&self, simple_name: &str) -> Option<&model::Message> { self.messages().into_iter().find(|m| m.name == simple_name) } fn enums(&self) -> &[model::Enumeration] { match self { &LookupScope::File(file) => &file.enums, &LookupScope::Message(messasge) => &messasge.enums, } } fn members(&self) -> Vec<(&str, MessageOrEnum)> { let mut r = Vec::new(); r.extend( self.enums() .into_iter() .map(|e| (&e.name[..], MessageOrEnum::Enum)), ); r.extend( self.messages() .into_iter() .map(|e| (&e.name[..], MessageOrEnum::Message)), ); r } fn find_member(&self, simple_name: &str) -> Option { self.members() .into_iter() .filter_map(|(member_name, message_or_enum)| { if member_name == simple_name { Some(message_or_enum) } else { None } }) .next() } fn resolve_message_or_enum( &self, current_path: &ProtobufAbsolutePath, path: &ProtobufRelativePath, ) -> Option<(ProtobufAbsolutePath, MessageOrEnum)> { let (first, rem) = match path.split_first_rem() { Some(x) => x, None => return None, }; if rem.is_empty() { match self.find_member(first.get()) { Some(message_or_enum) => { let mut result_path = current_path.clone(); result_path.push_simple(first.get().into()); Some((result_path, message_or_enum)) } None => None, } } else { match self.find_message(first.get()) { Some(message) => { let mut message_path = current_path.clone(); message_path.push_simple(message.name.clone().into()); let message_scope = LookupScope::Message(message); message_scope.resolve_message_or_enum(&message_path, &rem) } None => None, } } } } struct Resolver<'a> { current_file: &'a model::FileDescriptor, deps: &'a [model::FileDescriptor], } impl<'a> Resolver<'a> { fn map_entry_name_for_field_name(field_name: &str) -> String { format!("{}_MapEntry", field_name) } fn map_entry_field( &self, name: &str, number: i32, field_type: &model::FieldType, path_in_file: &ProtobufRelativePath, ) -> protobuf::descriptor::FieldDescriptorProto { let mut output = protobuf::descriptor::FieldDescriptorProto::new(); output.set_name(name.to_owned()); output.set_number(number); let (t, t_name) = self.field_type(name, field_type, path_in_file); output.set_field_type(t); if let Some(t_name) = t_name { output.set_type_name(t_name.path); } output.set_json_name(json_name(&name)); output } fn map_entry_message( &self, field_name: &str, key: &model::FieldType, value: &model::FieldType, path_in_file: &ProtobufRelativePath, ) -> ConvertResult { let mut output = protobuf::descriptor::DescriptorProto::new(); output.mut_options().set_map_entry(true); output.set_name(Resolver::map_entry_name_for_field_name(field_name)); output .mut_field() .push(self.map_entry_field("key", 1, key, path_in_file)); output .mut_field() .push(self.map_entry_field("value", 2, value, path_in_file)); Ok(output) } fn group_message( &self, name: &str, fields: &[model::Field], path_in_file: &ProtobufRelativePath, ) -> ConvertResult { let mut output = protobuf::descriptor::DescriptorProto::new(); output.set_name(name.to_owned()); for f in fields { output.field.push(self.field(f, None, path_in_file)?); } Ok(output) } fn message_options( &self, input: &[model::ProtobufOption], ) -> ConvertResult { let mut r = protobuf::descriptor::MessageOptions::new(); self.custom_options( input, "google.protobuf.MessageOptions", r.mut_unknown_fields(), )?; Ok(r) } fn message( &self, input: &model::Message, path_in_file: &ProtobufRelativePath, ) -> ConvertResult { let nested_path_in_file = path_in_file.append(&ProtobufRelativePath::new(input.name.clone())); let mut output = protobuf::descriptor::DescriptorProto::new(); output.set_name(input.name.clone()); let mut nested_messages = protobuf::RepeatedField::new(); for m in &input.messages { nested_messages.push(self.message(m, &nested_path_in_file)?); } for f in input.regular_fields_including_in_oneofs() { match &f.typ { model::FieldType::Map(t) => { nested_messages.push(self.map_entry_message( &f.name, &t.0, &t.1, &nested_path_in_file, )?); } model::FieldType::Group { name, fields } => { nested_messages.push(self.group_message(name, fields, &nested_path_in_file)?); } _ => (), } } output.set_nested_type(nested_messages); output.set_enum_type( input .enums .iter() .map(|e| self.enumeration(e)) .collect::>()?, ); { let mut fields = protobuf::RepeatedField::new(); for fo in &input.fields { match fo { FieldOrOneOf::Field(f) => { fields.push(self.field(f, None, &nested_path_in_file)?); } FieldOrOneOf::OneOf(o) => { let oneof_index = output.oneof_decl.len(); for f in &o.fields { fields.push(self.field( f, Some(oneof_index as i32), &nested_path_in_file, )?); } output.oneof_decl.push(self.oneof(o)); } } } output.set_field(fields); } output.options = Some(self.message_options(&input.options)?).into(); Ok(output) } fn custom_options( &self, input: &[model::ProtobufOption], extendee: &'static str, unknown_fields: &mut protobuf::UnknownFields, ) -> ConvertResult<()> { for option in input { // TODO: builtin options too if !option.name.starts_with('(') { continue; } let extension = match self.find_extension(&option.name) { Ok(e) => e, // TODO: return error Err(_) => continue, }; if extension.extendee != extendee { return Err(ConvertError::WrongExtensionType( option.name.clone(), extendee, )); } let value = match Resolver::option_value_to_unknown_value( &option.value, &extension.field.typ, &option.name, ) { Ok(value) => value, Err(_) => { // TODO: return error continue; } }; unknown_fields.add_value(extension.field.number as u32, value); } Ok(()) } fn field_options( &self, input: &[model::ProtobufOption], ) -> ConvertResult { let mut r = protobuf::descriptor::FieldOptions::new(); if let Some(deprecated) = input.by_name_bool("deprecated")? { r.set_deprecated(deprecated); } if let Some(packed) = input.by_name_bool("packed")? { r.set_packed(packed); } self.custom_options( input, "google.protobuf.FieldOptions", r.mut_unknown_fields(), )?; Ok(r) } fn field( &self, input: &model::Field, oneof_index: Option, path_in_file: &ProtobufRelativePath, ) -> ConvertResult { let mut output = protobuf::descriptor::FieldDescriptorProto::new(); output.set_name(input.name.clone()); if let model::FieldType::Map(..) = input.typ { output.set_label(protobuf::descriptor::FieldDescriptorProto_Label::LABEL_REPEATED); } else { output.set_label(label(input.rule)); } let (t, t_name) = self.field_type(&input.name, &input.typ, path_in_file); output.set_field_type(t); if let Some(t_name) = t_name { output.set_type_name(t_name.path); } output.set_number(input.number); if let Some(default) = input.options.as_slice().by_name("default") { let default = match output.get_field_type() { protobuf::descriptor::FieldDescriptorProto_Type::TYPE_STRING => { if let &model::ProtobufConstant::String(ref s) = default { s.decode_utf8()? } else { return Err(ConvertError::DefaultValueIsNotStringLiteral); } } protobuf::descriptor::FieldDescriptorProto_Type::TYPE_BYTES => { if let &model::ProtobufConstant::String(ref s) = default { let mut buf = String::new(); quote_bytes_to(&s.decode_bytes()?, &mut buf); buf } else { return Err(ConvertError::DefaultValueIsNotStringLiteral); } } _ => default.format(), }; output.set_default_value(default); } output.set_options(self.field_options(&input.options)?); if let Some(oneof_index) = oneof_index { output.set_oneof_index(oneof_index); } if let Some(json_name) = input.options.as_slice().by_name_string("json_name")? { output.set_json_name(json_name); } else { output.set_json_name(json_name(&input.name)); } Ok(output) } fn all_files(&self) -> Vec<&model::FileDescriptor> { iter::once(self.current_file).chain(self.deps).collect() } fn package_files(&self, package: Option<&str>) -> Vec<&model::FileDescriptor> { self.all_files() .into_iter() .filter(|f| f.package.as_deref() == package) .collect() } fn current_file_package_files(&self) -> Vec<&model::FileDescriptor> { self.package_files(self.current_file.package.as_deref()) } fn resolve_message_or_enum( &self, name: &str, path_in_file: &ProtobufRelativePath, ) -> (ProtobufAbsolutePath, MessageOrEnum) { // find message or enum in current package if !name.starts_with(".") { for p in path_in_file.self_and_parents() { let relative_path_with_name = p.clone(); let relative_path_with_name = relative_path_with_name.append(&ProtobufRelativePath::new(name.to_owned())); for file in self.current_file_package_files() { if let Some((n, t)) = LookupScope::File(file).resolve_message_or_enum( &ProtobufAbsolutePath::from_package_path(file.package.as_deref()), &relative_path_with_name, ) { return (n, t); } } } } // find message or enum in root package { let absolute_path = ProtobufAbsolutePath::from_path_maybe_dot(name); for file in self.all_files() { let file_package = ProtobufAbsolutePath::from_package_path(file.package.as_deref()); if let Some(relative) = absolute_path.remove_prefix(&file_package) { if let Some((n, t)) = LookupScope::File(file).resolve_message_or_enum(&file_package, &relative) { return (n, t); } } } } panic!( "couldn't find message or enum {} when parsing {}", name, self.current_file.package.as_deref().unwrap_or("") ); } fn field_type( &self, name: &str, input: &model::FieldType, path_in_file: &ProtobufRelativePath, ) -> ( protobuf::descriptor::FieldDescriptorProto_Type, Option, ) { match *input { model::FieldType::Bool => ( protobuf::descriptor::FieldDescriptorProto_Type::TYPE_BOOL, None, ), model::FieldType::Int32 => ( protobuf::descriptor::FieldDescriptorProto_Type::TYPE_INT32, None, ), model::FieldType::Int64 => ( protobuf::descriptor::FieldDescriptorProto_Type::TYPE_INT64, None, ), model::FieldType::Uint32 => ( protobuf::descriptor::FieldDescriptorProto_Type::TYPE_UINT32, None, ), model::FieldType::Uint64 => ( protobuf::descriptor::FieldDescriptorProto_Type::TYPE_UINT64, None, ), model::FieldType::Sint32 => ( protobuf::descriptor::FieldDescriptorProto_Type::TYPE_SINT32, None, ), model::FieldType::Sint64 => ( protobuf::descriptor::FieldDescriptorProto_Type::TYPE_SINT64, None, ), model::FieldType::Fixed32 => ( protobuf::descriptor::FieldDescriptorProto_Type::TYPE_FIXED32, None, ), model::FieldType::Fixed64 => ( protobuf::descriptor::FieldDescriptorProto_Type::TYPE_FIXED64, None, ), model::FieldType::Sfixed32 => ( protobuf::descriptor::FieldDescriptorProto_Type::TYPE_SFIXED32, None, ), model::FieldType::Sfixed64 => ( protobuf::descriptor::FieldDescriptorProto_Type::TYPE_SFIXED64, None, ), model::FieldType::Float => ( protobuf::descriptor::FieldDescriptorProto_Type::TYPE_FLOAT, None, ), model::FieldType::Double => ( protobuf::descriptor::FieldDescriptorProto_Type::TYPE_DOUBLE, None, ), model::FieldType::String => ( protobuf::descriptor::FieldDescriptorProto_Type::TYPE_STRING, None, ), model::FieldType::Bytes => ( protobuf::descriptor::FieldDescriptorProto_Type::TYPE_BYTES, None, ), model::FieldType::MessageOrEnum(ref name) => { let (name, me) = self.resolve_message_or_enum(&name, path_in_file); (me.descriptor_type(), Some(name)) } model::FieldType::Map(..) => { let mut type_name = ProtobufAbsolutePath::from_package_path(self.current_file.package.as_deref()); type_name.push_relative(path_in_file); type_name.push_simple(Resolver::map_entry_name_for_field_name(name).into()); ( protobuf::descriptor::FieldDescriptorProto_Type::TYPE_MESSAGE, Some(type_name), ) } model::FieldType::Group { ref name, .. } => { let mut type_name = ProtobufAbsolutePath::from_package_path(self.current_file.package.as_deref()); type_name.push_relative(path_in_file); type_name.push_simple(ProtobufIdent::from(name.clone())); ( protobuf::descriptor::FieldDescriptorProto_Type::TYPE_GROUP, Some(type_name), ) } } } fn enum_value( &self, name: &str, number: i32, ) -> protobuf::descriptor::EnumValueDescriptorProto { let mut output = protobuf::descriptor::EnumValueDescriptorProto::new(); output.set_name(name.to_owned()); output.set_number(number); output } fn enum_options( &self, input: &[model::ProtobufOption], ) -> ConvertResult { let mut r = protobuf::descriptor::EnumOptions::new(); if let Some(allow_alias) = input.by_name_bool("allow_alias")? { r.set_allow_alias(allow_alias); } if let Some(deprecated) = input.by_name_bool("deprecated")? { r.set_deprecated(deprecated); } self.custom_options(input, "google.protobuf.EnumOptions", r.mut_unknown_fields())?; Ok(r) } fn enumeration( &self, input: &model::Enumeration, ) -> ConvertResult { let mut output = protobuf::descriptor::EnumDescriptorProto::new(); output.set_name(input.name.clone()); output.set_value( input .values .iter() .map(|v| self.enum_value(&v.name, v.number)) .collect(), ); output.set_options(self.enum_options(&input.options)?); Ok(output) } fn oneof(&self, input: &model::OneOf) -> protobuf::descriptor::OneofDescriptorProto { let mut output = protobuf::descriptor::OneofDescriptorProto::new(); output.set_name(input.name.clone()); output } fn find_extension_by_path(&self, path: &str) -> ConvertResult<&model::Extension> { let (package, name) = match path.rfind('.') { Some(dot) => (Some(&path[..dot]), &path[dot + 1..]), None => (self.current_file.package.as_deref(), path), }; for file in self.package_files(package) { for ext in &file.extensions { if ext.field.name == name { return Ok(ext); } } } Err(ConvertError::ExtensionNotFound(path.to_owned())) } fn find_extension(&self, option_name: &str) -> ConvertResult<&model::Extension> { if !option_name.starts_with('(') || !option_name.ends_with(')') { return Err(ConvertError::UnsupportedOption(option_name.to_owned())); } let path = &option_name[1..option_name.len() - 1]; self.find_extension_by_path(path) } fn option_value_to_unknown_value( value: &model::ProtobufConstant, field_type: &model::FieldType, option_name: &str, ) -> ConvertResult { let v = match value { &model::ProtobufConstant::Bool(b) => { if field_type != &model::FieldType::Bool { Err(()) } else { Ok(protobuf::UnknownValue::Varint(if b { 1 } else { 0 })) } } // TODO: check overflow &model::ProtobufConstant::U64(v) => match field_type { &model::FieldType::Fixed64 | &model::FieldType::Sfixed64 => { Ok(protobuf::UnknownValue::Fixed64(v)) } &model::FieldType::Fixed32 | &model::FieldType::Sfixed32 => { Ok(protobuf::UnknownValue::Fixed32(v as u32)) } &model::FieldType::Int64 | &model::FieldType::Int32 | &model::FieldType::Uint64 | &model::FieldType::Uint32 => Ok(protobuf::UnknownValue::Varint(v)), &model::FieldType::Sint64 => Ok(protobuf::UnknownValue::sint64(v as i64)), &model::FieldType::Sint32 => Ok(protobuf::UnknownValue::sint32(v as i32)), _ => Err(()), }, &model::ProtobufConstant::I64(v) => match field_type { &model::FieldType::Fixed64 | &model::FieldType::Sfixed64 => { Ok(protobuf::UnknownValue::Fixed64(v as u64)) } &model::FieldType::Fixed32 | &model::FieldType::Sfixed32 => { Ok(protobuf::UnknownValue::Fixed32(v as u32)) } &model::FieldType::Int64 | &model::FieldType::Int32 | &model::FieldType::Uint64 | &model::FieldType::Uint32 => Ok(protobuf::UnknownValue::Varint(v as u64)), &model::FieldType::Sint64 => Ok(protobuf::UnknownValue::sint64(v as i64)), &model::FieldType::Sint32 => Ok(protobuf::UnknownValue::sint32(v as i32)), _ => Err(()), }, &model::ProtobufConstant::F64(f) => match field_type { &model::FieldType::Float => { Ok(protobuf::UnknownValue::Fixed32((f as f32).to_bits())) } &model::FieldType::Double => Ok(protobuf::UnknownValue::Fixed64(f.to_bits())), _ => Err(()), }, &model::ProtobufConstant::String(ref s) => { match field_type { &model::FieldType::String => Ok(protobuf::UnknownValue::LengthDelimited( s.decode_utf8()?.into_bytes(), )), // TODO: bytes _ => Err(()), } } _ => Err(()), }; v.map_err(|()| { ConvertError::UnsupportedExtensionType( option_name.to_owned(), format!("{:?}", field_type), ) }) } fn file_options( &self, input: &[model::ProtobufOption], ) -> ConvertResult { let mut r = protobuf::descriptor::FileOptions::new(); self.custom_options(input, "google.protobuf.FileOptions", r.mut_unknown_fields())?; Ok(r) } fn extension( &self, input: &model::Extension, ) -> ConvertResult { let relative_path = ProtobufRelativePath::new("".to_owned()); let mut field = self.field(&input.field, None, &relative_path)?; field.set_extendee( self.resolve_message_or_enum(&input.extendee, &relative_path) .0 .path, ); Ok(field) } } fn syntax(input: model::Syntax) -> String { match input { model::Syntax::Proto2 => "proto2".to_owned(), model::Syntax::Proto3 => "proto3".to_owned(), } } fn label(input: model::Rule) -> protobuf::descriptor::FieldDescriptorProto_Label { match input { model::Rule::Optional => protobuf::descriptor::FieldDescriptorProto_Label::LABEL_OPTIONAL, model::Rule::Required => protobuf::descriptor::FieldDescriptorProto_Label::LABEL_REQUIRED, model::Rule::Repeated => protobuf::descriptor::FieldDescriptorProto_Label::LABEL_REPEATED, } } pub fn file_descriptor( name: String, input: &model::FileDescriptor, deps: &[model::FileDescriptor], ) -> ConvertResult { let resolver = Resolver { current_file: &input, deps, }; let mut output = protobuf::descriptor::FileDescriptorProto::new(); output.set_name(name.to_owned()); output.set_syntax(syntax(input.syntax)); if let Some(package) = &input.package { output.set_package(package.clone()); } for import in &input.imports { if import.vis == model::ImportVis::Public { output .public_dependency .push(output.dependency.len() as i32); } else if import.vis == model::ImportVis::Weak { output.weak_dependency.push(output.dependency.len() as i32); } output.dependency.push(import.path.clone()); } let mut messages = protobuf::RepeatedField::new(); for m in &input.messages { messages.push(resolver.message(&m, &ProtobufRelativePath::empty())?); } output.set_message_type(messages); output.set_enum_type( input .enums .iter() .map(|e| resolver.enumeration(e)) .collect::>()?, ); output.set_options(resolver.file_options(&input.options)?); let mut extensions = protobuf::RepeatedField::new(); for e in &input.extensions { extensions.push(resolver.extension(e)?); } output.set_extension(extensions); Ok(output) } protobuf-codegen-pure-2.27.1/src/lib.rs000064400000000000000000000334540072674642500160740ustar 00000000000000//! # API to generate `.rs` files //! //! This API does not require `protoc` command present in `$PATH`. //! //! ``` //! extern crate protoc_rust; //! //! fn main() { //! protobuf_codegen_pure::Codegen::new() //! .out_dir("src/protos") //! .inputs(&["protos/a.proto", "protos/b.proto"]) //! .include("protos") //! .run() //! .expect("Codegen failed."); //! } //! ``` //! //! And in `Cargo.toml`: //! //! ```toml //! [build-dependencies] //! protobuf-codegen-pure = "2" //! ``` //! //! It is advisable that `protobuf-codegen-pure` build-dependecy version be the same as //! `protobuf` dependency. //! //! The alternative is to use [`protoc-rust`](https://docs.rs/protoc-rust/=2) crate //! which uses `protoc` command for parsing (so it uses the same parser //! Google is using in their protobuf implementations). //! //! # Version 2 //! //! This is documentation for version 2 of the crate. //! //! In version 3, this API is moved to //! [`protobuf-codegen` crate](https://docs.rs/protobuf-codegen/%3E=3.0.0-alpha). #![deny(missing_docs)] #![deny(rustdoc::broken_intra_doc_links)] extern crate protobuf; extern crate protobuf_codegen; mod convert; use std::error::Error; use std::fmt; use std::fmt::Formatter; use std::fs; use std::io; use std::io::Read; use std::path::Path; use std::path::PathBuf; use std::path::StripPrefixError; mod linked_hash_map; mod model; mod parser; use linked_hash_map::LinkedHashMap; pub use protobuf_codegen::Customize; #[cfg(test)] mod test_against_protobuf_protos; /// Invoke pure rust codegen. See [crate docs](crate) for example. // TODO: merge with protoc-rust def #[derive(Debug, Default)] pub struct Codegen { /// --lang_out= param out_dir: PathBuf, /// -I args includes: Vec, /// List of .proto files to compile inputs: Vec, /// Customize code generation customize: Customize, } impl Codegen { /// Fresh new codegen object. pub fn new() -> Self { Self::default() } /// Set the output directory for codegen. pub fn out_dir(&mut self, out_dir: impl AsRef) -> &mut Self { self.out_dir = out_dir.as_ref().to_owned(); self } /// Add an include directory. pub fn include(&mut self, include: impl AsRef) -> &mut Self { self.includes.push(include.as_ref().to_owned()); self } /// Add include directories. pub fn includes(&mut self, includes: impl IntoIterator>) -> &mut Self { for include in includes { self.include(include); } self } /// Add an input (`.proto` file). pub fn input(&mut self, input: impl AsRef) -> &mut Self { self.inputs.push(input.as_ref().to_owned()); self } /// Add inputs (`.proto` files). pub fn inputs(&mut self, inputs: impl IntoIterator>) -> &mut Self { for input in inputs { self.input(input); } self } /// Specify generated code [`Customize`] object. pub fn customize(&mut self, customize: Customize) -> &mut Self { self.customize = customize; self } /// Like `protoc --rust_out=...` but without requiring `protoc` or `protoc-gen-rust` /// commands in `$PATH`. pub fn run(&self) -> io::Result<()> { let includes: Vec<&Path> = self.includes.iter().map(|p| p.as_path()).collect(); let inputs: Vec<&Path> = self.inputs.iter().map(|p| p.as_path()).collect(); let p = parse_and_typecheck(&includes, &inputs)?; protobuf_codegen::gen_and_write( &p.file_descriptors, &p.relative_paths, &self.out_dir, &self.customize, ) } } /// Arguments for pure rust codegen invocation. // TODO: merge with protoc-rust def #[derive(Debug, Default)] #[deprecated(since = "2.14", note = "Use Codegen object instead")] pub struct Args<'a> { /// --lang_out= param pub out_dir: &'a str, /// -I args pub includes: &'a [&'a str], /// List of .proto files to compile pub input: &'a [&'a str], /// Customize code generation pub customize: Customize, } /// Convert OS path to protobuf path (with slashes) /// Function is `pub(crate)` for test. pub(crate) fn relative_path_to_protobuf_path(path: &Path) -> String { assert!(path.is_relative()); let path = path.to_str().expect("not a valid UTF-8 name"); if cfg!(windows) { path.replace('\\', "/") } else { path.to_owned() } } #[derive(Clone)] struct FileDescriptorPair { parsed: model::FileDescriptor, descriptor: protobuf::descriptor::FileDescriptorProto, } #[derive(Debug)] enum CodegenError { ParserErrorWithLocation(parser::ParserErrorWithLocation), ConvertError(convert::ConvertError), } impl fmt::Display for CodegenError { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { CodegenError::ParserErrorWithLocation(_) => write!(f, "Parse error"), CodegenError::ConvertError(_) => write!(f, "Could not typecheck parsed file"), } } } impl From for CodegenError { fn from(e: parser::ParserErrorWithLocation) -> Self { CodegenError::ParserErrorWithLocation(e) } } impl From for CodegenError { fn from(e: convert::ConvertError) -> Self { CodegenError::ConvertError(e) } } #[derive(Debug)] struct WithFileError { file: String, error: CodegenError, } impl fmt::Display for WithFileError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Could not write to {}: {}", self.file, self.error) } } impl Error for WithFileError { fn description(&self) -> &str { "WithFileError" } } struct Run<'a> { parsed_files: LinkedHashMap, includes: &'a [&'a Path], } impl<'a> Run<'a> { fn get_file_and_all_deps_already_parsed( &self, protobuf_path: &str, result: &mut LinkedHashMap, ) { if let Some(_) = result.get(protobuf_path) { return; } let pair = self .parsed_files .get(protobuf_path) .expect("must be already parsed"); result.insert(protobuf_path.to_owned(), pair.clone()); self.get_all_deps_already_parsed(&pair.parsed, result); } fn get_all_deps_already_parsed( &self, parsed: &model::FileDescriptor, result: &mut LinkedHashMap, ) { for import in &parsed.imports { self.get_file_and_all_deps_already_parsed(&import.path, result); } } fn add_file(&mut self, protobuf_path: &str, fs_path: &Path) -> io::Result<()> { if let Some(_) = self.parsed_files.get(protobuf_path) { return Ok(()); } let mut content = String::new(); fs::File::open(fs_path)?.read_to_string(&mut content)?; self.add_file_content(protobuf_path, fs_path, &content) } fn add_file_content( &mut self, protobuf_path: &str, fs_path: &Path, content: &str, ) -> io::Result<()> { let parsed = model::FileDescriptor::parse(content).map_err(|e| { io::Error::new( io::ErrorKind::Other, WithFileError { file: format!("{}", fs_path.display()), error: e.into(), }, ) })?; for import_path in &parsed.imports { self.add_imported_file(&import_path.path)?; } let mut this_file_deps = LinkedHashMap::new(); self.get_all_deps_already_parsed(&parsed, &mut this_file_deps); let this_file_deps: Vec<_> = this_file_deps.into_iter().map(|(_, v)| v.parsed).collect(); let descriptor = convert::file_descriptor(protobuf_path.to_owned(), &parsed, &this_file_deps).map_err( |e| { io::Error::new( io::ErrorKind::Other, WithFileError { file: format!("{}", fs_path.display()), error: e.into(), }, ) }, )?; self.parsed_files.insert( protobuf_path.to_owned(), FileDescriptorPair { parsed, descriptor }, ); Ok(()) } fn add_imported_file(&mut self, protobuf_path: &str) -> io::Result<()> { for include_dir in self.includes { let fs_path = Path::new(include_dir).join(protobuf_path); if fs_path.exists() { return self.add_file(protobuf_path, &fs_path); } } let embedded = match protobuf_path { "rustproto.proto" => Some(RUSTPROTO_PROTO), "google/protobuf/any.proto" => Some(ANY_PROTO), "google/protobuf/api.proto" => Some(API_PROTO), "google/protobuf/descriptor.proto" => Some(DESCRIPTOR_PROTO), "google/protobuf/duration.proto" => Some(DURATION_PROTO), "google/protobuf/empty.proto" => Some(EMPTY_PROTO), "google/protobuf/field_mask.proto" => Some(FIELD_MASK_PROTO), "google/protobuf/source_context.proto" => Some(SOURCE_CONTEXT_PROTO), "google/protobuf/struct.proto" => Some(STRUCT_PROTO), "google/protobuf/timestamp.proto" => Some(TIMESTAMP_PROTO), "google/protobuf/type.proto" => Some(TYPE_PROTO), "google/protobuf/wrappers.proto" => Some(WRAPPERS_PROTO), _ => None, }; match embedded { Some(content) => { self.add_file_content(protobuf_path, Path::new(protobuf_path), content) } None => Err(io::Error::new( io::ErrorKind::Other, format!( "protobuf path {:?} is not found in import path {:?}", protobuf_path, self.includes ), )), } } fn strip_prefix<'b>(path: &'b Path, prefix: &Path) -> Result<&'b Path, StripPrefixError> { // special handling of `.` to allow successful `strip_prefix("foo.proto", ".") if prefix == Path::new(".") { Ok(path) } else { path.strip_prefix(prefix) } } fn add_fs_file(&mut self, fs_path: &Path) -> io::Result { let relative_path = self .includes .iter() .filter_map(|include_dir| Self::strip_prefix(fs_path, include_dir).ok()) .next(); match relative_path { Some(relative_path) => { let protobuf_path = relative_path_to_protobuf_path(relative_path); self.add_file(&protobuf_path, fs_path)?; Ok(protobuf_path) } None => Err(io::Error::new( io::ErrorKind::Other, format!( "file {:?} must reside in include path {:?}", fs_path, self.includes ), )), } } } #[doc(hidden)] pub struct ParsedAndTypechecked { pub relative_paths: Vec, pub file_descriptors: Vec, } #[doc(hidden)] pub fn parse_and_typecheck( includes: &[&Path], input: &[&Path], ) -> io::Result { let mut run = Run { parsed_files: LinkedHashMap::new(), includes: includes, }; let mut relative_paths = Vec::new(); for input in input { relative_paths.push(run.add_fs_file(&Path::new(input))?); } let file_descriptors: Vec<_> = run .parsed_files .into_iter() .map(|(_, v)| v.descriptor) .collect(); Ok(ParsedAndTypechecked { relative_paths, file_descriptors, }) } const RUSTPROTO_PROTO: &str = include_str!("proto/rustproto.proto"); const ANY_PROTO: &str = include_str!("proto/google/protobuf/any.proto"); const API_PROTO: &str = include_str!("proto/google/protobuf/api.proto"); const DESCRIPTOR_PROTO: &str = include_str!("proto/google/protobuf/descriptor.proto"); const DURATION_PROTO: &str = include_str!("proto/google/protobuf/duration.proto"); const EMPTY_PROTO: &str = include_str!("proto/google/protobuf/empty.proto"); const FIELD_MASK_PROTO: &str = include_str!("proto/google/protobuf/field_mask.proto"); const SOURCE_CONTEXT_PROTO: &str = include_str!("proto/google/protobuf/source_context.proto"); const STRUCT_PROTO: &str = include_str!("proto/google/protobuf/struct.proto"); const TIMESTAMP_PROTO: &str = include_str!("proto/google/protobuf/timestamp.proto"); const TYPE_PROTO: &str = include_str!("proto/google/protobuf/type.proto"); const WRAPPERS_PROTO: &str = include_str!("proto/google/protobuf/wrappers.proto"); /// Like `protoc --rust_out=...` but without requiring `protoc` or `protoc-gen-rust` /// commands in `$PATH`. #[deprecated(since = "2.14", note = "Use Codegen instead")] #[allow(deprecated)] pub fn run(args: Args) -> io::Result<()> { let includes: Vec<&Path> = args.includes.iter().map(|p| Path::new(p)).collect(); let inputs: Vec<&Path> = args.input.iter().map(|p| Path::new(p)).collect(); let p = parse_and_typecheck(&includes, &inputs)?; protobuf_codegen::gen_and_write( &p.file_descriptors, &p.relative_paths, &Path::new(&args.out_dir), &args.customize, ) } #[cfg(test)] mod test { use super::*; #[cfg(windows)] #[test] fn test_relative_path_to_protobuf_path_windows() { assert_eq!( "foo/bar.proto", relative_path_to_protobuf_path(&Path::new("foo\\bar.proto")) ); } #[test] fn test_relative_path_to_protobuf_path() { assert_eq!( "foo/bar.proto", relative_path_to_protobuf_path(&Path::new("foo/bar.proto")) ); } } protobuf-codegen-pure-2.27.1/src/linked_hash_map.rs000064400000000000000000001174650072674642500204410ustar 00000000000000// This file is copy-paste from // https://github.com/contain-rs/linked-hash-map/blob/master/src/lib.rs // rev df65b33f8a9dbd06b95b0a6af7521f0d47233545. // to avoid conflicting versions in dependent crates. // Should be used as an external dependency when private dependencies implemented: // https://github.com/rust-lang/rust/issues/44663 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! A `HashMap` wrapper that holds key-value pairs in insertion order. //! //! # Examples //! //! ``` //! use linked_hash_map::LinkedHashMap; //! //! let mut map = LinkedHashMap::new(); //! map.insert(2, 20); //! map.insert(1, 10); //! map.insert(3, 30); //! assert_eq!(map[&1], 10); //! assert_eq!(map[&2], 20); //! assert_eq!(map[&3], 30); //! //! let items: Vec<(i32, i32)> = map.iter().map(|t| (*t.0, *t.1)).collect(); //! assert_eq!(items, [(2, 20), (1, 10), (3, 30)]); //! ``` #![forbid(missing_docs)] #![cfg_attr(all(feature = "nightly", test), feature(test))] #![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #![cfg_attr(feature = "clippy", deny(clippy))] // Optional Serde support // #[cfg(feature = "serde_impl")] // pub mod serde; // Optional Heapsize support // #[cfg(feature = "heapsize_impl")] // mod heapsize; use std::borrow::Borrow; use std::cmp::Ordering; use std::collections::hash_map::HashMap; use std::collections::hash_map::{self}; use std::fmt; use std::hash::BuildHasher; use std::hash::Hash; use std::hash::Hasher; use std::iter; use std::marker; use std::mem; use std::ops::Index; use std::ops::IndexMut; use std::ptr; struct KeyRef { k: *const K, } struct Node { next: *mut Node, prev: *mut Node, key: K, value: V, } /// A linked hash map. pub struct LinkedHashMap { map: HashMap, *mut Node, S>, head: *mut Node, free: *mut Node, } impl Hash for KeyRef { fn hash(&self, state: &mut H) { unsafe { (*self.k).hash(state) } } } impl PartialEq for KeyRef { fn eq(&self, other: &Self) -> bool { unsafe { (*self.k).eq(&*other.k) } } } impl Eq for KeyRef {} // This type exists only to support borrowing `KeyRef`s, which cannot be borrowed to `Q` directly // due to conflicting implementations of `Borrow`. The layout of `&Qey` must be identical to // `&Q` in order to support transmuting in the `Qey::from_ref` method. #[derive(Hash, PartialEq, Eq)] struct Qey(Q); impl Qey { fn from_ref(q: &Q) -> &Self { unsafe { mem::transmute(q) } } } impl Borrow> for KeyRef where K: Borrow, { fn borrow(&self) -> &Qey { Qey::from_ref(unsafe { (*self.k).borrow() }) } } impl Node { fn new(k: K, v: V) -> Self { Node { key: k, value: v, next: ptr::null_mut(), prev: ptr::null_mut(), } } } unsafe fn drop_empty_node(the_box: *mut Node) { // Prevent compiler from trying to drop the un-initialized key and values in the node. let Node { key, value, .. } = *Box::from_raw(the_box); mem::forget(key); mem::forget(value); } impl LinkedHashMap { /// Creates a linked hash map. pub fn new() -> Self { Self::with_map(HashMap::new()) } /// Creates an empty linked hash map with the given initial capacity. pub fn with_capacity(capacity: usize) -> Self { Self::with_map(HashMap::with_capacity(capacity)) } } impl LinkedHashMap { #[inline] fn detach(&mut self, node: *mut Node) { unsafe { (*(*node).prev).next = (*node).next; (*(*node).next).prev = (*node).prev; } } #[inline] fn attach(&mut self, node: *mut Node) { unsafe { (*node).next = (*self.head).next; (*node).prev = self.head; (*self.head).next = node; (*(*node).next).prev = node; } } // Caller must check `!self.head.is_null()` unsafe fn drop_entries(&mut self) { let mut cur = (*self.head).next; while cur != self.head { let next = (*cur).next; Box::from_raw(cur); cur = next; } } fn clear_free_list(&mut self) { unsafe { let mut free = self.free; while !free.is_null() { let next_free = (*free).next; drop_empty_node(free); free = next_free; } self.free = ptr::null_mut(); } } fn ensure_guard_node(&mut self) { if self.head.is_null() { // allocate the guard node if not present unsafe { let node_layout = std::alloc::Layout::new::>(); self.head = std::alloc::alloc(node_layout) as *mut Node; (*self.head).next = self.head; (*self.head).prev = self.head; } } } } impl LinkedHashMap { fn with_map(map: HashMap, *mut Node, S>) -> Self { LinkedHashMap { map: map, head: ptr::null_mut(), free: ptr::null_mut(), } } /// Creates an empty linked hash map with the given initial hash builder. pub fn with_hasher(hash_builder: S) -> Self { Self::with_map(HashMap::with_hasher(hash_builder)) } /// Creates an empty linked hash map with the given initial capacity and hash builder. pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self { Self::with_map(HashMap::with_capacity_and_hasher(capacity, hash_builder)) } /// Reserves capacity for at least `additional` more elements to be inserted into the map. The /// map may reserve more space to avoid frequent allocations. /// /// # Panics /// /// Panics if the new allocation size overflows `usize.` pub fn reserve(&mut self, additional: usize) { self.map.reserve(additional); } /// Shrinks the capacity of the map as much as possible. It will drop down as much as possible /// while maintaining the internal rules and possibly leaving some space in accordance with the /// resize policy. pub fn shrink_to_fit(&mut self) { self.map.shrink_to_fit(); self.clear_free_list(); } /// Gets the given key's corresponding entry in the map for in-place manipulation. /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// /// let mut letters = LinkedHashMap::new(); /// /// for ch in "a short treatise on fungi".chars() { /// let counter = letters.entry(ch).or_insert(0); /// *counter += 1; /// } /// /// assert_eq!(letters[&'s'], 2); /// assert_eq!(letters[&'t'], 3); /// assert_eq!(letters[&'u'], 1); /// assert_eq!(letters.get(&'y'), None); /// ``` pub fn entry(&mut self, k: K) -> Entry { let self_ptr: *mut Self = self; if let Some(entry) = self.map.get_mut(&KeyRef { k: &k }) { return Entry::Occupied(OccupiedEntry { entry: *entry, map: self_ptr, marker: marker::PhantomData, }); } Entry::Vacant(VacantEntry { key: k, map: self }) } /// Returns an iterator visiting all entries in insertion order. /// Iterator element type is `OccupiedEntry`. Allows for removal /// as well as replacing the entry. /// /// # Examples /// ``` /// use linked_hash_map::LinkedHashMap; /// /// let mut map = LinkedHashMap::new(); /// map.insert("a", 10); /// map.insert("c", 30); /// map.insert("b", 20); /// /// { /// let mut iter = map.entries(); /// let mut entry = iter.next().unwrap(); /// assert_eq!(&"a", entry.key()); /// *entry.get_mut() = 17; /// } /// /// assert_eq!(&17, map.get(&"a").unwrap()); /// ``` pub fn entries(&mut self) -> Entries { let head = if !self.head.is_null() { unsafe { (*self.head).prev } } else { ptr::null_mut() }; Entries { map: self, head: head, remaining: self.len(), marker: marker::PhantomData, } } /// Inserts a key-value pair into the map. If the key already existed, the old value is /// returned. /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// let mut map = LinkedHashMap::new(); /// /// map.insert(1, "a"); /// map.insert(2, "b"); /// assert_eq!(map[&1], "a"); /// assert_eq!(map[&2], "b"); /// ``` pub fn insert(&mut self, k: K, v: V) -> Option { self.ensure_guard_node(); let (node, old_val) = match self.map.get(&KeyRef { k: &k }) { Some(node) => { let old_val = unsafe { ptr::replace(&mut (**node).value, v) }; (*node, Some(old_val)) } None => { let node = if self.free.is_null() { Box::into_raw(Box::new(Node::new(k, v))) } else { // use a recycled box unsafe { let free = self.free; self.free = (*free).next; ptr::write(free, Node::new(k, v)); free } }; (node, None) } }; match old_val { Some(_) => { // Existing node, just update LRU position self.detach(node); self.attach(node); } None => { let keyref = unsafe { &(*node).key }; self.map.insert(KeyRef { k: keyref }, node); self.attach(node); } } old_val } /// Checks if the map contains the given key. pub fn contains_key(&self, k: &Q) -> bool where K: Borrow, Q: Eq + Hash, { self.map.contains_key(Qey::from_ref(k)) } /// Returns the value corresponding to the key in the map. /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// let mut map = LinkedHashMap::new(); /// /// map.insert(1, "a"); /// map.insert(2, "b"); /// map.insert(2, "c"); /// map.insert(3, "d"); /// /// assert_eq!(map.get(&1), Some(&"a")); /// assert_eq!(map.get(&2), Some(&"c")); /// ``` pub fn get(&self, k: &Q) -> Option<&V> where K: Borrow, Q: Eq + Hash, { self.map .get(Qey::from_ref(k)) .map(|e| unsafe { &(**e).value }) } /// Returns the mutable reference corresponding to the key in the map. /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// let mut map = LinkedHashMap::new(); /// /// map.insert(1, "a"); /// map.insert(2, "b"); /// /// *map.get_mut(&1).unwrap() = "c"; /// assert_eq!(map.get(&1), Some(&"c")); /// ``` pub fn get_mut(&mut self, k: &Q) -> Option<&mut V> where K: Borrow, Q: Eq + Hash, { self.map .get(Qey::from_ref(k)) .map(|e| unsafe { &mut (**e).value }) } /// Returns the value corresponding to the key in the map. /// /// If value is found, it is moved to the end of the list. /// This operation can be used in implemenation of LRU cache. /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// let mut map = LinkedHashMap::new(); /// /// map.insert(1, "a"); /// map.insert(2, "b"); /// map.insert(3, "d"); /// /// assert_eq!(map.get_refresh(&2), Some(&mut "b")); /// /// assert_eq!((&2, &"b"), map.iter().rev().next().unwrap()); /// ``` pub fn get_refresh(&mut self, k: &Q) -> Option<&mut V> where K: Borrow, Q: Eq + Hash, { let (value, node_ptr_opt) = match self.map.get(Qey::from_ref(k)) { None => (None, None), Some(node) => (Some(unsafe { &mut (**node).value }), Some(*node)), }; if let Some(node_ptr) = node_ptr_opt { self.detach(node_ptr); self.attach(node_ptr); } value } /// Removes and returns the value corresponding to the key from the map. /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// let mut map = LinkedHashMap::new(); /// /// map.insert(2, "a"); /// /// assert_eq!(map.remove(&1), None); /// assert_eq!(map.remove(&2), Some("a")); /// assert_eq!(map.remove(&2), None); /// assert_eq!(map.len(), 0); /// ``` pub fn remove(&mut self, k: &Q) -> Option where K: Borrow, Q: Eq + Hash, { let removed = self.map.remove(Qey::from_ref(k)); removed.map(|node| { self.detach(node); unsafe { // add to free list (*node).next = self.free; self.free = node; // drop the key and return the value drop(ptr::read(&(*node).key)); ptr::read(&(*node).value) } }) } /// Returns the maximum number of key-value pairs the map can hold without reallocating. /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// let mut map: LinkedHashMap = LinkedHashMap::new(); /// let capacity = map.capacity(); /// ``` pub fn capacity(&self) -> usize { self.map.capacity() } /// Removes the first entry. /// /// Can be used in implementation of LRU cache. /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// let mut map = LinkedHashMap::new(); /// map.insert(1, 10); /// map.insert(2, 20); /// map.pop_front(); /// assert_eq!(map.get(&1), None); /// assert_eq!(map.get(&2), Some(&20)); /// ``` #[inline] pub fn pop_front(&mut self) -> Option<(K, V)> { if self.is_empty() { return None; } let lru = unsafe { (*self.head).prev }; self.detach(lru); self.map .remove(&KeyRef { k: unsafe { &(*lru).key }, }) .map(|e| { let e = *unsafe { Box::from_raw(e) }; (e.key, e.value) }) } /// Gets the first entry. /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// let mut map = LinkedHashMap::new(); /// map.insert(1, 10); /// map.insert(2, 20); /// assert_eq!(map.front(), Some((&1, &10))); /// ``` #[inline] pub fn front(&self) -> Option<(&K, &V)> { if self.is_empty() { return None; } let lru = unsafe { (*self.head).prev }; self.map .get(&KeyRef { k: unsafe { &(*lru).key }, }) .map(|e| unsafe { (&(**e).key, &(**e).value) }) } /// Removes the last entry. /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// let mut map = LinkedHashMap::new(); /// map.insert(1, 10); /// map.insert(2, 20); /// map.pop_back(); /// assert_eq!(map.get(&1), Some(&10)); /// assert_eq!(map.get(&2), None); /// ``` #[inline] pub fn pop_back(&mut self) -> Option<(K, V)> { if self.is_empty() { return None; } let mru = unsafe { (*self.head).next }; self.detach(mru); self.map .remove(&KeyRef { k: unsafe { &(*mru).key }, }) .map(|e| { let e = *unsafe { Box::from_raw(e) }; (e.key, e.value) }) } /// Gets the last entry. /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// let mut map = LinkedHashMap::new(); /// map.insert(1, 10); /// map.insert(2, 20); /// assert_eq!(map.back(), Some((&2, &20))); /// ``` #[inline] pub fn back(&mut self) -> Option<(&K, &V)> { if self.is_empty() { return None; } let mru = unsafe { (*self.head).next }; self.map .get(&KeyRef { k: unsafe { &(*mru).key }, }) .map(|e| unsafe { (&(**e).key, &(**e).value) }) } /// Returns the number of key-value pairs in the map. pub fn len(&self) -> usize { self.map.len() } /// Returns whether the map is currently empty. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Returns a reference to the map's hasher. pub fn hasher(&self) -> &S { self.map.hasher() } /// Clears the map of all key-value pairs. pub fn clear(&mut self) { self.map.clear(); // update the guard node if present if !self.head.is_null() { unsafe { self.drop_entries(); (*self.head).prev = self.head; (*self.head).next = self.head; } } } /// Returns a double-ended iterator visiting all key-value pairs in order of insertion. /// Iterator element type is `(&'a K, &'a V)` /// /// # Examples /// ``` /// use linked_hash_map::LinkedHashMap; /// /// let mut map = LinkedHashMap::new(); /// map.insert("a", 10); /// map.insert("c", 30); /// map.insert("b", 20); /// /// let mut iter = map.iter(); /// assert_eq!((&"a", &10), iter.next().unwrap()); /// assert_eq!((&"c", &30), iter.next().unwrap()); /// assert_eq!((&"b", &20), iter.next().unwrap()); /// assert_eq!(None, iter.next()); /// ``` pub fn iter(&self) -> Iter { let head = if self.head.is_null() { ptr::null_mut() } else { unsafe { (*self.head).prev } }; Iter { head: head, tail: self.head, remaining: self.len(), marker: marker::PhantomData, } } /// Returns a double-ended iterator visiting all key-value pairs in order of insertion. /// Iterator element type is `(&'a K, &'a mut V)` /// # Examples /// ``` /// use linked_hash_map::LinkedHashMap; /// /// let mut map = LinkedHashMap::new(); /// map.insert("a", 10); /// map.insert("c", 30); /// map.insert("b", 20); /// /// { /// let mut iter = map.iter_mut(); /// let mut entry = iter.next().unwrap(); /// assert_eq!(&"a", entry.0); /// *entry.1 = 17; /// } /// /// assert_eq!(&17, map.get(&"a").unwrap()); /// ``` pub fn iter_mut(&mut self) -> IterMut { let head = if self.head.is_null() { ptr::null_mut() } else { unsafe { (*self.head).prev } }; IterMut { head: head, tail: self.head, remaining: self.len(), marker: marker::PhantomData, } } /// Returns a double-ended iterator visiting all key in order of insertion. /// /// # Examples /// ``` /// use linked_hash_map::LinkedHashMap; /// /// let mut map = LinkedHashMap::new(); /// map.insert('a', 10); /// map.insert('c', 30); /// map.insert('b', 20); /// /// let mut keys = map.keys(); /// assert_eq!(&'a', keys.next().unwrap()); /// assert_eq!(&'c', keys.next().unwrap()); /// assert_eq!(&'b', keys.next().unwrap()); /// assert_eq!(None, keys.next()); /// ``` pub fn keys(&self) -> Keys { Keys { inner: self.iter() } } /// Returns a double-ended iterator visiting all values in order of insertion. /// /// # Examples /// ``` /// use linked_hash_map::LinkedHashMap; /// /// let mut map = LinkedHashMap::new(); /// map.insert('a', 10); /// map.insert('c', 30); /// map.insert('b', 20); /// /// let mut values = map.values(); /// assert_eq!(&10, values.next().unwrap()); /// assert_eq!(&30, values.next().unwrap()); /// assert_eq!(&20, values.next().unwrap()); /// assert_eq!(None, values.next()); /// ``` pub fn values(&self) -> Values { Values { inner: self.iter() } } } impl<'a, K, V, S, Q: ?Sized> Index<&'a Q> for LinkedHashMap where K: Hash + Eq + Borrow, S: BuildHasher, Q: Eq + Hash, { type Output = V; fn index(&self, index: &'a Q) -> &V { self.get(index).expect("no entry found for key") } } impl<'a, K, V, S, Q: ?Sized> IndexMut<&'a Q> for LinkedHashMap where K: Hash + Eq + Borrow, S: BuildHasher, Q: Eq + Hash, { fn index_mut(&mut self, index: &'a Q) -> &mut V { self.get_mut(index).expect("no entry found for key") } } impl Clone for LinkedHashMap { fn clone(&self) -> Self { let mut map = Self::with_hasher(self.map.hasher().clone()); map.extend(self.iter().map(|(k, v)| (k.clone(), v.clone()))); map } } impl Default for LinkedHashMap { fn default() -> Self { Self::with_hasher(S::default()) } } impl Extend<(K, V)> for LinkedHashMap { fn extend>(&mut self, iter: I) { for (k, v) in iter { self.insert(k, v); } } } impl<'a, K, V, S> Extend<(&'a K, &'a V)> for LinkedHashMap where K: 'a + Hash + Eq + Copy, V: 'a + Copy, S: BuildHasher, { fn extend>(&mut self, iter: I) { for (&k, &v) in iter { self.insert(k, v); } } } impl iter::FromIterator<(K, V)> for LinkedHashMap { fn from_iter>(iter: I) -> Self { let iter = iter.into_iter(); let mut map = Self::with_capacity_and_hasher(iter.size_hint().0, S::default()); map.extend(iter); map } } impl fmt::Debug for LinkedHashMap { /// Returns a string that lists the key-value pairs in insertion order. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_map().entries(self).finish() } } impl PartialEq for LinkedHashMap { fn eq(&self, other: &Self) -> bool { self.len() == other.len() && self.iter().eq(other) } } impl Eq for LinkedHashMap {} impl PartialOrd for LinkedHashMap { fn partial_cmp(&self, other: &Self) -> Option { self.iter().partial_cmp(other) } fn lt(&self, other: &Self) -> bool { self.iter().lt(other) } fn le(&self, other: &Self) -> bool { self.iter().le(other) } fn ge(&self, other: &Self) -> bool { self.iter().ge(other) } fn gt(&self, other: &Self) -> bool { self.iter().gt(other) } } impl Ord for LinkedHashMap { fn cmp(&self, other: &Self) -> Ordering { self.iter().cmp(other) } } impl Hash for LinkedHashMap { fn hash(&self, h: &mut H) { for e in self.iter() { e.hash(h); } } } unsafe impl Send for LinkedHashMap {} unsafe impl Sync for LinkedHashMap {} impl Drop for LinkedHashMap { fn drop(&mut self) { if !self.head.is_null() { unsafe { self.drop_entries(); drop_empty_node(self.head); } } self.clear_free_list(); } } /// An insertion-order iterator over a `LinkedHashMap`'s entries, with immutable references to the /// values. pub struct Iter<'a, K: 'a, V: 'a> { head: *const Node, tail: *const Node, remaining: usize, marker: marker::PhantomData<(&'a K, &'a V)>, } /// An insertion-order iterator over a `LinkedHashMap`'s entries, with mutable references to the /// values. pub struct IterMut<'a, K: 'a, V: 'a> { head: *mut Node, tail: *mut Node, remaining: usize, marker: marker::PhantomData<(&'a K, &'a mut V)>, } /// A consuming insertion-order iterator over a `LinkedHashMap`'s entries. pub struct IntoIter { head: *mut Node, tail: *mut Node, remaining: usize, marker: marker::PhantomData<(K, V)>, } /// An insertion-order iterator over a `LinkedHashMap`'s entries represented as /// an `OccupiedEntry`. pub struct Entries<'a, K: 'a, V: 'a, S: 'a = hash_map::RandomState> { map: *mut LinkedHashMap, head: *mut Node, remaining: usize, marker: marker::PhantomData<(&'a K, &'a mut V, &'a S)>, } unsafe impl<'a, K, V> Send for Iter<'a, K, V> where K: Send, V: Send, { } unsafe impl<'a, K, V> Send for IterMut<'a, K, V> where K: Send, V: Send, { } unsafe impl Send for IntoIter where K: Send, V: Send, { } unsafe impl<'a, K, V, S> Send for Entries<'a, K, V, S> where K: Send, V: Send, S: Send, { } unsafe impl<'a, K, V> Sync for Iter<'a, K, V> where K: Sync, V: Sync, { } unsafe impl<'a, K, V> Sync for IterMut<'a, K, V> where K: Sync, V: Sync, { } unsafe impl Sync for IntoIter where K: Sync, V: Sync, { } unsafe impl<'a, K, V, S> Sync for Entries<'a, K, V, S> where K: Sync, V: Sync, S: Sync, { } impl<'a, K, V> Clone for Iter<'a, K, V> { fn clone(&self) -> Self { Iter { ..*self } } } impl Clone for IntoIter where K: Clone, V: Clone, { fn clone(&self) -> Self { if self.remaining == 0 { return IntoIter { ..*self }; } fn clone_node(e: *mut Node) -> *mut Node where K: Clone, V: Clone, { Box::into_raw(Box::new(Node::new(unsafe { (*e).key.clone() }, unsafe { (*e).value.clone() }))) } let mut cur = self.head; let head = clone_node(cur); let mut tail = head; for _ in 1..self.remaining { unsafe { (*tail).prev = clone_node((*cur).prev); (*(*tail).prev).next = tail; tail = (*tail).prev; cur = (*cur).prev; } } IntoIter { head: head, tail: tail, remaining: self.remaining, marker: marker::PhantomData, } } } impl<'a, K, V> Iterator for Iter<'a, K, V> { type Item = (&'a K, &'a V); fn next(&mut self) -> Option<(&'a K, &'a V)> { if self.head == self.tail { None } else { self.remaining -= 1; unsafe { let r = Some((&(*self.head).key, &(*self.head).value)); self.head = (*self.head).prev; r } } } fn size_hint(&self) -> (usize, Option) { (self.remaining, Some(self.remaining)) } } impl<'a, K, V> Iterator for IterMut<'a, K, V> { type Item = (&'a K, &'a mut V); fn next(&mut self) -> Option<(&'a K, &'a mut V)> { if self.head == self.tail { None } else { self.remaining -= 1; unsafe { let r = Some((&(*self.head).key, &mut (*self.head).value)); self.head = (*self.head).prev; r } } } fn size_hint(&self) -> (usize, Option) { (self.remaining, Some(self.remaining)) } } impl Iterator for IntoIter { type Item = (K, V); fn next(&mut self) -> Option<(K, V)> { if self.remaining == 0 { return None; } self.remaining -= 1; unsafe { let prev = (*self.head).prev; let e = *Box::from_raw(self.head); self.head = prev; Some((e.key, e.value)) } } fn size_hint(&self) -> (usize, Option) { (self.remaining, Some(self.remaining)) } } impl<'a, K, V, S: BuildHasher> Iterator for Entries<'a, K, V, S> { type Item = OccupiedEntry<'a, K, V, S>; fn next(&mut self) -> Option> { if self.remaining == 0 { None } else { self.remaining -= 1; unsafe { let r = Some(OccupiedEntry { map: self.map, entry: self.head, marker: marker::PhantomData, }); self.head = (*self.head).prev; r } } } fn size_hint(&self) -> (usize, Option) { (self.remaining, Some(self.remaining)) } } impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V> { fn next_back(&mut self) -> Option<(&'a K, &'a V)> { if self.head == self.tail { None } else { self.remaining -= 1; unsafe { self.tail = (*self.tail).next; Some((&(*self.tail).key, &(*self.tail).value)) } } } } impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> { fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> { if self.head == self.tail { None } else { self.remaining -= 1; unsafe { self.tail = (*self.tail).next; Some((&(*self.tail).key, &mut (*self.tail).value)) } } } } impl DoubleEndedIterator for IntoIter { fn next_back(&mut self) -> Option<(K, V)> { if self.remaining == 0 { return None; } self.remaining -= 1; unsafe { let next = (*self.tail).next; let e = *Box::from_raw(self.tail); self.tail = next; Some((e.key, e.value)) } } } impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> { fn len(&self) -> usize { self.remaining } } impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> { fn len(&self) -> usize { self.remaining } } impl ExactSizeIterator for IntoIter { fn len(&self) -> usize { self.remaining } } impl Drop for IntoIter { fn drop(&mut self) { for _ in 0..self.remaining { unsafe { let next = (*self.tail).next; Box::from_raw(self.tail); self.tail = next; } } } } /// An insertion-order iterator over a `LinkedHashMap`'s keys. pub struct Keys<'a, K: 'a, V: 'a> { inner: Iter<'a, K, V>, } impl<'a, K, V> Clone for Keys<'a, K, V> { fn clone(&self) -> Self { Keys { inner: self.inner.clone(), } } } impl<'a, K, V> Iterator for Keys<'a, K, V> { type Item = &'a K; #[inline] fn next(&mut self) -> Option<&'a K> { self.inner.next().map(|e| e.0) } #[inline] fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> { #[inline] fn next_back(&mut self) -> Option<&'a K> { self.inner.next_back().map(|e| e.0) } } impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> { fn len(&self) -> usize { self.inner.len() } } /// An insertion-order iterator over a `LinkedHashMap`'s values. pub struct Values<'a, K: 'a, V: 'a> { inner: Iter<'a, K, V>, } impl<'a, K, V> Clone for Values<'a, K, V> { fn clone(&self) -> Self { Values { inner: self.inner.clone(), } } } impl<'a, K, V> Iterator for Values<'a, K, V> { type Item = &'a V; #[inline] fn next(&mut self) -> Option<&'a V> { self.inner.next().map(|e| e.1) } #[inline] fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } } impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> { #[inline] fn next_back(&mut self) -> Option<&'a V> { self.inner.next_back().map(|e| e.1) } } impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> { fn len(&self) -> usize { self.inner.len() } } impl<'a, K: Hash + Eq, V, S: BuildHasher> IntoIterator for &'a LinkedHashMap { type Item = (&'a K, &'a V); type IntoIter = Iter<'a, K, V>; fn into_iter(self) -> Iter<'a, K, V> { self.iter() } } impl<'a, K: Hash + Eq, V, S: BuildHasher> IntoIterator for &'a mut LinkedHashMap { type Item = (&'a K, &'a mut V); type IntoIter = IterMut<'a, K, V>; fn into_iter(self) -> IterMut<'a, K, V> { self.iter_mut() } } impl IntoIterator for LinkedHashMap { type Item = (K, V); type IntoIter = IntoIter; fn into_iter(mut self) -> IntoIter { let (head, tail) = if !self.head.is_null() { unsafe { ((*self.head).prev, (*self.head).next) } } else { (ptr::null_mut(), ptr::null_mut()) }; let len = self.len(); if !self.head.is_null() { unsafe { drop_empty_node(self.head) } } self.clear_free_list(); // drop the HashMap but not the LinkedHashMap unsafe { ptr::drop_in_place(&mut self.map); } mem::forget(self); IntoIter { head: head, tail: tail, remaining: len, marker: marker::PhantomData, } } } /// A view into a single location in a map, which may be vacant or occupied. pub enum Entry<'a, K: 'a, V: 'a, S: 'a = hash_map::RandomState> { /// An occupied Entry. Occupied(OccupiedEntry<'a, K, V, S>), /// A vacant Entry. Vacant(VacantEntry<'a, K, V, S>), } /// A view into a single occupied location in a `LinkedHashMap`. pub struct OccupiedEntry<'a, K: 'a, V: 'a, S: 'a = hash_map::RandomState> { entry: *mut Node, map: *mut LinkedHashMap, marker: marker::PhantomData<&'a K>, } /// A view into a single empty location in a `LinkedHashMap`. pub struct VacantEntry<'a, K: 'a, V: 'a, S: 'a = hash_map::RandomState> { key: K, map: &'a mut LinkedHashMap, } impl<'a, K: Hash + Eq, V, S: BuildHasher> Entry<'a, K, V, S> { /// Returns the entry key /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// /// let mut map = LinkedHashMap::::new(); /// /// assert_eq!("hello", map.entry("hello".to_string()).key()); /// ``` pub fn key(&self) -> &K { match *self { Entry::Occupied(ref e) => e.key(), Entry::Vacant(ref e) => e.key(), } } /// Ensures a value is in the entry by inserting the default if empty, and returns /// a mutable reference to the value in the entry. pub fn or_insert(self, default: V) -> &'a mut V { match self { Entry::Occupied(entry) => entry.into_mut(), Entry::Vacant(entry) => entry.insert(default), } } /// Ensures a value is in the entry by inserting the result of the default function if empty, /// and returns a mutable reference to the value in the entry. pub fn or_insert_with V>(self, default: F) -> &'a mut V { match self { Entry::Occupied(entry) => entry.into_mut(), Entry::Vacant(entry) => entry.insert(default()), } } } impl<'a, K: Hash + Eq, V, S: BuildHasher> OccupiedEntry<'a, K, V, S> { /// Gets a reference to the entry key /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// /// let mut map = LinkedHashMap::new(); /// /// map.insert("foo".to_string(), 1); /// assert_eq!("foo", map.entry("foo".to_string()).key()); /// ``` pub fn key(&self) -> &K { unsafe { &(*self.entry).key } } /// Gets a reference to the value in the entry. pub fn get(&self) -> &V { unsafe { &(*self.entry).value } } /// Gets a mutable reference to the value in the entry. pub fn get_mut(&mut self) -> &mut V { unsafe { &mut (*self.entry).value } } /// Converts the OccupiedEntry into a mutable reference to the value in the entry /// with a lifetime bound to the map itself pub fn into_mut(self) -> &'a mut V { unsafe { &mut (*self.entry).value } } /// Sets the value of the entry, and returns the entry's old value pub fn insert(&mut self, value: V) -> V { unsafe { (*self.map).ensure_guard_node(); let old_val = mem::replace(&mut (*self.entry).value, value); let node_ptr: *mut Node = self.entry; // Existing node, just update LRU position (*self.map).detach(node_ptr); (*self.map).attach(node_ptr); old_val } } /// Takes the value out of the entry, and returns it pub fn remove(self) -> V { unsafe { (*self.map).remove(&(*self.entry).key) }.unwrap() } } impl<'a, K: 'a + Hash + Eq, V: 'a, S: BuildHasher> VacantEntry<'a, K, V, S> { /// Gets a reference to the entry key /// /// # Examples /// /// ``` /// use linked_hash_map::LinkedHashMap; /// /// let mut map = LinkedHashMap::::new(); /// /// assert_eq!("foo", map.entry("foo".to_string()).key()); /// ``` pub fn key(&self) -> &K { &self.key } /// Sets the value of the entry with the VacantEntry's key, /// and returns a mutable reference to it pub fn insert(self, value: V) -> &'a mut V { self.map.ensure_guard_node(); let node = if self.map.free.is_null() { Box::into_raw(Box::new(Node::new(self.key, value))) } else { // use a recycled box unsafe { let free = self.map.free; self.map.free = (*free).next; ptr::write(free, Node::new(self.key, value)); free } }; let keyref = unsafe { &(*node).key }; self.map.attach(node); let ret = self.map.map.entry(KeyRef { k: keyref }).or_insert(node); unsafe { &mut (**ret).value } } } #[cfg(all(feature = "nightly", test))] mod bench { extern crate test; use super::LinkedHashMap; #[bench] fn not_recycled_cycling(b: &mut test::Bencher) { let mut hash_map = LinkedHashMap::with_capacity(1000); for i in 0usize..1000 { hash_map.insert(i, i); } b.iter(|| { for i in 0usize..1000 { hash_map.remove(&i); } hash_map.clear_free_list(); for i in 0usize..1000 { hash_map.insert(i, i); } }) } #[bench] fn recycled_cycling(b: &mut test::Bencher) { let mut hash_map = LinkedHashMap::with_capacity(1000); for i in 0usize..1000 { hash_map.insert(i, i); } b.iter(|| { for i in 0usize..1000 { hash_map.remove(&i); } for i in 0usize..1000 { hash_map.insert(i, i); } }) } } protobuf-codegen-pure-2.27.1/src/model.rs000064400000000000000000000204770072674642500164270ustar 00000000000000//! A nom-based protobuf file parser //! //! This crate can be seen as a rust transcription of the //! [descriptor.proto](https://github.com/google/protobuf/blob/master/src/google/protobuf/descriptor.proto) file use parser::Loc; use parser::Parser; pub use parser::ParserError; pub use parser::ParserErrorWithLocation; use protobuf::text_format::lexer::StrLit; use protobuf_codegen::float; /// Protobox syntax #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum Syntax { /// Protobuf syntax [2](https://developers.google.com/protocol-buffers/docs/proto) (default) Proto2, /// Protobuf syntax [3](https://developers.google.com/protocol-buffers/docs/proto3) Proto3, } impl Default for Syntax { fn default() -> Syntax { Syntax::Proto2 } } /// A field rule #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] pub enum Rule { /// A well-formed message can have zero or one of this field (but not more than one). Optional, /// This field can be repeated any number of times (including zero) in a well-formed message. /// The order of the repeated values will be preserved. Repeated, /// A well-formed message must have exactly one of this field. Required, } /// Protobuf supported field types #[derive(Debug, Clone, PartialEq)] pub enum FieldType { /// Protobuf int32 /// /// # Remarks /// /// Uses variable-length encoding. Inefficient for encoding negative numbers – if /// your field is likely to have negative values, use sint32 instead. Int32, /// Protobuf int64 /// /// # Remarks /// /// Uses variable-length encoding. Inefficient for encoding negative numbers – if /// your field is likely to have negative values, use sint64 instead. Int64, /// Protobuf uint32 /// /// # Remarks /// /// Uses variable-length encoding. Uint32, /// Protobuf uint64 /// /// # Remarks /// /// Uses variable-length encoding. Uint64, /// Protobuf sint32 /// /// # Remarks /// /// Uses ZigZag variable-length encoding. Signed int value. These more efficiently /// encode negative numbers than regular int32s. Sint32, /// Protobuf sint64 /// /// # Remarks /// /// Uses ZigZag variable-length encoding. Signed int value. These more efficiently /// encode negative numbers than regular int32s. Sint64, /// Protobuf bool Bool, /// Protobuf fixed64 /// /// # Remarks /// /// Always eight bytes. More efficient than uint64 if values are often greater than 2^56. Fixed64, /// Protobuf sfixed64 /// /// # Remarks /// /// Always eight bytes. Sfixed64, /// Protobuf double Double, /// Protobuf string /// /// # Remarks /// /// A string must always contain UTF-8 encoded or 7-bit ASCII text. String, /// Protobuf bytes /// /// # Remarks /// /// May contain any arbitrary sequence of bytes. Bytes, /// Protobut fixed32 /// /// # Remarks /// /// Always four bytes. More efficient than uint32 if values are often greater than 2^28. Fixed32, /// Protobut sfixed32 /// /// # Remarks /// /// Always four bytes. Sfixed32, /// Protobut float Float, /// Protobuf message or enum (holds the name) MessageOrEnum(String), /// Protobut map Map(Box<(FieldType, FieldType)>), /// Protobuf group (deprecated) Group { name: String, fields: Vec }, } /// A Protobuf Field #[derive(Debug, Clone, PartialEq)] pub struct Field { /// Field name pub name: String, /// Field `Rule` pub rule: Rule, /// Field type pub typ: FieldType, /// Tag number pub number: i32, /// Non-builtin options pub options: Vec, } /// A Protobuf field of oneof group #[derive(Debug, Clone, PartialEq)] pub enum FieldOrOneOf { Field(Field), OneOf(OneOf), } /// Extension range #[derive(Default, Debug, Eq, PartialEq, Copy, Clone)] pub struct FieldNumberRange { /// First number pub from: i32, /// Inclusive pub to: i32, } /// A protobuf message #[derive(Debug, Clone, Default)] pub struct Message { /// Message name pub name: String, /// Message fields and oneofs pub fields: Vec, /// Message reserved numbers /// /// TODO: use RangeInclusive once stable pub reserved_nums: Vec, /// Message reserved names pub reserved_names: Vec, /// Nested messages pub messages: Vec, /// Nested enums pub enums: Vec, /// Non-builtin options pub options: Vec, } impl Message { pub fn regular_fields_including_in_oneofs(&self) -> Vec<&Field> { self.fields .iter() .flat_map(|fo| match fo { FieldOrOneOf::Field(f) => vec![f], FieldOrOneOf::OneOf(o) => o.fields.iter().collect(), }) .collect() } #[cfg(test)] pub fn regular_fields_for_test(&self) -> Vec<&Field> { self.fields .iter() .flat_map(|fo| match fo { FieldOrOneOf::Field(f) => Some(f), FieldOrOneOf::OneOf(_) => None, }) .collect() } #[cfg(test)] pub fn oneofs_for_test(&self) -> Vec<&OneOf> { self.fields .iter() .flat_map(|fo| match fo { FieldOrOneOf::Field(_) => None, FieldOrOneOf::OneOf(o) => Some(o), }) .collect() } } /// A protobuf enumeration field #[derive(Debug, Clone)] pub struct EnumValue { /// enum value name pub name: String, /// enum value number pub number: i32, } /// A protobuf enumerator #[derive(Debug, Clone)] pub struct Enumeration { /// enum name pub name: String, /// enum values pub values: Vec, /// enum options pub options: Vec, } /// A OneOf #[derive(Debug, Clone, Default, PartialEq)] pub struct OneOf { /// OneOf name pub name: String, /// OneOf fields pub fields: Vec, } #[derive(Debug, Clone)] pub struct Extension { /// Extend this type with field pub extendee: String, /// Extension field pub field: Field, } #[derive(Debug, Clone, PartialEq)] pub enum ProtobufConstant { U64(u64), I64(i64), F64(f64), // TODO: eq Bool(bool), Ident(String), String(StrLit), BracedExpr(String), } impl ProtobufConstant { pub fn format(&self) -> String { match *self { ProtobufConstant::U64(u) => u.to_string(), ProtobufConstant::I64(i) => i.to_string(), ProtobufConstant::F64(f) => float::format_protobuf_float(f), ProtobufConstant::Bool(b) => b.to_string(), ProtobufConstant::Ident(ref i) => i.clone(), ProtobufConstant::String(ref s) => s.quoted(), ProtobufConstant::BracedExpr(ref s) => s.clone(), } } } #[derive(Debug, Clone, PartialEq)] pub struct ProtobufOption { pub name: String, pub value: ProtobufConstant, } /// Visibility of import statement #[derive(Debug, Clone, Eq, PartialEq)] pub enum ImportVis { Default, Public, Weak, } impl Default for ImportVis { fn default() -> Self { ImportVis::Default } } /// Import statement #[derive(Debug, Default, Clone)] pub struct Import { pub path: String, pub vis: ImportVis, } /// A File descriptor representing a whole .proto file #[derive(Debug, Default, Clone)] pub struct FileDescriptor { /// Imports pub imports: Vec, /// Package pub package: Option, /// Protobuf Syntax pub syntax: Syntax, /// Top level messages pub messages: Vec, /// Enums pub enums: Vec, /// Extensions pub extensions: Vec, /// Non-builtin options pub options: Vec, } impl FileDescriptor { /// Parses a .proto file content into a `FileDescriptor` pub fn parse>(file: S) -> Result { let mut parser = Parser::new(file.as_ref()); match parser.next_proto() { Ok(r) => Ok(r), Err(error) => { let Loc { line, col } = parser.loc(); Err(ParserErrorWithLocation { error, line, col }) } } } } protobuf-codegen-pure-2.27.1/src/parser.rs000064400000000000000000001744320072674642500166240ustar 00000000000000use std::f64; use std::fmt; use std::num::ParseIntError; use std::str; use model::*; use protobuf::text_format::lexer::StrLit; use protobuf::text_format::lexer::StrLitDecodeError; use protobuf_codegen::float; const FIRST_LINE: u32 = 1; const FIRST_COL: u32 = 1; /// Location in file #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub struct Loc { /// 1-based pub line: u32, /// 1-based pub col: u32, } impl fmt::Display for Loc { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}:{}", self.line, self.col) } } impl Loc { pub fn start() -> Loc { Loc { line: FIRST_LINE, col: FIRST_COL, } } } /// Basic information about parsing error. #[derive(Debug)] pub enum ParserError { IncorrectInput, IncorrectFloatLit, NotUtf8, ExpectChar(char), ExpectConstant, ExpectIdent, ExpectHexDigit, ExpectOctDigit, ExpectDecDigit, UnknownSyntax, UnexpectedEof, ParseIntError, IntegerOverflow, LabelNotAllowed, LabelRequired, InternalError, StrLitDecodeError(StrLitDecodeError), GroupNameShouldStartWithUpperCase, MapFieldNotAllowed, OneOfInGroup, OneOfInOneOf, OneOfInExtend, } #[derive(Debug)] pub struct ParserErrorWithLocation { pub error: ParserError, /// 1-based pub line: u32, /// 1-based pub col: u32, } impl From for ParserError { fn from(e: StrLitDecodeError) -> Self { ParserError::StrLitDecodeError(e) } } impl From for ParserError { fn from(_: ParseIntError) -> Self { ParserError::ParseIntError } } impl From for ParserError { fn from(_: float::ProtobufFloatParseError) -> Self { ParserError::IncorrectFloatLit } } pub type ParserResult = Result; trait ToU8 { fn to_u8(&self) -> ParserResult; } trait ToI32 { fn to_i32(&self) -> ParserResult; } trait ToI64 { fn to_i64(&self) -> ParserResult; } trait ToChar { fn to_char(&self) -> ParserResult; } impl ToI32 for u64 { fn to_i32(&self) -> ParserResult { if *self <= i32::max_value() as u64 { Ok(*self as i32) } else { Err(ParserError::IntegerOverflow) } } } impl ToI32 for i64 { fn to_i32(&self) -> ParserResult { if *self <= i32::max_value() as i64 && *self >= i32::min_value() as i64 { Ok(*self as i32) } else { Err(ParserError::IntegerOverflow) } } } impl ToI64 for u64 { fn to_i64(&self) -> Result { if *self <= i64::max_value() as u64 { Ok(*self as i64) } else { Err(ParserError::IntegerOverflow) } } } impl ToChar for u8 { fn to_char(&self) -> Result { if *self <= 0x7f { Ok(*self as char) } else { Err(ParserError::NotUtf8) } } } impl ToU8 for u32 { fn to_u8(&self) -> Result { if *self as u8 as u32 == *self { Ok(*self as u8) } else { Err(ParserError::IntegerOverflow) } } } trait U64Extensions { fn neg(&self) -> ParserResult; } impl U64Extensions for u64 { fn neg(&self) -> ParserResult { if *self <= 0x7fff_ffff_ffff_ffff { Ok(-(*self as i64)) } else if *self == 0x8000_0000_0000_0000 { Ok(-0x8000_0000_0000_0000) } else { Err(ParserError::IntegerOverflow) } } } #[derive(Clone, Debug, PartialEq)] enum Token { Ident(String), Symbol(char), IntLit(u64), // including quotes StrLit(StrLit), FloatLit(f64), } impl Token { /// Back to original fn format(&self) -> String { match self { &Token::Ident(ref s) => s.clone(), &Token::Symbol(c) => c.to_string(), &Token::IntLit(ref i) => i.to_string(), &Token::StrLit(ref s) => s.quoted(), &Token::FloatLit(ref f) => f.to_string(), } } fn to_num_lit(&self) -> ParserResult { match self { &Token::IntLit(i) => Ok(NumLit::U64(i)), &Token::FloatLit(f) => Ok(NumLit::F64(f)), _ => Err(ParserError::IncorrectInput), } } } #[derive(Clone)] struct TokenWithLocation { token: Token, loc: Loc, } #[derive(Copy, Clone)] pub struct Lexer<'a> { pub input: &'a str, pub pos: usize, pub loc: Loc, } fn is_letter(c: char) -> bool { c.is_alphabetic() || c == '_' } impl<'a> Lexer<'a> { /// No more chars pub fn eof(&self) -> bool { self.pos == self.input.len() } /// Remaining chars fn rem_chars(&self) -> &'a str { &self.input[self.pos..] } fn lookahead_char_is_in(&self, alphabet: &str) -> bool { self.lookahead_char() .map_or(false, |c| alphabet.contains(c)) } fn next_char_opt(&mut self) -> Option { let rem = self.rem_chars(); if rem.is_empty() { None } else { let mut char_indices = rem.char_indices(); let (_, c) = char_indices.next().unwrap(); let c_len = char_indices.next().map(|(len, _)| len).unwrap_or(rem.len()); self.pos += c_len; if c == '\n' { self.loc.line += 1; self.loc.col = FIRST_COL; } else { self.loc.col += 1; } Some(c) } } fn next_char(&mut self) -> ParserResult { self.next_char_opt().ok_or(ParserError::UnexpectedEof) } /// Skip whitespaces fn skip_whitespaces(&mut self) { self.take_while(|c| c.is_whitespace()); } fn skip_comment(&mut self) -> ParserResult<()> { if self.skip_if_lookahead_is_str("/*") { let end = "*/"; match self.rem_chars().find(end) { None => Err(ParserError::UnexpectedEof), Some(len) => { let new_pos = self.pos + len + end.len(); self.skip_to_pos(new_pos); Ok(()) } } } else { Ok(()) } } fn skip_block_comment(&mut self) { if self.skip_if_lookahead_is_str("//") { loop { match self.next_char_opt() { Some('\n') | None => break, _ => {} } } } } fn skip_ws(&mut self) -> ParserResult<()> { loop { let pos = self.pos; self.skip_whitespaces(); self.skip_comment()?; self.skip_block_comment(); if pos == self.pos { // Did not advance return Ok(()); } } } fn take_while(&mut self, f: F) -> &'a str where F: Fn(char) -> bool, { let start = self.pos; while self.lookahead_char().map(&f) == Some(true) { self.next_char_opt().unwrap(); } let end = self.pos; &self.input[start..end] } fn lookahead_char(&self) -> Option { self.clone().next_char_opt() } fn lookahead_is_str(&self, s: &str) -> bool { self.rem_chars().starts_with(s) } fn skip_if_lookahead_is_str(&mut self, s: &str) -> bool { if self.lookahead_is_str(s) { let new_pos = self.pos + s.len(); self.skip_to_pos(new_pos); true } else { false } } fn next_char_if

(&mut self, p: P) -> Option where P: FnOnce(char) -> bool, { let mut clone = self.clone(); match clone.next_char_opt() { Some(c) if p(c) => { *self = clone; Some(c) } _ => None, } } fn next_char_if_eq(&mut self, expect: char) -> bool { self.next_char_if(|c| c == expect) != None } fn next_char_if_in(&mut self, alphabet: &str) -> Option { for c in alphabet.chars() { if self.next_char_if_eq(c) { return Some(c); } } None } fn next_char_expect_eq(&mut self, expect: char) -> ParserResult<()> { if self.next_char_if_eq(expect) { Ok(()) } else { Err(ParserError::ExpectChar(expect)) } } // str functions /// properly update line and column fn skip_to_pos(&mut self, new_pos: usize) -> &'a str { assert!(new_pos >= self.pos); assert!(new_pos <= self.input.len()); let pos = self.pos; while self.pos != new_pos { self.next_char_opt().unwrap(); } &self.input[pos..new_pos] } // Protobuf grammar // char functions // letter = "A" … "Z" | "a" … "z" // https://github.com/google/protobuf/issues/4565 fn next_letter_opt(&mut self) -> Option { self.next_char_if(is_letter) } // capitalLetter = "A" … "Z" fn _next_capital_letter_opt(&mut self) -> Option { self.next_char_if(|c| c >= 'A' && c <= 'Z') } fn is_ascii_alphanumeric(c: char) -> bool { (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') } fn next_ident_part(&mut self) -> Option { self.next_char_if(|c| Lexer::is_ascii_alphanumeric(c) || c == '_') } // Identifiers // ident = letter { letter | decimalDigit | "_" } fn next_ident_opt(&mut self) -> ParserResult> { if let Some(c) = self.next_letter_opt() { let mut ident = String::new(); ident.push(c); while let Some(c) = self.next_ident_part() { ident.push(c); } Ok(Some(ident)) } else { Ok(None) } } // Integer literals fn is_ascii_hexdigit(c: char) -> bool { (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') } // hexLit = "0" ( "x" | "X" ) hexDigit { hexDigit } fn next_hex_lit(&mut self) -> ParserResult> { Ok( if self.skip_if_lookahead_is_str("0x") || self.skip_if_lookahead_is_str("0X") { let s = self.take_while(Lexer::is_ascii_hexdigit); Some(u64::from_str_radix(s, 16)? as u64) } else { None }, ) } fn is_ascii_digit(c: char) -> bool { c >= '0' && c <= '9' } // decimalLit = ( "1" … "9" ) { decimalDigit } // octalLit = "0" { octalDigit } fn next_decimal_octal_lit(&mut self) -> ParserResult> { // do not advance on number parse error let mut clone = self.clone(); let pos = clone.pos; Ok(if clone.next_char_if(Lexer::is_ascii_digit) != None { clone.take_while(Lexer::is_ascii_digit); let value = clone.input[pos..clone.pos].parse()?; *self = clone; Some(value) } else { None }) } // hexDigit = "0" … "9" | "A" … "F" | "a" … "f" fn next_hex_digit(&mut self) -> ParserResult { let mut clone = self.clone(); let r = match clone.next_char()? { c if c >= '0' && c <= '9' => c as u32 - b'0' as u32, c if c >= 'A' && c <= 'F' => c as u32 - b'A' as u32 + 10, c if c >= 'a' && c <= 'f' => c as u32 - b'a' as u32 + 10, _ => return Err(ParserError::ExpectHexDigit), }; *self = clone; Ok(r) } // octalDigit = "0" … "7" fn next_octal_digit(&mut self) -> ParserResult { let mut clone = self.clone(); let r = match clone.next_char()? { c if c >= '0' && c <= '7' => c as u32 - b'0' as u32, _ => return Err(ParserError::ExpectOctDigit), }; *self = clone; Ok(r) } // decimalDigit = "0" … "9" fn next_decimal_digit(&mut self) -> ParserResult { let mut clone = self.clone(); let r = match clone.next_char()? { c if c >= '0' && c <= '9' => c as u32 - '0' as u32, _ => return Err(ParserError::ExpectDecDigit), }; *self = clone; Ok(r) } // decimals = decimalDigit { decimalDigit } fn next_decimal_digits(&mut self) -> ParserResult<()> { self.next_decimal_digit()?; self.take_while(|c| c >= '0' && c <= '9'); Ok(()) } // intLit = decimalLit | octalLit | hexLit fn next_int_lit_opt(&mut self) -> ParserResult> { self.skip_ws()?; if let Some(i) = self.next_hex_lit()? { return Ok(Some(i)); } if let Some(i) = self.next_decimal_octal_lit()? { return Ok(Some(i)); } Ok(None) } // Floating-point literals // exponent = ( "e" | "E" ) [ "+" | "-" ] decimals fn next_exponent_opt(&mut self) -> ParserResult> { if self.next_char_if_in("eE") != None { self.next_char_if_in("+-"); self.next_decimal_digits()?; Ok(Some(())) } else { Ok(None) } } // floatLit = ( decimals "." [ decimals ] [ exponent ] | decimals exponent | "."decimals [ exponent ] ) | "inf" | "nan" fn next_float_lit(&mut self) -> ParserResult<()> { // "inf" and "nan" are handled as part of ident if self.next_char_if_eq('.') { self.next_decimal_digits()?; self.next_exponent_opt()?; } else { self.next_decimal_digits()?; if self.next_char_if_eq('.') { self.next_decimal_digits()?; self.next_exponent_opt()?; } else { if self.next_exponent_opt()? == None { return Err(ParserError::IncorrectFloatLit); } } } Ok(()) } // String literals // charValue = hexEscape | octEscape | charEscape | /[^\0\n\\]/ // hexEscape = '\' ( "x" | "X" ) hexDigit hexDigit // https://github.com/google/protobuf/issues/4560 // octEscape = '\' octalDigit octalDigit octalDigit // charEscape = '\' ( "a" | "b" | "f" | "n" | "r" | "t" | "v" | '\' | "'" | '"' ) // quote = "'" | '"' pub fn next_char_value(&mut self) -> ParserResult { match self.next_char()? { '\\' => { match self.next_char()? { '\'' => Ok('\''), '"' => Ok('"'), '\\' => Ok('\\'), 'a' => Ok('\x07'), 'b' => Ok('\x08'), 'f' => Ok('\x0c'), 'n' => Ok('\n'), 'r' => Ok('\r'), 't' => Ok('\t'), 'v' => Ok('\x0b'), 'x' => { let d1 = self.next_hex_digit()? as u8; let d2 = self.next_hex_digit()? as u8; // TODO: do not decode as char if > 0x80 Ok(((d1 << 4) | d2) as char) } d if d >= '0' && d <= '7' => { let mut r = d as u8 - b'0'; for _ in 0..2 { match self.next_octal_digit() { Err(_) => break, Ok(d) => r = (r << 3) + d as u8, } } // TODO: do not decode as char if > 0x80 Ok(r as char) } // https://github.com/google/protobuf/issues/4562 c => Ok(c), } } '\n' | '\0' => Err(ParserError::IncorrectInput), c => Ok(c), } } // https://github.com/google/protobuf/issues/4564 // strLit = ( "'" { charValue } "'" ) | ( '"' { charValue } '"' ) fn next_str_lit_raw(&mut self) -> ParserResult { let mut raw = String::new(); let mut first = true; loop { if !first { self.skip_ws()?; } let start = self.pos; let q = match self.next_char_if_in("'\"") { Some(q) => q, None if !first => break, None => return Err(ParserError::IncorrectInput), }; first = false; while self.lookahead_char() != Some(q) { self.next_char_value()?; } self.next_char_expect_eq(q)?; raw.push_str(&self.input[start + 1..self.pos - 1]); } Ok(raw) } fn next_str_lit_raw_opt(&mut self) -> ParserResult> { if self.lookahead_char_is_in("'\"") { Ok(Some(self.next_str_lit_raw()?)) } else { Ok(None) } } fn is_ascii_punctuation(c: char) -> bool { match c { '.' | ',' | ':' | ';' | '/' | '\\' | '=' | '%' | '+' | '-' | '*' | '<' | '>' | '(' | ')' | '{' | '}' | '[' | ']' => true, _ => false, } } fn next_token_inner(&mut self) -> ParserResult { if let Some(ident) = self.next_ident_opt()? { let token = if ident == float::PROTOBUF_NAN { Token::FloatLit(f64::NAN) } else if ident == float::PROTOBUF_INF { Token::FloatLit(f64::INFINITY) } else { Token::Ident(ident.to_owned()) }; return Ok(token); } let mut clone = self.clone(); let pos = clone.pos; if let Ok(_) = clone.next_float_lit() { let f = float::parse_protobuf_float(&self.input[pos..clone.pos])?; *self = clone; return Ok(Token::FloatLit(f)); } if let Some(lit) = self.next_int_lit_opt()? { return Ok(Token::IntLit(lit)); } if let Some(escaped) = self.next_str_lit_raw_opt()? { return Ok(Token::StrLit(StrLit { escaped })); } // This branch must be after str lit if let Some(c) = self.next_char_if(Lexer::is_ascii_punctuation) { return Ok(Token::Symbol(c)); } if let Some(ident) = self.next_ident_opt()? { return Ok(Token::Ident(ident)); } Err(ParserError::IncorrectInput) } fn next_token(&mut self) -> ParserResult> { self.skip_ws()?; let loc = self.loc; Ok(if self.eof() { None } else { let token = self.next_token_inner()?; // Skip whitespace here to update location // to the beginning of the next token self.skip_ws()?; Some(TokenWithLocation { token, loc }) }) } } #[derive(Clone)] pub struct Parser<'a> { lexer: Lexer<'a>, syntax: Syntax, next_token: Option, } #[derive(Copy, Clone)] enum MessageBodyParseMode { MessageProto2, MessageProto3, Oneof, ExtendProto2, ExtendProto3, } impl MessageBodyParseMode { fn label_allowed(&self, label: Rule) -> bool { match label { Rule::Repeated => match *self { MessageBodyParseMode::MessageProto2 | MessageBodyParseMode::MessageProto3 | MessageBodyParseMode::ExtendProto2 | MessageBodyParseMode::ExtendProto3 => true, MessageBodyParseMode::Oneof => false, }, Rule::Optional | Rule::Required => match *self { MessageBodyParseMode::MessageProto2 | MessageBodyParseMode::ExtendProto2 => true, MessageBodyParseMode::MessageProto3 | MessageBodyParseMode::ExtendProto3 | MessageBodyParseMode::Oneof => false, }, } } fn some_label_required(&self) -> bool { match *self { MessageBodyParseMode::MessageProto2 | MessageBodyParseMode::ExtendProto2 => true, MessageBodyParseMode::MessageProto3 | MessageBodyParseMode::ExtendProto3 | MessageBodyParseMode::Oneof => false, } } fn map_allowed(&self) -> bool { match *self { MessageBodyParseMode::MessageProto2 | MessageBodyParseMode::MessageProto3 | MessageBodyParseMode::ExtendProto2 | MessageBodyParseMode::ExtendProto3 => true, MessageBodyParseMode::Oneof => false, } } fn is_most_non_fields_allowed(&self) -> bool { match *self { MessageBodyParseMode::MessageProto2 | MessageBodyParseMode::MessageProto3 => true, MessageBodyParseMode::ExtendProto2 | MessageBodyParseMode::ExtendProto3 | MessageBodyParseMode::Oneof => false, } } fn is_option_allowed(&self) -> bool { match *self { MessageBodyParseMode::MessageProto2 | MessageBodyParseMode::MessageProto3 | MessageBodyParseMode::Oneof => true, MessageBodyParseMode::ExtendProto2 | MessageBodyParseMode::ExtendProto3 => false, } } } #[derive(Default)] pub struct MessageBody { pub fields: Vec, pub reserved_nums: Vec, pub reserved_names: Vec, pub messages: Vec, pub enums: Vec, pub options: Vec, } #[derive(Copy, Clone)] enum NumLit { U64(u64), F64(f64), } impl NumLit { fn to_option_value(&self, sign_is_plus: bool) -> ParserResult { Ok(match (*self, sign_is_plus) { (NumLit::U64(u), true) => ProtobufConstant::U64(u), (NumLit::F64(f), true) => ProtobufConstant::F64(f), (NumLit::U64(u), false) => ProtobufConstant::I64(u.neg()?), (NumLit::F64(f), false) => ProtobufConstant::F64(-f), }) } } impl<'a> Parser<'a> { pub fn new(input: &'a str) -> Parser<'a> { Parser { lexer: Lexer { input, pos: 0, loc: Loc::start(), }, syntax: Syntax::Proto2, next_token: None, } } pub fn loc(&self) -> Loc { self.next_token.clone().map_or(self.lexer.loc, |n| n.loc) } fn lookahead(&mut self) -> ParserResult> { Ok(match self.next_token { Some(ref token) => Some(&token.token), None => { self.next_token = self.lexer.next_token()?; match self.next_token { Some(ref token) => Some(&token.token), None => None, } } }) } fn lookahead_some(&mut self) -> ParserResult<&Token> { match self.lookahead()? { Some(token) => Ok(token), None => Err(ParserError::UnexpectedEof), } } fn next(&mut self) -> ParserResult> { self.lookahead()?; Ok(self .next_token .take() .map(|TokenWithLocation { token, .. }| token)) } fn next_some(&mut self) -> ParserResult { match self.next()? { Some(token) => Ok(token), None => Err(ParserError::UnexpectedEof), } } /// Can be called only after lookahead, otherwise it's error fn advance(&mut self) -> ParserResult { self.next_token .take() .map(|TokenWithLocation { token, .. }| token) .ok_or(ParserError::InternalError) } /// No more tokens fn syntax_eof(&mut self) -> ParserResult { Ok(self.lookahead()?.is_none()) } fn next_token_if_map(&mut self, p: P) -> ParserResult> where P: FnOnce(&Token) -> Option, { self.lookahead()?; let v = match self.next_token { Some(ref token) => match p(&token.token) { Some(v) => v, None => return Ok(None), }, _ => return Ok(None), }; self.next_token = None; Ok(Some(v)) } fn next_token_check_map(&mut self, p: P) -> ParserResult where P: FnOnce(&Token) -> ParserResult, { self.lookahead()?; let r = match self.next_token { Some(ref token) => p(&token.token)?, None => return Err(ParserError::UnexpectedEof), }; self.next_token = None; Ok(r) } fn next_token_if

(&mut self, p: P) -> ParserResult> where P: FnOnce(&Token) -> bool, { self.next_token_if_map(|token| if p(token) { Some(token.clone()) } else { None }) } fn next_ident_if_in(&mut self, idents: &[&str]) -> ParserResult> { let v = match self.lookahead()? { Some(&Token::Ident(ref next)) => { if idents.into_iter().find(|&i| i == next).is_some() { next.clone() } else { return Ok(None); } } _ => return Ok(None), }; self.advance()?; Ok(Some(v)) } fn next_ident_if_eq(&mut self, word: &str) -> ParserResult { Ok(self.next_ident_if_in(&[word])? != None) } fn next_ident_if_eq_error(&mut self, word: &str) -> ParserResult<()> { if self.clone().next_ident_if_eq(word)? { return Err(ParserError::IncorrectInput); } Ok(()) } fn next_symbol_if_eq(&mut self, symbol: char) -> ParserResult { Ok(self.next_token_if(|token| match token { &Token::Symbol(c) if c == symbol => true, _ => false, })? != None) } fn next_symbol_expect_eq(&mut self, symbol: char) -> ParserResult<()> { if self.lookahead_is_symbol(symbol)? { self.advance()?; Ok(()) } else { Err(ParserError::ExpectChar(symbol)) } } fn lookahead_if_symbol(&mut self) -> ParserResult> { Ok(match self.lookahead()? { Some(&Token::Symbol(c)) => Some(c), _ => None, }) } fn lookahead_is_symbol(&mut self, symbol: char) -> ParserResult { Ok(self.lookahead_if_symbol()? == Some(symbol)) } // Protobuf grammar fn next_ident(&mut self) -> ParserResult { self.next_token_check_map(|token| match token { &Token::Ident(ref ident) => Ok(ident.clone()), _ => Err(ParserError::ExpectIdent), }) } fn next_str_lit(&mut self) -> ParserResult { self.next_token_check_map(|token| match token { &Token::StrLit(ref str_lit) => Ok(str_lit.clone()), _ => Err(ParserError::IncorrectInput), }) } // fullIdent = ident { "." ident } fn next_full_ident(&mut self) -> ParserResult { let mut full_ident = String::new(); // https://github.com/google/protobuf/issues/4563 if self.next_symbol_if_eq('.')? { full_ident.push('.'); } full_ident.push_str(&self.next_ident()?); while self.next_symbol_if_eq('.')? { full_ident.push('.'); full_ident.push_str(&self.next_ident()?); } Ok(full_ident) } // messageName = ident // enumName = ident // messageType = [ "." ] { ident "." } messageName // enumType = [ "." ] { ident "." } enumName fn next_message_or_enum_type(&mut self) -> ParserResult { let mut full_name = String::new(); if self.next_symbol_if_eq('.')? { full_name.push('.'); } full_name.push_str(&self.next_ident()?); while self.next_symbol_if_eq('.')? { full_name.push('.'); full_name.push_str(&self.next_ident()?); } Ok(full_name) } fn is_ascii_uppercase(c: char) -> bool { c >= 'A' && c <= 'Z' } // groupName = capitalLetter { letter | decimalDigit | "_" } fn next_group_name(&mut self) -> ParserResult { // lexer cannot distinguish between group name and other ident let mut clone = self.clone(); let ident = clone.next_ident()?; if !Parser::is_ascii_uppercase(ident.chars().next().unwrap()) { return Err(ParserError::GroupNameShouldStartWithUpperCase); } *self = clone; Ok(ident) } // Boolean // boolLit = "true" | "false" fn next_bool_lit_opt(&mut self) -> ParserResult> { Ok(if self.next_ident_if_eq("true")? { Some(true) } else if self.next_ident_if_eq("false")? { Some(false) } else { None }) } // Constant fn next_num_lit(&mut self) -> ParserResult { self.next_token_check_map(|token| token.to_num_lit()) } // constant = fullIdent | ( [ "-" | "+" ] intLit ) | ( [ "-" | "+" ] floatLit ) | // strLit | boolLit fn next_constant(&mut self) -> ParserResult { // https://github.com/google/protobuf/blob/a21f225824e994ebd35e8447382ea4e0cd165b3c/src/google/protobuf/unittest_custom_options.proto#L350 if self.lookahead_is_symbol('{')? { return Ok(ProtobufConstant::BracedExpr(self.next_braces()?)); } if let Some(b) = self.next_bool_lit_opt()? { return Ok(ProtobufConstant::Bool(b)); } if let &Token::Symbol(c) = self.lookahead_some()? { if c == '+' || c == '-' { self.advance()?; let sign = c == '+'; return Ok(self.next_num_lit()?.to_option_value(sign)?); } } if let Some(r) = self.next_token_if_map(|token| match token { &Token::StrLit(ref s) => Some(ProtobufConstant::String(s.clone())), _ => None, })? { return Ok(r); } match self.lookahead_some()? { &Token::IntLit(..) | &Token::FloatLit(..) => { return self.next_num_lit()?.to_option_value(true); } &Token::Ident(..) => { return Ok(ProtobufConstant::Ident(self.next_full_ident()?)); } _ => {} } Err(ParserError::ExpectConstant) } fn next_int_lit(&mut self) -> ParserResult { self.next_token_check_map(|token| match token { &Token::IntLit(i) => Ok(i), _ => Err(ParserError::IncorrectInput), }) } // Syntax // syntax = "syntax" "=" quote "proto2" quote ";" // syntax = "syntax" "=" quote "proto3" quote ";" fn next_syntax(&mut self) -> ParserResult> { if self.next_ident_if_eq("syntax")? { self.next_symbol_expect_eq('=')?; let syntax_str = self.next_str_lit()?.decode_utf8()?; let syntax = if syntax_str == "proto2" { Syntax::Proto2 } else if syntax_str == "proto3" { Syntax::Proto3 } else { return Err(ParserError::UnknownSyntax); }; self.next_symbol_expect_eq(';')?; Ok(Some(syntax)) } else { Ok(None) } } // Import Statement // import = "import" [ "weak" | "public" ] strLit ";" fn next_import_opt(&mut self) -> ParserResult> { if self.next_ident_if_eq("import")? { let vis = if self.next_ident_if_eq("weak")? { ImportVis::Weak } else if self.next_ident_if_eq("public")? { ImportVis::Public } else { ImportVis::Default }; let path = self.next_str_lit()?.decode_utf8()?; self.next_symbol_expect_eq(';')?; Ok(Some(Import { path, vis })) } else { Ok(None) } } // Package // package = "package" fullIdent ";" fn next_package_opt(&mut self) -> ParserResult> { if self.next_ident_if_eq("package")? { let package = self.next_full_ident()?; self.next_symbol_expect_eq(';')?; Ok(Some(package)) } else { Ok(None) } } // Option fn next_ident_or_braced(&mut self) -> ParserResult { let mut ident_or_braced = String::new(); if self.next_symbol_if_eq('(')? { ident_or_braced.push('('); ident_or_braced.push_str(&self.next_full_ident()?); self.next_symbol_expect_eq(')')?; ident_or_braced.push(')'); } else { ident_or_braced.push_str(&self.next_ident()?); } Ok(ident_or_braced) } // https://github.com/google/protobuf/issues/4563 // optionName = ( ident | "(" fullIdent ")" ) { "." ident } fn next_option_name(&mut self) -> ParserResult { let mut option_name = String::new(); option_name.push_str(&self.next_ident_or_braced()?); while self.next_symbol_if_eq('.')? { option_name.push('.'); option_name.push_str(&self.next_ident_or_braced()?); } Ok(option_name) } // option = "option" optionName "=" constant ";" fn next_option_opt(&mut self) -> ParserResult> { if self.next_ident_if_eq("option")? { let name = self.next_option_name()?; self.next_symbol_expect_eq('=')?; let value = self.next_constant()?; self.next_symbol_expect_eq(';')?; Ok(Some(ProtobufOption { name, value })) } else { Ok(None) } } // Fields // label = "required" | "optional" | "repeated" fn next_label(&mut self, mode: MessageBodyParseMode) -> ParserResult { let map = &[ ("optional", Rule::Optional), ("required", Rule::Required), ("repeated", Rule::Repeated), ]; for &(name, value) in map { let mut clone = self.clone(); if clone.next_ident_if_eq(name)? { if !mode.label_allowed(value) { return Err(ParserError::LabelNotAllowed); } *self = clone; return Ok(value); } } if mode.some_label_required() { Err(ParserError::LabelRequired) } else { Ok(Rule::Optional) } } fn next_field_type(&mut self) -> ParserResult { let simple = &[ ("int32", FieldType::Int32), ("int64", FieldType::Int64), ("uint32", FieldType::Uint32), ("uint64", FieldType::Uint64), ("sint32", FieldType::Sint32), ("sint64", FieldType::Sint64), ("fixed32", FieldType::Fixed32), ("sfixed32", FieldType::Sfixed32), ("fixed64", FieldType::Fixed64), ("sfixed64", FieldType::Sfixed64), ("bool", FieldType::Bool), ("string", FieldType::String), ("bytes", FieldType::Bytes), ("float", FieldType::Float), ("double", FieldType::Double), ]; for &(ref n, ref t) in simple { if self.next_ident_if_eq(n)? { return Ok(t.clone()); } } if let Some(t) = self.next_map_field_type_opt()? { return Ok(t); } let message_or_enum = self.next_message_or_enum_type()?; Ok(FieldType::MessageOrEnum(message_or_enum)) } fn next_field_number(&mut self) -> ParserResult { self.next_token_check_map(|token| match token { &Token::IntLit(i) => i.to_i32(), _ => Err(ParserError::IncorrectInput), }) } // fieldOption = optionName "=" constant fn next_field_option(&mut self) -> ParserResult { let name = self.next_option_name()?; self.next_symbol_expect_eq('=')?; let value = self.next_constant()?; Ok(ProtobufOption { name, value }) } // fieldOptions = fieldOption { "," fieldOption } fn next_field_options(&mut self) -> ParserResult> { let mut options = Vec::new(); options.push(self.next_field_option()?); while self.next_symbol_if_eq(',')? { options.push(self.next_field_option()?); } Ok(options) } // field = label type fieldName "=" fieldNumber [ "[" fieldOptions "]" ] ";" // group = label "group" groupName "=" fieldNumber messageBody fn next_field(&mut self, mode: MessageBodyParseMode) -> ParserResult { let rule = if self.clone().next_ident_if_eq("map")? { if !mode.map_allowed() { return Err(ParserError::MapFieldNotAllowed); } Rule::Optional } else { self.next_label(mode)? }; if self.next_ident_if_eq("group")? { let name = self.next_group_name()?.to_owned(); self.next_symbol_expect_eq('=')?; let number = self.next_field_number()?; let mode = match self.syntax { Syntax::Proto2 => MessageBodyParseMode::MessageProto2, Syntax::Proto3 => MessageBodyParseMode::MessageProto3, }; let MessageBody { fields, .. } = self.next_message_body(mode)?; let fields = fields .into_iter() .map(|fo| match fo { FieldOrOneOf::Field(f) => Ok(f), FieldOrOneOf::OneOf(_) => Err(ParserError::OneOfInGroup), }) .collect::>()?; Ok(Field { // The field name is a lowercased version of the type name // (which has been verified to start with an uppercase letter). // https://git.io/JvxAP name: name.to_ascii_lowercase(), rule, typ: FieldType::Group { name, fields }, number, options: Vec::new(), }) } else { let typ = self.next_field_type()?; let name = self.next_ident()?.to_owned(); self.next_symbol_expect_eq('=')?; let number = self.next_field_number()?; let mut options = Vec::new(); if self.next_symbol_if_eq('[')? { for o in self.next_field_options()? { options.push(o); } self.next_symbol_expect_eq(']')?; } self.next_symbol_expect_eq(';')?; Ok(Field { name, rule, typ, number, options, }) } } // oneof = "oneof" oneofName "{" { oneofField | emptyStatement } "}" // oneofField = type fieldName "=" fieldNumber [ "[" fieldOptions "]" ] ";" fn next_oneof_opt(&mut self) -> ParserResult> { if self.next_ident_if_eq("oneof")? { let name = self.next_ident()?.to_owned(); let MessageBody { fields, .. } = self.next_message_body(MessageBodyParseMode::Oneof)?; let fields = fields .into_iter() .map(|fo| match fo { FieldOrOneOf::Field(f) => Ok(f), FieldOrOneOf::OneOf(_) => Err(ParserError::OneOfInOneOf), }) .collect::>()?; Ok(Some(OneOf { name, fields })) } else { Ok(None) } } // mapField = "map" "<" keyType "," type ">" mapName "=" fieldNumber [ "[" fieldOptions "]" ] ";" // keyType = "int32" | "int64" | "uint32" | "uint64" | "sint32" | "sint64" | // "fixed32" | "fixed64" | "sfixed32" | "sfixed64" | "bool" | "string" fn next_map_field_type_opt(&mut self) -> ParserResult> { if self.next_ident_if_eq("map")? { self.next_symbol_expect_eq('<')?; // TODO: restrict key types let key = self.next_field_type()?; self.next_symbol_expect_eq(',')?; let value = self.next_field_type()?; self.next_symbol_expect_eq('>')?; Ok(Some(FieldType::Map(Box::new((key, value))))) } else { Ok(None) } } // Extensions and Reserved // Extensions // range = intLit [ "to" ( intLit | "max" ) ] fn next_range(&mut self) -> ParserResult { let from = self.next_field_number()?; let to = if self.next_ident_if_eq("to")? { if self.next_ident_if_eq("max")? { i32::max_value() } else { self.next_field_number()? } } else { from }; Ok(FieldNumberRange { from, to }) } // ranges = range { "," range } fn next_ranges(&mut self) -> ParserResult> { let mut ranges = Vec::new(); ranges.push(self.next_range()?); while self.next_symbol_if_eq(',')? { ranges.push(self.next_range()?); } Ok(ranges) } // extensions = "extensions" ranges ";" fn next_extensions_opt(&mut self) -> ParserResult>> { if self.next_ident_if_eq("extensions")? { Ok(Some(self.next_ranges()?)) } else { Ok(None) } } // Reserved // Grammar is incorrect: https://github.com/google/protobuf/issues/4558 // reserved = "reserved" ( ranges | fieldNames ) ";" // fieldNames = fieldName { "," fieldName } fn next_reserved_opt(&mut self) -> ParserResult, Vec)>> { if self.next_ident_if_eq("reserved")? { let (ranges, names) = if let &Token::StrLit(..) = self.lookahead_some()? { let mut names = Vec::new(); names.push(self.next_str_lit()?.decode_utf8()?); while self.next_symbol_if_eq(',')? { names.push(self.next_str_lit()?.decode_utf8()?); } (Vec::new(), names) } else { (self.next_ranges()?, Vec::new()) }; self.next_symbol_expect_eq(';')?; Ok(Some((ranges, names))) } else { Ok(None) } } // Top Level definitions // Enum definition // enumValueOption = optionName "=" constant fn next_enum_value_option(&mut self) -> ParserResult<()> { self.next_option_name()?; self.next_symbol_expect_eq('=')?; self.next_constant()?; Ok(()) } // https://github.com/google/protobuf/issues/4561 fn next_enum_value(&mut self) -> ParserResult { let minus = self.next_symbol_if_eq('-')?; let lit = self.next_int_lit()?; Ok(if minus { let unsigned = lit.to_i64()?; match unsigned.checked_neg() { Some(neg) => neg.to_i32()?, None => return Err(ParserError::IntegerOverflow), } } else { lit.to_i32()? }) } // enumField = ident "=" intLit [ "[" enumValueOption { "," enumValueOption } "]" ]";" fn next_enum_field(&mut self) -> ParserResult { let name = self.next_ident()?.to_owned(); self.next_symbol_expect_eq('=')?; let number = self.next_enum_value()?; if self.next_symbol_if_eq('[')? { self.next_enum_value_option()?; while self.next_symbol_if_eq(',')? { self.next_enum_value_option()?; } self.next_symbol_expect_eq(']')?; } Ok(EnumValue { name, number }) } // enum = "enum" enumName enumBody // enumBody = "{" { option | enumField | emptyStatement } "}" fn next_enum_opt(&mut self) -> ParserResult> { if self.next_ident_if_eq("enum")? { let name = self.next_ident()?.to_owned(); let mut values = Vec::new(); let mut options = Vec::new(); self.next_symbol_expect_eq('{')?; while self.lookahead_if_symbol()? != Some('}') { // emptyStatement if self.next_symbol_if_eq(';')? { continue; } if let Some(o) = self.next_option_opt()? { options.push(o); continue; } values.push(self.next_enum_field()?); } self.next_symbol_expect_eq('}')?; Ok(Some(Enumeration { name, values, options, })) } else { Ok(None) } } // Message definition // messageBody = "{" { field | enum | message | extend | extensions | group | // option | oneof | mapField | reserved | emptyStatement } "}" fn next_message_body(&mut self, mode: MessageBodyParseMode) -> ParserResult { self.next_symbol_expect_eq('{')?; let mut r = MessageBody::default(); while self.lookahead_if_symbol()? != Some('}') { // emptyStatement if self.next_symbol_if_eq(';')? { continue; } if mode.is_most_non_fields_allowed() { if let Some((field_nums, field_names)) = self.next_reserved_opt()? { r.reserved_nums.extend(field_nums); r.reserved_names.extend(field_names); continue; } if let Some(oneof) = self.next_oneof_opt()? { r.fields.push(FieldOrOneOf::OneOf(oneof)); continue; } if let Some(_extensions) = self.next_extensions_opt()? { continue; } if let Some(_extend) = self.next_extend_opt()? { continue; } if let Some(nested_message) = self.next_message_opt()? { r.messages.push(nested_message); continue; } if let Some(nested_enum) = self.next_enum_opt()? { r.enums.push(nested_enum); continue; } } else { self.next_ident_if_eq_error("reserved")?; self.next_ident_if_eq_error("oneof")?; self.next_ident_if_eq_error("extensions")?; self.next_ident_if_eq_error("extend")?; self.next_ident_if_eq_error("message")?; self.next_ident_if_eq_error("enum")?; } if mode.is_option_allowed() { if let Some(option) = self.next_option_opt()? { r.options.push(option); continue; } } else { self.next_ident_if_eq_error("option")?; } r.fields.push(FieldOrOneOf::Field(self.next_field(mode)?)); } self.next_symbol_expect_eq('}')?; Ok(r) } // message = "message" messageName messageBody fn next_message_opt(&mut self) -> ParserResult> { if self.next_ident_if_eq("message")? { let name = self.next_ident()?.to_owned(); let mode = match self.syntax { Syntax::Proto2 => MessageBodyParseMode::MessageProto2, Syntax::Proto3 => MessageBodyParseMode::MessageProto3, }; let MessageBody { fields, reserved_nums, reserved_names, messages, enums, options, } = self.next_message_body(mode)?; Ok(Some(Message { name, fields, reserved_nums, reserved_names, messages, enums, options, })) } else { Ok(None) } } // Extend // extend = "extend" messageType "{" {field | group | emptyStatement} "}" fn next_extend_opt(&mut self) -> ParserResult>> { let mut clone = self.clone(); if clone.next_ident_if_eq("extend")? { // According to spec `extend` is only for `proto2`, but it is used in `proto3` // https://github.com/google/protobuf/issues/4610 *self = clone; let extendee = self.next_message_or_enum_type()?; let mode = match self.syntax { Syntax::Proto2 => MessageBodyParseMode::ExtendProto2, Syntax::Proto3 => MessageBodyParseMode::ExtendProto3, }; let MessageBody { fields, .. } = self.next_message_body(mode)?; // TODO: is oneof allowed in extend? let fields: Vec = fields .into_iter() .map(|fo| match fo { FieldOrOneOf::Field(f) => Ok(f), FieldOrOneOf::OneOf(_) => Err(ParserError::OneOfInExtend), }) .collect::>()?; let extensions = fields .into_iter() .map(|field| { let extendee = extendee.clone(); Extension { extendee, field } }) .collect(); Ok(Some(extensions)) } else { Ok(None) } } // Service definition fn next_braces(&mut self) -> ParserResult { let mut r = String::new(); self.next_symbol_expect_eq('{')?; r.push('{'); loop { if self.lookahead_if_symbol()? == Some('{') { r.push_str(&self.next_braces()?); continue; } let next = self.next_some()?; r.push_str(&next.format()); if let Token::Symbol('}') = next { break; } } Ok(r) } // service = "service" serviceName "{" { option | rpc | stream | emptyStatement } "}" // rpc = "rpc" rpcName "(" [ "stream" ] messageType ")" "returns" "(" [ "stream" ] // messageType ")" (( "{" { option | emptyStatement } "}" ) | ";" ) // stream = "stream" streamName "(" messageType "," messageType ")" (( "{" // { option | emptyStatement } "}") | ";" ) fn next_service_opt(&mut self) -> ParserResult> { if self.next_ident_if_eq("service")? { let _name = self.next_ident()?; self.next_braces()?; Ok(Some(())) } else { Ok(None) } } // Proto file // proto = syntax { import | package | option | topLevelDef | emptyStatement } // topLevelDef = message | enum | extend | service pub fn next_proto(&mut self) -> ParserResult { let syntax = self.next_syntax()?.unwrap_or(Syntax::Proto2); self.syntax = syntax; let mut imports = Vec::new(); let mut package = None; let mut messages = Vec::new(); let mut enums = Vec::new(); let mut extensions = Vec::new(); let mut options = Vec::new(); while !self.syntax_eof()? { if let Some(import) = self.next_import_opt()? { imports.push(import); continue; } if let Some(next_package) = self.next_package_opt()? { package = Some(next_package); continue; } if let Some(option) = self.next_option_opt()? { options.push(option); continue; } if let Some(message) = self.next_message_opt()? { messages.push(message); continue; } if let Some(enumeration) = self.next_enum_opt()? { enums.push(enumeration); continue; } if let Some(more_extensions) = self.next_extend_opt()? { extensions.extend(more_extensions); continue; } if let Some(_service) = self.next_service_opt()? { continue; } if self.next_symbol_if_eq(';')? { continue; } return Err(ParserError::IncorrectInput); } Ok(FileDescriptor { imports, package, syntax, messages, enums, extensions, options, }) } } #[cfg(test)] mod test { use super::*; fn lex(input: &str, parse_what: P) -> R where P: FnOnce(&mut Lexer) -> ParserResult, { let mut lexer = Lexer { input, pos: 0, loc: Loc::start(), }; let r = parse_what(&mut lexer).expect(&format!("lexer failed at {}", lexer.loc)); assert!(lexer.eof(), "check eof failed at {}", lexer.loc); r } fn lex_opt(input: &str, parse_what: P) -> R where P: FnOnce(&mut Lexer) -> ParserResult>, { let mut lexer = Lexer { input, pos: 0, loc: Loc::start(), }; let o = parse_what(&mut lexer).expect(&format!("lexer failed at {}", lexer.loc)); let r = o.expect(&format!("lexer returned none at {}", lexer.loc)); assert!(lexer.eof(), "check eof failed at {}", lexer.loc); r } fn parse(input: &str, parse_what: P) -> R where P: FnOnce(&mut Parser) -> ParserResult, { let mut parser = Parser::new(input); let r = parse_what(&mut parser).expect(&format!("parse failed at {}", parser.loc())); let eof = parser .syntax_eof() .expect(&format!("check eof failed at {}", parser.loc())); assert!(eof, "{}", parser.loc()); r } fn parse_opt(input: &str, parse_what: P) -> R where P: FnOnce(&mut Parser) -> ParserResult>, { let mut parser = Parser::new(input); let o = parse_what(&mut parser).expect(&format!("parse failed at {}", parser.loc())); let r = o.expect(&format!("parser returned none at {}", parser.loc())); assert!(parser.syntax_eof().unwrap()); r } #[test] fn test_lexer_int_lit() { let msg = r#"10"#; let mess = lex_opt(msg, |p| p.next_int_lit_opt()); assert_eq!(10, mess); } #[test] fn test_lexer_float_lit() { let msg = r#"12.3"#; let mess = lex(msg, |p| p.next_token_inner()); assert_eq!(Token::FloatLit(12.3), mess); } #[test] fn test_ident() { let msg = r#" aabb_c "#; let mess = parse(msg, |p| p.next_ident().map(|s| s.to_owned())); assert_eq!("aabb_c", mess); } #[test] fn test_str_lit() { let msg = r#" "a\nb" "#; let mess = parse(msg, |p| p.next_str_lit()); assert_eq!( StrLit { escaped: r#"a\nb"#.to_owned() }, mess ); } #[test] fn test_syntax() { let msg = r#" syntax = "proto3"; "#; let mess = parse_opt(msg, |p| p.next_syntax()); assert_eq!(Syntax::Proto3, mess); } #[test] fn test_field_default_value_int() { let msg = r#" optional int64 f = 4 [default = 12]; "#; let mess = parse(msg, |p| p.next_field(MessageBodyParseMode::MessageProto2)); assert_eq!("f", mess.name); assert_eq!("default", mess.options[0].name); assert_eq!("12", mess.options[0].value.format()); } #[test] fn test_field_default_value_float() { let msg = r#" optional float f = 2 [default = 10.0]; "#; let mess = parse(msg, |p| p.next_field(MessageBodyParseMode::MessageProto2)); assert_eq!("f", mess.name); assert_eq!("default", mess.options[0].name); assert_eq!("10.0", mess.options[0].value.format()); } #[test] fn test_message() { let msg = r#"message ReferenceData { repeated ScenarioInfo scenarioSet = 1; repeated CalculatedObjectInfo calculatedObjectSet = 2; repeated RiskFactorList riskFactorListSet = 3; repeated RiskMaturityInfo riskMaturitySet = 4; repeated IndicatorInfo indicatorSet = 5; repeated RiskStrikeInfo riskStrikeSet = 6; repeated FreeProjectionList freeProjectionListSet = 7; repeated ValidationProperty ValidationSet = 8; repeated CalcProperties calcPropertiesSet = 9; repeated MaturityInfo maturitySet = 10; }"#; let mess = parse_opt(msg, |p| p.next_message_opt()); assert_eq!(10, mess.fields.len()); } #[test] fn test_enum() { let msg = r#"enum PairingStatus { DEALPAIRED = 0; INVENTORYORPHAN = 1; CALCULATEDORPHAN = 2; CANCELED = 3; }"#; let enumeration = parse_opt(msg, |p| p.next_enum_opt()); assert_eq!(4, enumeration.values.len()); } #[test] fn test_ignore() { let msg = r#"option optimize_for = SPEED;"#; parse_opt(msg, |p| p.next_option_opt()); } #[test] fn test_package() { let msg = r#" package foo.bar; message ContainsImportedNested { optional ContainerForNested.NestedMessage m = 1; optional ContainerForNested.NestedEnum e = 2; } "#; let desc = parse(msg, |p| p.next_proto()); assert_eq!(Some("foo.bar".to_string()), desc.package); } #[test] fn test_no_package() { let msg = r#" message A { optional int32 a = 1; } "#; let desc = parse(msg, |p| p.next_proto()); assert_eq!(None, desc.package); } #[test] fn test_nested_message() { let msg = r#"message A { message B { repeated int32 a = 1; optional string b = 2; } optional string b = 1; }"#; let mess = parse_opt(msg, |p| p.next_message_opt()); assert_eq!(1, mess.messages.len()); } #[test] fn test_map() { let msg = r#"message A { optional map b = 1; }"#; let mess = parse_opt(msg, |p| p.next_message_opt()); assert_eq!(1, mess.fields.len()); match mess.regular_fields_for_test()[0].typ { FieldType::Map(ref f) => match &**f { &(FieldType::String, FieldType::Int32) => (), ref f => panic!("Expecting Map found {:?}", f), }, ref f => panic!("Expecting map, got {:?}", f), } } #[test] fn test_oneof() { let msg = r#"message A { optional int32 a1 = 1; oneof a_oneof { string a2 = 2; int32 a3 = 3; bytes a4 = 4; } repeated bool a5 = 5; }"#; let mess = parse_opt(msg, |p| p.next_message_opt()); assert_eq!(1, mess.oneofs_for_test().len()); assert_eq!(3, mess.oneofs_for_test()[0].fields.len()); } #[test] fn test_reserved() { let msg = r#"message Sample { reserved 4, 15, 17 to 20, 30; reserved "foo", "bar"; optional uint64 age =1; required bytes name =2; }"#; let mess = parse_opt(msg, |p| p.next_message_opt()); assert_eq!( vec![ FieldNumberRange { from: 4, to: 4 }, FieldNumberRange { from: 15, to: 15 }, FieldNumberRange { from: 17, to: 20 }, FieldNumberRange { from: 30, to: 30 } ], mess.reserved_nums ); assert_eq!( vec!["foo".to_string(), "bar".to_string()], mess.reserved_names ); assert_eq!(2, mess.fields.len()); } #[test] fn test_default_value_int() { let msg = r#"message Sample { optional int32 x = 1 [default = 17]; }"#; let mess = parse_opt(msg, |p| p.next_message_opt()); assert_eq!("default", mess.regular_fields_for_test()[0].options[0].name); assert_eq!( "17", mess.regular_fields_for_test()[0].options[0].value.format() ); } #[test] fn test_default_value_string() { let msg = r#"message Sample { optional string x = 1 [default = "ab\nc d\"g\'h\0\"z"]; }"#; let mess = parse_opt(msg, |p| p.next_message_opt()); assert_eq!( r#""ab\nc d\"g\'h\0\"z""#, mess.regular_fields_for_test()[0].options[0].value.format() ); } #[test] fn test_default_value_bytes() { let msg = r#"message Sample { optional bytes x = 1 [default = "ab\nc d\xfeE\"g\'h\0\"z"]; }"#; let mess = parse_opt(msg, |p| p.next_message_opt()); assert_eq!( r#""ab\nc d\xfeE\"g\'h\0\"z""#, mess.regular_fields_for_test()[0].options[0].value.format() ); } #[test] fn test_group() { let msg = r#"message MessageWithGroup { optional string aaa = 1; repeated group Identifier = 18 { optional int32 iii = 19; optional string sss = 20; } required int bbb = 3; }"#; let mess = parse_opt(msg, |p| p.next_message_opt()); assert_eq!("identifier", mess.regular_fields_for_test()[1].name); if let FieldType::Group { name, fields } = &mess.regular_fields_for_test()[1].typ { assert_eq!(2, fields.len()); } else { panic!("expecting group"); } assert_eq!("bbb", mess.regular_fields_for_test()[2].name); } #[test] fn test_incorrect_file_descriptor() { let msg = r#" message Foo {} dfgdg "#; let err = FileDescriptor::parse(msg).err().expect("err"); assert_eq!(4, err.line); } #[test] fn test_extend() { let proto = r#" syntax = "proto2"; extend google.protobuf.FileOptions { optional bool foo = 17001; optional string bar = 17002; } extend google.protobuf.MessageOptions { optional bool baz = 17003; } "#; let fd = FileDescriptor::parse(proto).expect("fd"); assert_eq!(3, fd.extensions.len()); assert_eq!("google.protobuf.FileOptions", fd.extensions[0].extendee); assert_eq!("google.protobuf.FileOptions", fd.extensions[1].extendee); assert_eq!("google.protobuf.MessageOptions", fd.extensions[2].extendee); assert_eq!(17003, fd.extensions[2].field.number); } } protobuf-codegen-pure-2.27.1/src/proto/README.md000064400000000000000000000002540072674642500173720ustar 00000000000000This folder contains copy of .proto files needed for pure codegen. Files are copied here because when publishing to crates, referencing files from outside is not allowed. protobuf-codegen-pure-2.27.1/src/proto/google/protobuf/any.proto000064400000000000000000000134340072674642500231070ustar 00000000000000// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto3"; package google.protobuf; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option go_package = "google.golang.org/protobuf/types/known/anypb"; option java_package = "com.google.protobuf"; option java_outer_classname = "AnyProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; // `Any` contains an arbitrary serialized protocol buffer message along with a // URL that describes the type of the serialized message. // // Protobuf library provides support to pack/unpack Any values in the form // of utility functions or additional generated methods of the Any type. // // Example 1: Pack and unpack a message in C++. // // Foo foo = ...; // Any any; // any.PackFrom(foo); // ... // if (any.UnpackTo(&foo)) { // ... // } // // Example 2: Pack and unpack a message in Java. // // Foo foo = ...; // Any any = Any.pack(foo); // ... // if (any.is(Foo.class)) { // foo = any.unpack(Foo.class); // } // // Example 3: Pack and unpack a message in Python. // // foo = Foo(...) // any = Any() // any.Pack(foo) // ... // if any.Is(Foo.DESCRIPTOR): // any.Unpack(foo) // ... // // Example 4: Pack and unpack a message in Go // // foo := &pb.Foo{...} // any, err := anypb.New(foo) // if err != nil { // ... // } // ... // foo := &pb.Foo{} // if err := any.UnmarshalTo(foo); err != nil { // ... // } // // The pack methods provided by protobuf library will by default use // 'type.googleapis.com/full.type.name' as the type URL and the unpack // methods only use the fully qualified type name after the last '/' // in the type URL, for example "foo.bar.com/x/y.z" will yield type // name "y.z". // // // JSON // ==== // The JSON representation of an `Any` value uses the regular // representation of the deserialized, embedded message, with an // additional field `@type` which contains the type URL. Example: // // package google.profile; // message Person { // string first_name = 1; // string last_name = 2; // } // // { // "@type": "type.googleapis.com/google.profile.Person", // "firstName": , // "lastName": // } // // If the embedded message type is well-known and has a custom JSON // representation, that representation will be embedded adding a field // `value` which holds the custom JSON in addition to the `@type` // field. Example (for message [google.protobuf.Duration][]): // // { // "@type": "type.googleapis.com/google.protobuf.Duration", // "value": "1.212s" // } // message Any { // A URL/resource name that uniquely identifies the type of the serialized // protocol buffer message. This string must contain at least // one "/" character. The last segment of the URL's path must represent // the fully qualified name of the type (as in // `path/google.protobuf.Duration`). The name should be in a canonical form // (e.g., leading "." is not accepted). // // In practice, teams usually precompile into the binary all types that they // expect it to use in the context of Any. However, for URLs which use the // scheme `http`, `https`, or no scheme, one can optionally set up a type // server that maps type URLs to message definitions as follows: // // * If no scheme is provided, `https` is assumed. // * An HTTP GET on the URL must yield a [google.protobuf.Type][] // value in binary format, or produce an error. // * Applications are allowed to cache lookup results based on the // URL, or have them precompiled into a binary to avoid any // lookup. Therefore, binary compatibility needs to be preserved // on changes to types. (Use versioned type names to manage // breaking changes.) // // Note: this functionality is not currently available in the official // protobuf release, and it is not used for type URLs beginning with // type.googleapis.com. // // Schemes other than `http`, `https` (or the empty scheme) might be // used with implementation specific semantics. // string type_url = 1; // Must be a valid serialized protocol buffer of the above specified type. bytes value = 2; } protobuf-codegen-pure-2.27.1/src/proto/google/protobuf/api.proto000064400000000000000000000170660072674642500230760ustar 00000000000000// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto3"; package google.protobuf; import "google/protobuf/source_context.proto"; import "google/protobuf/type.proto"; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option java_package = "com.google.protobuf"; option java_outer_classname = "ApiProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; option go_package = "google.golang.org/protobuf/types/known/apipb"; // Api is a light-weight descriptor for an API Interface. // // Interfaces are also described as "protocol buffer services" in some contexts, // such as by the "service" keyword in a .proto file, but they are different // from API Services, which represent a concrete implementation of an interface // as opposed to simply a description of methods and bindings. They are also // sometimes simply referred to as "APIs" in other contexts, such as the name of // this message itself. See https://cloud.google.com/apis/design/glossary for // detailed terminology. message Api { // The fully qualified name of this interface, including package name // followed by the interface's simple name. string name = 1; // The methods of this interface, in unspecified order. repeated Method methods = 2; // Any metadata attached to the interface. repeated Option options = 3; // A version string for this interface. If specified, must have the form // `major-version.minor-version`, as in `1.10`. If the minor version is // omitted, it defaults to zero. If the entire version field is empty, the // major version is derived from the package name, as outlined below. If the // field is not empty, the version in the package name will be verified to be // consistent with what is provided here. // // The versioning schema uses [semantic // versioning](http://semver.org) where the major version number // indicates a breaking change and the minor version an additive, // non-breaking change. Both version numbers are signals to users // what to expect from different versions, and should be carefully // chosen based on the product plan. // // The major version is also reflected in the package name of the // interface, which must end in `v`, as in // `google.feature.v1`. For major versions 0 and 1, the suffix can // be omitted. Zero major versions must only be used for // experimental, non-GA interfaces. // // string version = 4; // Source context for the protocol buffer service represented by this // message. SourceContext source_context = 5; // Included interfaces. See [Mixin][]. repeated Mixin mixins = 6; // The source syntax of the service. Syntax syntax = 7; } // Method represents a method of an API interface. message Method { // The simple name of this method. string name = 1; // A URL of the input message type. string request_type_url = 2; // If true, the request is streamed. bool request_streaming = 3; // The URL of the output message type. string response_type_url = 4; // If true, the response is streamed. bool response_streaming = 5; // Any metadata attached to the method. repeated Option options = 6; // The source syntax of this method. Syntax syntax = 7; } // Declares an API Interface to be included in this interface. The including // interface must redeclare all the methods from the included interface, but // documentation and options are inherited as follows: // // - If after comment and whitespace stripping, the documentation // string of the redeclared method is empty, it will be inherited // from the original method. // // - Each annotation belonging to the service config (http, // visibility) which is not set in the redeclared method will be // inherited. // // - If an http annotation is inherited, the path pattern will be // modified as follows. Any version prefix will be replaced by the // version of the including interface plus the [root][] path if // specified. // // Example of a simple mixin: // // package google.acl.v1; // service AccessControl { // // Get the underlying ACL object. // rpc GetAcl(GetAclRequest) returns (Acl) { // option (google.api.http).get = "/v1/{resource=**}:getAcl"; // } // } // // package google.storage.v2; // service Storage { // rpc GetAcl(GetAclRequest) returns (Acl); // // // Get a data record. // rpc GetData(GetDataRequest) returns (Data) { // option (google.api.http).get = "/v2/{resource=**}"; // } // } // // Example of a mixin configuration: // // apis: // - name: google.storage.v2.Storage // mixins: // - name: google.acl.v1.AccessControl // // The mixin construct implies that all methods in `AccessControl` are // also declared with same name and request/response types in // `Storage`. A documentation generator or annotation processor will // see the effective `Storage.GetAcl` method after inheriting // documentation and annotations as follows: // // service Storage { // // Get the underlying ACL object. // rpc GetAcl(GetAclRequest) returns (Acl) { // option (google.api.http).get = "/v2/{resource=**}:getAcl"; // } // ... // } // // Note how the version in the path pattern changed from `v1` to `v2`. // // If the `root` field in the mixin is specified, it should be a // relative path under which inherited HTTP paths are placed. Example: // // apis: // - name: google.storage.v2.Storage // mixins: // - name: google.acl.v1.AccessControl // root: acls // // This implies the following inherited HTTP annotation: // // service Storage { // // Get the underlying ACL object. // rpc GetAcl(GetAclRequest) returns (Acl) { // option (google.api.http).get = "/v2/acls/{resource=**}:getAcl"; // } // ... // } message Mixin { // The fully qualified name of the interface which is included. string name = 1; // If non-empty specifies a path under which inherited HTTP paths // are rooted. string root = 2; } protobuf-codegen-pure-2.27.1/src/proto/google/protobuf/compiler/plugin.proto000064400000000000000000000210620072674642500254240ustar 00000000000000// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: kenton@google.com (Kenton Varda) // // WARNING: The plugin interface is currently EXPERIMENTAL and is subject to // change. // // protoc (aka the Protocol Compiler) can be extended via plugins. A plugin is // just a program that reads a CodeGeneratorRequest from stdin and writes a // CodeGeneratorResponse to stdout. // // Plugins written using C++ can use google/protobuf/compiler/plugin.h instead // of dealing with the raw protocol defined here. // // A plugin executable needs only to be placed somewhere in the path. The // plugin should be named "protoc-gen-$NAME", and will then be used when the // flag "--${NAME}_out" is passed to protoc. syntax = "proto2"; package google.protobuf.compiler; option java_package = "com.google.protobuf.compiler"; option java_outer_classname = "PluginProtos"; option go_package = "google.golang.org/protobuf/types/pluginpb"; import "google/protobuf/descriptor.proto"; // The version number of protocol compiler. message Version { optional int32 major = 1; optional int32 minor = 2; optional int32 patch = 3; // A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should // be empty for mainline stable releases. optional string suffix = 4; } // An encoded CodeGeneratorRequest is written to the plugin's stdin. message CodeGeneratorRequest { // The .proto files that were explicitly listed on the command-line. The // code generator should generate code only for these files. Each file's // descriptor will be included in proto_file, below. repeated string file_to_generate = 1; // The generator parameter passed on the command-line. optional string parameter = 2; // FileDescriptorProtos for all files in files_to_generate and everything // they import. The files will appear in topological order, so each file // appears before any file that imports it. // // protoc guarantees that all proto_files will be written after // the fields above, even though this is not technically guaranteed by the // protobuf wire format. This theoretically could allow a plugin to stream // in the FileDescriptorProtos and handle them one by one rather than read // the entire set into memory at once. However, as of this writing, this // is not similarly optimized on protoc's end -- it will store all fields in // memory at once before sending them to the plugin. // // Type names of fields and extensions in the FileDescriptorProto are always // fully qualified. repeated FileDescriptorProto proto_file = 15; // The version number of protocol compiler. optional Version compiler_version = 3; } // The plugin writes an encoded CodeGeneratorResponse to stdout. message CodeGeneratorResponse { // Error message. If non-empty, code generation failed. The plugin process // should exit with status code zero even if it reports an error in this way. // // This should be used to indicate errors in .proto files which prevent the // code generator from generating correct code. Errors which indicate a // problem in protoc itself -- such as the input CodeGeneratorRequest being // unparseable -- should be reported by writing a message to stderr and // exiting with a non-zero status code. optional string error = 1; // A bitmask of supported features that the code generator supports. // This is a bitwise "or" of values from the Feature enum. optional uint64 supported_features = 2; // Sync with code_generator.h. enum Feature { FEATURE_NONE = 0; FEATURE_PROTO3_OPTIONAL = 1; } // Represents a single generated file. message File { // The file name, relative to the output directory. The name must not // contain "." or ".." components and must be relative, not be absolute (so, // the file cannot lie outside the output directory). "/" must be used as // the path separator, not "\". // // If the name is omitted, the content will be appended to the previous // file. This allows the generator to break large files into small chunks, // and allows the generated text to be streamed back to protoc so that large // files need not reside completely in memory at one time. Note that as of // this writing protoc does not optimize for this -- it will read the entire // CodeGeneratorResponse before writing files to disk. optional string name = 1; // If non-empty, indicates that the named file should already exist, and the // content here is to be inserted into that file at a defined insertion // point. This feature allows a code generator to extend the output // produced by another code generator. The original generator may provide // insertion points by placing special annotations in the file that look // like: // @@protoc_insertion_point(NAME) // The annotation can have arbitrary text before and after it on the line, // which allows it to be placed in a comment. NAME should be replaced with // an identifier naming the point -- this is what other generators will use // as the insertion_point. Code inserted at this point will be placed // immediately above the line containing the insertion point (thus multiple // insertions to the same point will come out in the order they were added). // The double-@ is intended to make it unlikely that the generated code // could contain things that look like insertion points by accident. // // For example, the C++ code generator places the following line in the // .pb.h files that it generates: // // @@protoc_insertion_point(namespace_scope) // This line appears within the scope of the file's package namespace, but // outside of any particular class. Another plugin can then specify the // insertion_point "namespace_scope" to generate additional classes or // other declarations that should be placed in this scope. // // Note that if the line containing the insertion point begins with // whitespace, the same whitespace will be added to every line of the // inserted text. This is useful for languages like Python, where // indentation matters. In these languages, the insertion point comment // should be indented the same amount as any inserted code will need to be // in order to work correctly in that context. // // The code generator that generates the initial file and the one which // inserts into it must both run as part of a single invocation of protoc. // Code generators are executed in the order in which they appear on the // command line. // // If |insertion_point| is present, |name| must also be present. optional string insertion_point = 2; // The file contents. optional string content = 15; // Information describing the file content being inserted. If an insertion // point is used, this information will be appropriately offset and inserted // into the code generation metadata for the generated files. optional GeneratedCodeInfo generated_code_info = 16; } repeated File file = 15; } protobuf-codegen-pure-2.27.1/src/proto/google/protobuf/descriptor.proto000064400000000000000000001121210072674642500244670ustar 00000000000000// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: kenton@google.com (Kenton Varda) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. // // The messages in this file describe the definitions found in .proto files. // A valid .proto file can be translated directly to a FileDescriptorProto // without any other information (e.g. without reading its imports). syntax = "proto2"; package google.protobuf; option go_package = "google.golang.org/protobuf/types/descriptorpb"; option java_package = "com.google.protobuf"; option java_outer_classname = "DescriptorProtos"; option csharp_namespace = "Google.Protobuf.Reflection"; option objc_class_prefix = "GPB"; option cc_enable_arenas = true; // descriptor.proto must be optimized for speed because reflection-based // algorithms don't work during bootstrapping. option optimize_for = SPEED; // The protocol compiler can output a FileDescriptorSet containing the .proto // files it parses. message FileDescriptorSet { repeated FileDescriptorProto file = 1; } // Describes a complete .proto file. message FileDescriptorProto { optional string name = 1; // file name, relative to root of source tree optional string package = 2; // e.g. "foo", "foo.bar", etc. // Names of files imported by this file. repeated string dependency = 3; // Indexes of the public imported files in the dependency list above. repeated int32 public_dependency = 10; // Indexes of the weak imported files in the dependency list. // For Google-internal migration only. Do not use. repeated int32 weak_dependency = 11; // All top-level definitions in this file. repeated DescriptorProto message_type = 4; repeated EnumDescriptorProto enum_type = 5; repeated ServiceDescriptorProto service = 6; repeated FieldDescriptorProto extension = 7; optional FileOptions options = 8; // This field contains optional information about the original source code. // You may safely remove this entire field without harming runtime // functionality of the descriptors -- the information is needed only by // development tools. optional SourceCodeInfo source_code_info = 9; // The syntax of the proto file. // The supported values are "proto2" and "proto3". optional string syntax = 12; } // Describes a message type. message DescriptorProto { optional string name = 1; repeated FieldDescriptorProto field = 2; repeated FieldDescriptorProto extension = 6; repeated DescriptorProto nested_type = 3; repeated EnumDescriptorProto enum_type = 4; message ExtensionRange { optional int32 start = 1; // Inclusive. optional int32 end = 2; // Exclusive. optional ExtensionRangeOptions options = 3; } repeated ExtensionRange extension_range = 5; repeated OneofDescriptorProto oneof_decl = 8; optional MessageOptions options = 7; // Range of reserved tag numbers. Reserved tag numbers may not be used by // fields or extension ranges in the same message. Reserved ranges may // not overlap. message ReservedRange { optional int32 start = 1; // Inclusive. optional int32 end = 2; // Exclusive. } repeated ReservedRange reserved_range = 9; // Reserved field names, which may not be used by fields in the same message. // A given name may only be reserved once. repeated string reserved_name = 10; } message ExtensionRangeOptions { // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; } // Describes a field within a message. message FieldDescriptorProto { enum Type { // 0 is reserved for errors. // Order is weird for historical reasons. TYPE_DOUBLE = 1; TYPE_FLOAT = 2; // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if // negative values are likely. TYPE_INT64 = 3; TYPE_UINT64 = 4; // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if // negative values are likely. TYPE_INT32 = 5; TYPE_FIXED64 = 6; TYPE_FIXED32 = 7; TYPE_BOOL = 8; TYPE_STRING = 9; // Tag-delimited aggregate. // Group type is deprecated and not supported in proto3. However, Proto3 // implementations should still be able to parse the group wire format and // treat group fields as unknown fields. TYPE_GROUP = 10; TYPE_MESSAGE = 11; // Length-delimited aggregate. // New in version 2. TYPE_BYTES = 12; TYPE_UINT32 = 13; TYPE_ENUM = 14; TYPE_SFIXED32 = 15; TYPE_SFIXED64 = 16; TYPE_SINT32 = 17; // Uses ZigZag encoding. TYPE_SINT64 = 18; // Uses ZigZag encoding. } enum Label { // 0 is reserved for errors LABEL_OPTIONAL = 1; LABEL_REQUIRED = 2; LABEL_REPEATED = 3; } optional string name = 1; optional int32 number = 3; optional Label label = 4; // If type_name is set, this need not be set. If both this and type_name // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. optional Type type = 5; // For message and enum types, this is the name of the type. If the name // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping // rules are used to find the type (i.e. first the nested types within this // message are searched, then within the parent, on up to the root // namespace). optional string type_name = 6; // For extensions, this is the name of the type being extended. It is // resolved in the same manner as type_name. optional string extendee = 2; // For numeric types, contains the original text representation of the value. // For booleans, "true" or "false". // For strings, contains the default text contents (not escaped in any way). // For bytes, contains the C escaped value. All bytes >= 128 are escaped. // TODO(kenton): Base-64 encode? optional string default_value = 7; // If set, gives the index of a oneof in the containing type's oneof_decl // list. This field is a member of that oneof. optional int32 oneof_index = 9; // JSON name of this field. The value is set by protocol compiler. If the // user has set a "json_name" option on this field, that option's value // will be used. Otherwise, it's deduced from the field's name by converting // it to camelCase. optional string json_name = 10; optional FieldOptions options = 8; // If true, this is a proto3 "optional". When a proto3 field is optional, it // tracks presence regardless of field type. // // When proto3_optional is true, this field must be belong to a oneof to // signal to old proto3 clients that presence is tracked for this field. This // oneof is known as a "synthetic" oneof, and this field must be its sole // member (each proto3 optional field gets its own synthetic oneof). Synthetic // oneofs exist in the descriptor only, and do not generate any API. Synthetic // oneofs must be ordered after all "real" oneofs. // // For message fields, proto3_optional doesn't create any semantic change, // since non-repeated message fields always track presence. However it still // indicates the semantic detail of whether the user wrote "optional" or not. // This can be useful for round-tripping the .proto file. For consistency we // give message fields a synthetic oneof also, even though it is not required // to track presence. This is especially important because the parser can't // tell if a field is a message or an enum, so it must always create a // synthetic oneof. // // Proto2 optional fields do not set this flag, because they already indicate // optional with `LABEL_OPTIONAL`. optional bool proto3_optional = 17; } // Describes a oneof. message OneofDescriptorProto { optional string name = 1; optional OneofOptions options = 2; } // Describes an enum type. message EnumDescriptorProto { optional string name = 1; repeated EnumValueDescriptorProto value = 2; optional EnumOptions options = 3; // Range of reserved numeric values. Reserved values may not be used by // entries in the same enum. Reserved ranges may not overlap. // // Note that this is distinct from DescriptorProto.ReservedRange in that it // is inclusive such that it can appropriately represent the entire int32 // domain. message EnumReservedRange { optional int32 start = 1; // Inclusive. optional int32 end = 2; // Inclusive. } // Range of reserved numeric values. Reserved numeric values may not be used // by enum values in the same enum declaration. Reserved ranges may not // overlap. repeated EnumReservedRange reserved_range = 4; // Reserved enum value names, which may not be reused. A given name may only // be reserved once. repeated string reserved_name = 5; } // Describes a value within an enum. message EnumValueDescriptorProto { optional string name = 1; optional int32 number = 2; optional EnumValueOptions options = 3; } // Describes a service. message ServiceDescriptorProto { optional string name = 1; repeated MethodDescriptorProto method = 2; optional ServiceOptions options = 3; } // Describes a method of a service. message MethodDescriptorProto { optional string name = 1; // Input and output type names. These are resolved in the same way as // FieldDescriptorProto.type_name, but must refer to a message type. optional string input_type = 2; optional string output_type = 3; optional MethodOptions options = 4; // Identifies if client streams multiple client messages optional bool client_streaming = 5 [default = false]; // Identifies if server streams multiple server messages optional bool server_streaming = 6 [default = false]; } // =================================================================== // Options // Each of the definitions above may have "options" attached. These are // just annotations which may cause code to be generated slightly differently // or may contain hints for code that manipulates protocol messages. // // Clients may define custom options as extensions of the *Options messages. // These extensions may not yet be known at parsing time, so the parser cannot // store the values in them. Instead it stores them in a field in the *Options // message called uninterpreted_option. This field must have the same name // across all *Options messages. We then use this field to populate the // extensions when we build a descriptor, at which point all protos have been // parsed and so all extensions are known. // // Extension numbers for custom options may be chosen as follows: // * For options which will only be used within a single application or // organization, or for experimental options, use field numbers 50000 // through 99999. It is up to you to ensure that you do not use the // same number for multiple options. // * For options which will be published and used publicly by multiple // independent entities, e-mail protobuf-global-extension-registry@google.com // to reserve extension numbers. Simply provide your project name (e.g. // Objective-C plugin) and your project website (if available) -- there's no // need to explain how you intend to use them. Usually you only need one // extension number. You can declare multiple options with only one extension // number by putting them in a sub-message. See the Custom Options section of // the docs for examples: // https://developers.google.com/protocol-buffers/docs/proto#options // If this turns out to be popular, a web service will be set up // to automatically assign option numbers. message FileOptions { // Sets the Java package where classes generated from this .proto will be // placed. By default, the proto package is used, but this is often // inappropriate because proto packages do not normally start with backwards // domain names. optional string java_package = 1; // If set, all the classes from the .proto file are wrapped in a single // outer class with the given name. This applies to both Proto1 // (equivalent to the old "--one_java_file" option) and Proto2 (where // a .proto always translates to a single class, but you may want to // explicitly choose the class name). optional string java_outer_classname = 8; // If set true, then the Java code generator will generate a separate .java // file for each top-level message, enum, and service defined in the .proto // file. Thus, these types will *not* be nested inside the outer class // named by java_outer_classname. However, the outer class will still be // generated to contain the file's getDescriptor() method as well as any // top-level extensions defined in the file. optional bool java_multiple_files = 10 [default = false]; // This option does nothing. optional bool java_generate_equals_and_hash = 20 [deprecated=true]; // If set true, then the Java2 code generator will generate code that // throws an exception whenever an attempt is made to assign a non-UTF-8 // byte sequence to a string field. // Message reflection will do the same. // However, an extension field still accepts non-UTF-8 byte sequences. // This option has no effect on when used with the lite runtime. optional bool java_string_check_utf8 = 27 [default = false]; // Generated classes can be optimized for speed or code size. enum OptimizeMode { SPEED = 1; // Generate complete code for parsing, serialization, // etc. CODE_SIZE = 2; // Use ReflectionOps to implement these methods. LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime. } optional OptimizeMode optimize_for = 9 [default = SPEED]; // Sets the Go package where structs generated from this .proto will be // placed. If omitted, the Go package will be derived from the following: // - The basename of the package import path, if provided. // - Otherwise, the package statement in the .proto file, if present. // - Otherwise, the basename of the .proto file, without extension. optional string go_package = 11; // Should generic services be generated in each language? "Generic" services // are not specific to any particular RPC system. They are generated by the // main code generators in each language (without additional plugins). // Generic services were the only kind of service generation supported by // early versions of google.protobuf. // // Generic services are now considered deprecated in favor of using plugins // that generate code specific to your particular RPC system. Therefore, // these default to false. Old code which depends on generic services should // explicitly set them to true. optional bool cc_generic_services = 16 [default = false]; optional bool java_generic_services = 17 [default = false]; optional bool py_generic_services = 18 [default = false]; optional bool php_generic_services = 42 [default = false]; // Is this file deprecated? // Depending on the target platform, this can emit Deprecated annotations // for everything in the file, or it will be completely ignored; in the very // least, this is a formalization for deprecating files. optional bool deprecated = 23 [default = false]; // Enables the use of arenas for the proto messages in this file. This applies // only to generated classes for C++. optional bool cc_enable_arenas = 31 [default = true]; // Sets the objective c class prefix which is prepended to all objective c // generated classes from this .proto. There is no default. optional string objc_class_prefix = 36; // Namespace for generated classes; defaults to the package. optional string csharp_namespace = 37; // By default Swift generators will take the proto package and CamelCase it // replacing '.' with underscore and use that to prefix the types/symbols // defined. When this options is provided, they will use this value instead // to prefix the types/symbols defined. optional string swift_prefix = 39; // Sets the php class prefix which is prepended to all php generated classes // from this .proto. Default is empty. optional string php_class_prefix = 40; // Use this option to change the namespace of php generated classes. Default // is empty. When this option is empty, the package name will be used for // determining the namespace. optional string php_namespace = 41; // Use this option to change the namespace of php generated metadata classes. // Default is empty. When this option is empty, the proto file name will be // used for determining the namespace. optional string php_metadata_namespace = 44; // Use this option to change the package of ruby generated classes. Default // is empty. When this option is not set, the package name will be used for // determining the ruby package. optional string ruby_package = 45; // The parser stores options it doesn't recognize here. // See the documentation for the "Options" section above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. // See the documentation for the "Options" section above. extensions 1000 to max; reserved 38; } message MessageOptions { // Set true to use the old proto1 MessageSet wire format for extensions. // This is provided for backwards-compatibility with the MessageSet wire // format. You should not use this for any other reason: It's less // efficient, has fewer features, and is more complicated. // // The message must be defined exactly as follows: // message Foo { // option message_set_wire_format = true; // extensions 4 to max; // } // Note that the message cannot have any defined fields; MessageSets only // have extensions. // // All extensions of your type must be singular messages; e.g. they cannot // be int32s, enums, or repeated messages. // // Because this is an option, the above two restrictions are not enforced by // the protocol compiler. optional bool message_set_wire_format = 1 [default = false]; // Disables the generation of the standard "descriptor()" accessor, which can // conflict with a field of the same name. This is meant to make migration // from proto1 easier; new code should avoid fields named "descriptor". optional bool no_standard_descriptor_accessor = 2 [default = false]; // Is this message deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the message, or it will be completely ignored; in the very least, // this is a formalization for deprecating messages. optional bool deprecated = 3 [default = false]; // Whether the message is an automatically generated map entry type for the // maps field. // // For maps fields: // map map_field = 1; // The parsed descriptor looks like: // message MapFieldEntry { // option map_entry = true; // optional KeyType key = 1; // optional ValueType value = 2; // } // repeated MapFieldEntry map_field = 1; // // Implementations may choose not to generate the map_entry=true message, but // use a native map in the target language to hold the keys and values. // The reflection APIs in such implementations still need to work as // if the field is a repeated message field. // // NOTE: Do not set the option in .proto files. Always use the maps syntax // instead. The option should only be implicitly set by the proto compiler // parser. optional bool map_entry = 7; reserved 8; // javalite_serializable reserved 9; // javanano_as_lite // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; } message FieldOptions { // The ctype option instructs the C++ code generator to use a different // representation of the field than it normally would. See the specific // options below. This option is not yet implemented in the open source // release -- sorry, we'll try to include it in a future version! optional CType ctype = 1 [default = STRING]; enum CType { // Default mode. STRING = 0; CORD = 1; STRING_PIECE = 2; } // The packed option can be enabled for repeated primitive fields to enable // a more efficient representation on the wire. Rather than repeatedly // writing the tag and type for each element, the entire array is encoded as // a single length-delimited blob. In proto3, only explicit setting it to // false will avoid using packed encoding. optional bool packed = 2; // The jstype option determines the JavaScript type used for values of the // field. The option is permitted only for 64 bit integral and fixed types // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING // is represented as JavaScript string, which avoids loss of precision that // can happen when a large value is converted to a floating point JavaScript. // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to // use the JavaScript "number" type. The behavior of the default option // JS_NORMAL is implementation dependent. // // This option is an enum to permit additional types to be added, e.g. // goog.math.Integer. optional JSType jstype = 6 [default = JS_NORMAL]; enum JSType { // Use the default type. JS_NORMAL = 0; // Use JavaScript strings. JS_STRING = 1; // Use JavaScript numbers. JS_NUMBER = 2; } // Should this field be parsed lazily? Lazy applies only to message-type // fields. It means that when the outer message is initially parsed, the // inner message's contents will not be parsed but instead stored in encoded // form. The inner message will actually be parsed when it is first accessed. // // This is only a hint. Implementations are free to choose whether to use // eager or lazy parsing regardless of the value of this option. However, // setting this option true suggests that the protocol author believes that // using lazy parsing on this field is worth the additional bookkeeping // overhead typically needed to implement it. // // This option does not affect the public interface of any generated code; // all method signatures remain the same. Furthermore, thread-safety of the // interface is not affected by this option; const methods remain safe to // call from multiple threads concurrently, while non-const methods continue // to require exclusive access. // // // Note that implementations may choose not to check required fields within // a lazy sub-message. That is, calling IsInitialized() on the outer message // may return true even if the inner message has missing required fields. // This is necessary because otherwise the inner message would have to be // parsed in order to perform the check, defeating the purpose of lazy // parsing. An implementation which chooses not to check required fields // must be consistent about it. That is, for any particular sub-message, the // implementation must either *always* check its required fields, or *never* // check its required fields, regardless of whether or not the message has // been parsed. optional bool lazy = 5 [default = false]; // Is this field deprecated? // Depending on the target platform, this can emit Deprecated annotations // for accessors, or it will be completely ignored; in the very least, this // is a formalization for deprecating fields. optional bool deprecated = 3 [default = false]; // For Google-internal migration only. Do not use. optional bool weak = 10 [default = false]; // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; reserved 4; // removed jtype } message OneofOptions { // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; } message EnumOptions { // Set this option to true to allow mapping different tag names to the same // value. optional bool allow_alias = 2; // Is this enum deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the enum, or it will be completely ignored; in the very least, this // is a formalization for deprecating enums. optional bool deprecated = 3 [default = false]; reserved 5; // javanano_as_lite // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; } message EnumValueOptions { // Is this enum value deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the enum value, or it will be completely ignored; in the very least, // this is a formalization for deprecating enum values. optional bool deprecated = 1 [default = false]; // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; } message ServiceOptions { // Note: Field numbers 1 through 32 are reserved for Google's internal RPC // framework. We apologize for hoarding these numbers to ourselves, but // we were already using them long before we decided to release Protocol // Buffers. // Is this service deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the service, or it will be completely ignored; in the very least, // this is a formalization for deprecating services. optional bool deprecated = 33 [default = false]; // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; } message MethodOptions { // Note: Field numbers 1 through 32 are reserved for Google's internal RPC // framework. We apologize for hoarding these numbers to ourselves, but // we were already using them long before we decided to release Protocol // Buffers. // Is this method deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the method, or it will be completely ignored; in the very least, // this is a formalization for deprecating methods. optional bool deprecated = 33 [default = false]; // Is this method side-effect-free (or safe in HTTP parlance), or idempotent, // or neither? HTTP based RPC implementation may choose GET verb for safe // methods, and PUT verb for idempotent methods instead of the default POST. enum IdempotencyLevel { IDEMPOTENCY_UNKNOWN = 0; NO_SIDE_EFFECTS = 1; // implies idempotent IDEMPOTENT = 2; // idempotent, but may have side effects } optional IdempotencyLevel idempotency_level = 34 [default = IDEMPOTENCY_UNKNOWN]; // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; } // A message representing a option the parser does not recognize. This only // appears in options protos created by the compiler::Parser class. // DescriptorPool resolves these when building Descriptor objects. Therefore, // options protos in descriptor objects (e.g. returned by Descriptor::options(), // or produced by Descriptor::CopyTo()) will never have UninterpretedOptions // in them. message UninterpretedOption { // The name of the uninterpreted option. Each string represents a segment in // a dot-separated name. is_extension is true iff a segment represents an // extension (denoted with parentheses in options specs in .proto files). // E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents // "foo.(bar.baz).qux". message NamePart { required string name_part = 1; required bool is_extension = 2; } repeated NamePart name = 2; // The value of the uninterpreted option, in whatever type the tokenizer // identified it as during parsing. Exactly one of these should be set. optional string identifier_value = 3; optional uint64 positive_int_value = 4; optional int64 negative_int_value = 5; optional double double_value = 6; optional bytes string_value = 7; optional string aggregate_value = 8; } // =================================================================== // Optional source code info // Encapsulates information about the original source file from which a // FileDescriptorProto was generated. message SourceCodeInfo { // A Location identifies a piece of source code in a .proto file which // corresponds to a particular definition. This information is intended // to be useful to IDEs, code indexers, documentation generators, and similar // tools. // // For example, say we have a file like: // message Foo { // optional string foo = 1; // } // Let's look at just the field definition: // optional string foo = 1; // ^ ^^ ^^ ^ ^^^ // a bc de f ghi // We have the following locations: // span path represents // [a,i) [ 4, 0, 2, 0 ] The whole field definition. // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). // // Notes: // - A location may refer to a repeated field itself (i.e. not to any // particular index within it). This is used whenever a set of elements are // logically enclosed in a single code segment. For example, an entire // extend block (possibly containing multiple extension definitions) will // have an outer location whose path refers to the "extensions" repeated // field without an index. // - Multiple locations may have the same path. This happens when a single // logical declaration is spread out across multiple places. The most // obvious example is the "extend" block again -- there may be multiple // extend blocks in the same scope, each of which will have the same path. // - A location's span is not always a subset of its parent's span. For // example, the "extendee" of an extension declaration appears at the // beginning of the "extend" block and is shared by all extensions within // the block. // - Just because a location's span is a subset of some other location's span // does not mean that it is a descendant. For example, a "group" defines // both a type and a field in a single declaration. Thus, the locations // corresponding to the type and field and their components will overlap. // - Code which tries to interpret locations should probably be designed to // ignore those that it doesn't understand, as more types of locations could // be recorded in the future. repeated Location location = 1; message Location { // Identifies which part of the FileDescriptorProto was defined at this // location. // // Each element is a field number or an index. They form a path from // the root FileDescriptorProto to the place where the definition. For // example, this path: // [ 4, 3, 2, 7, 1 ] // refers to: // file.message_type(3) // 4, 3 // .field(7) // 2, 7 // .name() // 1 // This is because FileDescriptorProto.message_type has field number 4: // repeated DescriptorProto message_type = 4; // and DescriptorProto.field has field number 2: // repeated FieldDescriptorProto field = 2; // and FieldDescriptorProto.name has field number 1: // optional string name = 1; // // Thus, the above path gives the location of a field name. If we removed // the last element: // [ 4, 3, 2, 7 ] // this path refers to the whole field declaration (from the beginning // of the label to the terminating semicolon). repeated int32 path = 1 [packed = true]; // Always has exactly three or four elements: start line, start column, // end line (optional, otherwise assumed same as start line), end column. // These are packed into a single field for efficiency. Note that line // and column numbers are zero-based -- typically you will want to add // 1 to each before displaying to a user. repeated int32 span = 2 [packed = true]; // If this SourceCodeInfo represents a complete declaration, these are any // comments appearing before and after the declaration which appear to be // attached to the declaration. // // A series of line comments appearing on consecutive lines, with no other // tokens appearing on those lines, will be treated as a single comment. // // leading_detached_comments will keep paragraphs of comments that appear // before (but not connected to) the current element. Each paragraph, // separated by empty lines, will be one comment element in the repeated // field. // // Only the comment content is provided; comment markers (e.g. //) are // stripped out. For block comments, leading whitespace and an asterisk // will be stripped from the beginning of each line other than the first. // Newlines are included in the output. // // Examples: // // optional int32 foo = 1; // Comment attached to foo. // // Comment attached to bar. // optional int32 bar = 2; // // optional string baz = 3; // // Comment attached to baz. // // Another line attached to baz. // // // Comment attached to qux. // // // // Another line attached to qux. // optional double qux = 4; // // // Detached comment for corge. This is not leading or trailing comments // // to qux or corge because there are blank lines separating it from // // both. // // // Detached comment for corge paragraph 2. // // optional string corge = 5; // /* Block comment attached // * to corge. Leading asterisks // * will be removed. */ // /* Block comment attached to // * grault. */ // optional int32 grault = 6; // // // ignored detached comments. optional string leading_comments = 3; optional string trailing_comments = 4; repeated string leading_detached_comments = 6; } } // Describes the relationship between generated code and its original source // file. A GeneratedCodeInfo message is associated with only one generated // source file, but may contain references to different source .proto files. message GeneratedCodeInfo { // An Annotation connects some span of text in generated code to an element // of its generating .proto file. repeated Annotation annotation = 1; message Annotation { // Identifies the element in the original source .proto file. This field // is formatted the same as SourceCodeInfo.Location.path. repeated int32 path = 1 [packed = true]; // Identifies the filesystem path to the original source .proto. optional string source_file = 2; // Identifies the starting offset in bytes in the generated code // that relates to the identified object. optional int32 begin = 3; // Identifies the ending offset in bytes in the generated code that // relates to the identified offset. The end offset should be one past // the last relevant byte (so the length of the text = end - begin). optional int32 end = 4; } } protobuf-codegen-pure-2.27.1/src/proto/google/protobuf/duration.proto000064400000000000000000000114370072674642500241460ustar 00000000000000// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto3"; package google.protobuf; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option cc_enable_arenas = true; option go_package = "google.golang.org/protobuf/types/known/durationpb"; option java_package = "com.google.protobuf"; option java_outer_classname = "DurationProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; // A Duration represents a signed, fixed-length span of time represented // as a count of seconds and fractions of seconds at nanosecond // resolution. It is independent of any calendar and concepts like "day" // or "month". It is related to Timestamp in that the difference between // two Timestamp values is a Duration and it can be added or subtracted // from a Timestamp. Range is approximately +-10,000 years. // // # Examples // // Example 1: Compute Duration from two Timestamps in pseudo code. // // Timestamp start = ...; // Timestamp end = ...; // Duration duration = ...; // // duration.seconds = end.seconds - start.seconds; // duration.nanos = end.nanos - start.nanos; // // if (duration.seconds < 0 && duration.nanos > 0) { // duration.seconds += 1; // duration.nanos -= 1000000000; // } else if (duration.seconds > 0 && duration.nanos < 0) { // duration.seconds -= 1; // duration.nanos += 1000000000; // } // // Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. // // Timestamp start = ...; // Duration duration = ...; // Timestamp end = ...; // // end.seconds = start.seconds + duration.seconds; // end.nanos = start.nanos + duration.nanos; // // if (end.nanos < 0) { // end.seconds -= 1; // end.nanos += 1000000000; // } else if (end.nanos >= 1000000000) { // end.seconds += 1; // end.nanos -= 1000000000; // } // // Example 3: Compute Duration from datetime.timedelta in Python. // // td = datetime.timedelta(days=3, minutes=10) // duration = Duration() // duration.FromTimedelta(td) // // # JSON Mapping // // In JSON format, the Duration type is encoded as a string rather than an // object, where the string ends in the suffix "s" (indicating seconds) and // is preceded by the number of seconds, with nanoseconds expressed as // fractional seconds. For example, 3 seconds with 0 nanoseconds should be // encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should // be expressed in JSON format as "3.000000001s", and 3 seconds and 1 // microsecond should be expressed in JSON format as "3.000001s". // // message Duration { // Signed seconds of the span of time. Must be from -315,576,000,000 // to +315,576,000,000 inclusive. Note: these bounds are computed from: // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years int64 seconds = 1; // Signed fractions of a second at nanosecond resolution of the span // of time. Durations less than one second are represented with a 0 // `seconds` field and a positive or negative `nanos` field. For durations // of one second or more, a non-zero value for the `nanos` field must be // of the same sign as the `seconds` field. Must be from -999,999,999 // to +999,999,999 inclusive. int32 nanos = 2; } protobuf-codegen-pure-2.27.1/src/proto/google/protobuf/empty.proto000064400000000000000000000045750072674642500234640ustar 00000000000000// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto3"; package google.protobuf; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option go_package = "google.golang.org/protobuf/types/known/emptypb"; option java_package = "com.google.protobuf"; option java_outer_classname = "EmptyProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; option cc_enable_arenas = true; // A generic empty message that you can re-use to avoid defining duplicated // empty messages in your APIs. A typical example is to use it as the request // or the response type of an API method. For instance: // // service Foo { // rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); // } // // The JSON representation for `Empty` is empty JSON object `{}`. message Empty {} protobuf-codegen-pure-2.27.1/src/proto/google/protobuf/field_mask.proto000064400000000000000000000177710072674642500244260ustar 00000000000000// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto3"; package google.protobuf; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option java_package = "com.google.protobuf"; option java_outer_classname = "FieldMaskProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; option go_package = "google.golang.org/protobuf/types/known/fieldmaskpb"; option cc_enable_arenas = true; // `FieldMask` represents a set of symbolic field paths, for example: // // paths: "f.a" // paths: "f.b.d" // // Here `f` represents a field in some root message, `a` and `b` // fields in the message found in `f`, and `d` a field found in the // message in `f.b`. // // Field masks are used to specify a subset of fields that should be // returned by a get operation or modified by an update operation. // Field masks also have a custom JSON encoding (see below). // // # Field Masks in Projections // // When used in the context of a projection, a response message or // sub-message is filtered by the API to only contain those fields as // specified in the mask. For example, if the mask in the previous // example is applied to a response message as follows: // // f { // a : 22 // b { // d : 1 // x : 2 // } // y : 13 // } // z: 8 // // The result will not contain specific values for fields x,y and z // (their value will be set to the default, and omitted in proto text // output): // // // f { // a : 22 // b { // d : 1 // } // } // // A repeated field is not allowed except at the last position of a // paths string. // // If a FieldMask object is not present in a get operation, the // operation applies to all fields (as if a FieldMask of all fields // had been specified). // // Note that a field mask does not necessarily apply to the // top-level response message. In case of a REST get operation, the // field mask applies directly to the response, but in case of a REST // list operation, the mask instead applies to each individual message // in the returned resource list. In case of a REST custom method, // other definitions may be used. Where the mask applies will be // clearly documented together with its declaration in the API. In // any case, the effect on the returned resource/resources is required // behavior for APIs. // // # Field Masks in Update Operations // // A field mask in update operations specifies which fields of the // targeted resource are going to be updated. The API is required // to only change the values of the fields as specified in the mask // and leave the others untouched. If a resource is passed in to // describe the updated values, the API ignores the values of all // fields not covered by the mask. // // If a repeated field is specified for an update operation, new values will // be appended to the existing repeated field in the target resource. Note that // a repeated field is only allowed in the last position of a `paths` string. // // If a sub-message is specified in the last position of the field mask for an // update operation, then new value will be merged into the existing sub-message // in the target resource. // // For example, given the target message: // // f { // b { // d: 1 // x: 2 // } // c: [1] // } // // And an update message: // // f { // b { // d: 10 // } // c: [2] // } // // then if the field mask is: // // paths: ["f.b", "f.c"] // // then the result will be: // // f { // b { // d: 10 // x: 2 // } // c: [1, 2] // } // // An implementation may provide options to override this default behavior for // repeated and message fields. // // In order to reset a field's value to the default, the field must // be in the mask and set to the default value in the provided resource. // Hence, in order to reset all fields of a resource, provide a default // instance of the resource and set all fields in the mask, or do // not provide a mask as described below. // // If a field mask is not present on update, the operation applies to // all fields (as if a field mask of all fields has been specified). // Note that in the presence of schema evolution, this may mean that // fields the client does not know and has therefore not filled into // the request will be reset to their default. If this is unwanted // behavior, a specific service may require a client to always specify // a field mask, producing an error if not. // // As with get operations, the location of the resource which // describes the updated values in the request message depends on the // operation kind. In any case, the effect of the field mask is // required to be honored by the API. // // ## Considerations for HTTP REST // // The HTTP kind of an update operation which uses a field mask must // be set to PATCH instead of PUT in order to satisfy HTTP semantics // (PUT must only be used for full updates). // // # JSON Encoding of Field Masks // // In JSON, a field mask is encoded as a single string where paths are // separated by a comma. Fields name in each path are converted // to/from lower-camel naming conventions. // // As an example, consider the following message declarations: // // message Profile { // User user = 1; // Photo photo = 2; // } // message User { // string display_name = 1; // string address = 2; // } // // In proto a field mask for `Profile` may look as such: // // mask { // paths: "user.display_name" // paths: "photo" // } // // In JSON, the same mask is represented as below: // // { // mask: "user.displayName,photo" // } // // # Field Masks and Oneof Fields // // Field masks treat fields in oneofs just as regular fields. Consider the // following message: // // message SampleMessage { // oneof test_oneof { // string name = 4; // SubMessage sub_message = 9; // } // } // // The field mask can be: // // mask { // paths: "name" // } // // Or: // // mask { // paths: "sub_message" // } // // Note that oneof type names ("test_oneof" in this case) cannot be used in // paths. // // ## Field Mask Verification // // The implementation of any API method which has a FieldMask type field in the // request should verify the included field paths, and return an // `INVALID_ARGUMENT` error if any path is unmappable. message FieldMask { // The set of field mask paths. repeated string paths = 1; } protobuf-codegen-pure-2.27.1/src/proto/google/protobuf/source_context.proto000064400000000000000000000044450072674642500253660ustar 00000000000000// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto3"; package google.protobuf; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option java_package = "com.google.protobuf"; option java_outer_classname = "SourceContextProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; option go_package = "google.golang.org/protobuf/types/known/sourcecontextpb"; // `SourceContext` represents information about the source of a // protobuf element, like the file in which it is defined. message SourceContext { // The path-qualified name of the .proto file that contained the associated // protobuf element. For example: `"google/protobuf/source_context.proto"`. string file_name = 1; } protobuf-codegen-pure-2.27.1/src/proto/google/protobuf/struct.proto000064400000000000000000000073020072674642500236410ustar 00000000000000// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto3"; package google.protobuf; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option cc_enable_arenas = true; option go_package = "google.golang.org/protobuf/types/known/structpb"; option java_package = "com.google.protobuf"; option java_outer_classname = "StructProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; // `Struct` represents a structured data value, consisting of fields // which map to dynamically typed values. In some languages, `Struct` // might be supported by a native representation. For example, in // scripting languages like JS a struct is represented as an // object. The details of that representation are described together // with the proto support for the language. // // The JSON representation for `Struct` is JSON object. message Struct { // Unordered map of dynamically typed values. map fields = 1; } // `Value` represents a dynamically typed value which can be either // null, a number, a string, a boolean, a recursive struct value, or a // list of values. A producer of value is expected to set one of that // variants, absence of any variant indicates an error. // // The JSON representation for `Value` is JSON value. message Value { // The kind of value. oneof kind { // Represents a null value. NullValue null_value = 1; // Represents a double value. double number_value = 2; // Represents a string value. string string_value = 3; // Represents a boolean value. bool bool_value = 4; // Represents a structured value. Struct struct_value = 5; // Represents a repeated `Value`. ListValue list_value = 6; } } // `NullValue` is a singleton enumeration to represent the null value for the // `Value` type union. // // The JSON representation for `NullValue` is JSON `null`. enum NullValue { // Null value. NULL_VALUE = 0; } // `ListValue` is a wrapper around a repeated field of values. // // The JSON representation for `ListValue` is JSON array. message ListValue { // Repeated field of dynamically typed values. repeated Value values = 1; } protobuf-codegen-pure-2.27.1/src/proto/google/protobuf/timestamp.proto000064400000000000000000000144730072674642500243270ustar 00000000000000// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto3"; package google.protobuf; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option cc_enable_arenas = true; option go_package = "google.golang.org/protobuf/types/known/timestamppb"; option java_package = "com.google.protobuf"; option java_outer_classname = "TimestampProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; // A Timestamp represents a point in time independent of any time zone or local // calendar, encoded as a count of seconds and fractions of seconds at // nanosecond resolution. The count is relative to an epoch at UTC midnight on // January 1, 1970, in the proleptic Gregorian calendar which extends the // Gregorian calendar backwards to year one. // // All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap // second table is needed for interpretation, using a [24-hour linear // smear](https://developers.google.com/time/smear). // // The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By // restricting to that range, we ensure that we can convert to and from [RFC // 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings. // // # Examples // // Example 1: Compute Timestamp from POSIX `time()`. // // Timestamp timestamp; // timestamp.set_seconds(time(NULL)); // timestamp.set_nanos(0); // // Example 2: Compute Timestamp from POSIX `gettimeofday()`. // // struct timeval tv; // gettimeofday(&tv, NULL); // // Timestamp timestamp; // timestamp.set_seconds(tv.tv_sec); // timestamp.set_nanos(tv.tv_usec * 1000); // // Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. // // FILETIME ft; // GetSystemTimeAsFileTime(&ft); // UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; // // // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z // // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. // Timestamp timestamp; // timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); // timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); // // Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. // // long millis = System.currentTimeMillis(); // // Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) // .setNanos((int) ((millis % 1000) * 1000000)).build(); // // // Example 5: Compute Timestamp from Java `Instant.now()`. // // Instant now = Instant.now(); // // Timestamp timestamp = // Timestamp.newBuilder().setSeconds(now.getEpochSecond()) // .setNanos(now.getNano()).build(); // // // Example 6: Compute Timestamp from current time in Python. // // timestamp = Timestamp() // timestamp.GetCurrentTime() // // # JSON Mapping // // In JSON format, the Timestamp type is encoded as a string in the // [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the // format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" // where {year} is always expressed using four digits while {month}, {day}, // {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional // seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), // are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone // is required. A proto3 JSON serializer should always use UTC (as indicated by // "Z") when printing the Timestamp type and a proto3 JSON parser should be // able to accept both UTC and other timezones (as indicated by an offset). // // For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past // 01:30 UTC on January 15, 2017. // // In JavaScript, one can convert a Date object to this format using the // standard // [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) // method. In Python, a standard `datetime.datetime` object can be converted // to this format using // [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with // the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use // the Joda Time's [`ISODateTimeFormat.dateTime()`]( // http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D // ) to obtain a formatter capable of generating timestamps in this format. // // message Timestamp { // Represents seconds of UTC time since Unix epoch // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to // 9999-12-31T23:59:59Z inclusive. int64 seconds = 1; // Non-negative fractions of a second at nanosecond resolution. Negative // second values with fractions must still have non-negative nanos values // that count forward in time. Must be from 0 to 999,999,999 // inclusive. int32 nanos = 2; } protobuf-codegen-pure-2.27.1/src/proto/google/protobuf/type.proto000064400000000000000000000137560072674642500233100ustar 00000000000000// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. syntax = "proto3"; package google.protobuf; import "google/protobuf/any.proto"; import "google/protobuf/source_context.proto"; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option cc_enable_arenas = true; option java_package = "com.google.protobuf"; option java_outer_classname = "TypeProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; option go_package = "google.golang.org/protobuf/types/known/typepb"; // A protocol buffer message type. message Type { // The fully qualified message name. string name = 1; // The list of fields. repeated Field fields = 2; // The list of types appearing in `oneof` definitions in this type. repeated string oneofs = 3; // The protocol buffer options. repeated Option options = 4; // The source context. SourceContext source_context = 5; // The source syntax. Syntax syntax = 6; } // A single field of a message type. message Field { // Basic field types. enum Kind { // Field type unknown. TYPE_UNKNOWN = 0; // Field type double. TYPE_DOUBLE = 1; // Field type float. TYPE_FLOAT = 2; // Field type int64. TYPE_INT64 = 3; // Field type uint64. TYPE_UINT64 = 4; // Field type int32. TYPE_INT32 = 5; // Field type fixed64. TYPE_FIXED64 = 6; // Field type fixed32. TYPE_FIXED32 = 7; // Field type bool. TYPE_BOOL = 8; // Field type string. TYPE_STRING = 9; // Field type group. Proto2 syntax only, and deprecated. TYPE_GROUP = 10; // Field type message. TYPE_MESSAGE = 11; // Field type bytes. TYPE_BYTES = 12; // Field type uint32. TYPE_UINT32 = 13; // Field type enum. TYPE_ENUM = 14; // Field type sfixed32. TYPE_SFIXED32 = 15; // Field type sfixed64. TYPE_SFIXED64 = 16; // Field type sint32. TYPE_SINT32 = 17; // Field type sint64. TYPE_SINT64 = 18; } // Whether a field is optional, required, or repeated. enum Cardinality { // For fields with unknown cardinality. CARDINALITY_UNKNOWN = 0; // For optional fields. CARDINALITY_OPTIONAL = 1; // For required fields. Proto2 syntax only. CARDINALITY_REQUIRED = 2; // For repeated fields. CARDINALITY_REPEATED = 3; } // The field type. Kind kind = 1; // The field cardinality. Cardinality cardinality = 2; // The field number. int32 number = 3; // The field name. string name = 4; // The field type URL, without the scheme, for message or enumeration // types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`. string type_url = 6; // The index of the field type in `Type.oneofs`, for message or enumeration // types. The first type has index 1; zero means the type is not in the list. int32 oneof_index = 7; // Whether to use alternative packed wire representation. bool packed = 8; // The protocol buffer options. repeated Option options = 9; // The field JSON name. string json_name = 10; // The string value of the default value of this field. Proto2 syntax only. string default_value = 11; } // Enum type definition. message Enum { // Enum type name. string name = 1; // Enum value definitions. repeated EnumValue enumvalue = 2; // Protocol buffer options. repeated Option options = 3; // The source context. SourceContext source_context = 4; // The source syntax. Syntax syntax = 5; } // Enum value definition. message EnumValue { // Enum value name. string name = 1; // Enum value number. int32 number = 2; // Protocol buffer options. repeated Option options = 3; } // A protocol buffer option, which can be attached to a message, field, // enumeration, etc. message Option { // The option's name. For protobuf built-in options (options defined in // descriptor.proto), this is the short name. For example, `"map_entry"`. // For custom options, it should be the fully-qualified name. For example, // `"google.api.http"`. string name = 1; // The option's value packed in an Any message. If the value is a primitive, // the corresponding wrapper type defined in google/protobuf/wrappers.proto // should be used. If the value is an enum, it should be stored as an int32 // value using the google.protobuf.Int32Value type. Any value = 2; } // The syntax in which a protocol buffer element is defined. enum Syntax { // Syntax `proto2`. SYNTAX_PROTO2 = 0; // Syntax `proto3`. SYNTAX_PROTO3 = 1; } protobuf-codegen-pure-2.27.1/src/proto/google/protobuf/wrappers.proto000064400000000000000000000077120072674642500241650ustar 00000000000000// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Wrappers for primitive (non-message) types. These types are useful // for embedding primitives in the `google.protobuf.Any` type and for places // where we need to distinguish between the absence of a primitive // typed field and its default value. // // These wrappers have no meaningful use within repeated fields as they lack // the ability to detect presence on individual elements. // These wrappers have no meaningful use within a map or a oneof since // individual entries of a map or fields of a oneof can already detect presence. syntax = "proto3"; package google.protobuf; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option cc_enable_arenas = true; option go_package = "google.golang.org/protobuf/types/known/wrapperspb"; option java_package = "com.google.protobuf"; option java_outer_classname = "WrappersProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; // Wrapper message for `double`. // // The JSON representation for `DoubleValue` is JSON number. message DoubleValue { // The double value. double value = 1; } // Wrapper message for `float`. // // The JSON representation for `FloatValue` is JSON number. message FloatValue { // The float value. float value = 1; } // Wrapper message for `int64`. // // The JSON representation for `Int64Value` is JSON string. message Int64Value { // The int64 value. int64 value = 1; } // Wrapper message for `uint64`. // // The JSON representation for `UInt64Value` is JSON string. message UInt64Value { // The uint64 value. uint64 value = 1; } // Wrapper message for `int32`. // // The JSON representation for `Int32Value` is JSON number. message Int32Value { // The int32 value. int32 value = 1; } // Wrapper message for `uint32`. // // The JSON representation for `UInt32Value` is JSON number. message UInt32Value { // The uint32 value. uint32 value = 1; } // Wrapper message for `bool`. // // The JSON representation for `BoolValue` is JSON `true` and `false`. message BoolValue { // The bool value. bool value = 1; } // Wrapper message for `string`. // // The JSON representation for `StringValue` is JSON string. message StringValue { // The string value. string value = 1; } // Wrapper message for `bytes`. // // The JSON representation for `BytesValue` is JSON string. message BytesValue { // The bytes value. bytes value = 1; } protobuf-codegen-pure-2.27.1/src/proto/rustproto.proto000064400000000000000000000046540072674642500212710ustar 00000000000000syntax = "proto2"; import "google/protobuf/descriptor.proto"; // see https://github.com/gogo/protobuf/blob/master/gogoproto/gogo.proto // for the original idea package rustproto; extend google.protobuf.FileOptions { // When true, oneof field is generated public optional bool expose_oneof_all = 17001; // When true all fields are public, and not accessors generated optional bool expose_fields_all = 17003; // When false, `get_`, `set_`, `mut_` etc. accessors are not generated optional bool generate_accessors_all = 17004; // Use `bytes::Bytes` for `bytes` fields optional bool carllerche_bytes_for_bytes_all = 17011; // Use `bytes::Bytes` for `string` fields optional bool carllerche_bytes_for_string_all = 17012; // Use `serde_derive` to implement `Serialize` and `Deserialize` optional bool serde_derive_all = 17030; // Guard serde annotations with cfg attr. optional string serde_derive_cfg_all = 17031; // When true, will only generate codes that works with lite runtime. optional bool lite_runtime_all = 17035; } extend google.protobuf.MessageOptions { // When true, oneof field is generated public optional bool expose_oneof = 17001; // When true all fields are public, and not accessors generated optional bool expose_fields = 17003; // When false, `get_`, `set_`, `mut_` etc. accessors are not generated optional bool generate_accessors = 17004; // Use `bytes::Bytes` for `bytes` fields optional bool carllerche_bytes_for_bytes = 17011; // Use `bytes::Bytes` for `string` fields optional bool carllerche_bytes_for_string = 17012; // Use `serde_derive` to implement `Serialize` and `Deserialize` optional bool serde_derive = 17030; // Guard serde annotations with cfg attr. optional string serde_derive_cfg = 17031; } extend google.protobuf.FieldOptions { // When true all fields are public, and not accessors generated optional bool expose_fields_field = 17003; // When false, `get_`, `set_`, `mut_` etc. accessors are not generated optional bool generate_accessors_field = 17004; // Use `bytes::Bytes` for `bytes` fields optional bool carllerche_bytes_for_bytes_field = 17011; // Use `bytes::Bytes` for `string` fields optional bool carllerche_bytes_for_string_field = 17012; } extend google.protobuf.EnumOptions { // use rename_all attribute for serde optional string serde_rename_all = 17032; } protobuf-codegen-pure-2.27.1/src/test_against_protobuf_protos.rs000064400000000000000000000014730072674642500233350ustar 00000000000000use std::fs; use std::io::Read; use std::path::Path; use model; fn parse_recursively(path: &Path) { let file_name = path .file_name() .expect("file_name") .to_str() .expect("to_str"); if path.is_dir() { for entry in fs::read_dir(path).expect("read_dir") { parse_recursively(&entry.expect("entry").path()); } } else if file_name.ends_with(".proto") { println!("checking {}", path.display()); let mut content = String::new(); fs::File::open(path) .expect("open") .read_to_string(&mut content) .expect("read"); model::FileDescriptor::parse(&content).expect("parse"); } } #[test] fn test() { let path = &Path::new("../google-protobuf"); parse_recursively(&Path::new(path)); } protobuf-codegen-pure-2.27.1/tests/bundled_proto_consistent.rs000064400000000000000000000033210072674642500230000ustar 00000000000000use std::fs; use std::path::Path; use std::path::PathBuf; fn list_dir(p: &Path) -> Vec { let mut children = fs::read_dir(p) .unwrap() .map(|r| r.map(|e| e.path())) .collect::, _>>() .unwrap(); children.sort(); children } fn assert_equal_recursively(a: &Path, b: &Path) { assert_eq!(a.is_dir(), b.is_dir()); assert_eq!(a.is_file(), b.is_file()); if a.is_dir() { let mut a_contents = list_dir(a).into_iter(); let mut b_contents = list_dir(b).into_iter(); loop { let a_child = a_contents.next(); let b_child = b_contents.next(); match (a_child, b_child) { (Some(a_child), Some(b_child)) => { assert_eq!(a_child.file_name(), b_child.file_name()); assert_equal_recursively(&a_child, &b_child); } (None, None) => break, _ => panic!( "mismatched directories: {} and {}", a.display(), b.display() ), } } } else { let a_contents = fs::read(a).unwrap(); let b_contents = fs::read(b).unwrap(); assert_eq!(a_contents, b_contents); } } #[test] fn test_bundled_google_proto_files_consistent() { let source = "../protoc-bin-vendored/include/google"; let our_copy = "src/proto/google"; assert_equal_recursively(Path::new(source), Path::new(our_copy)); } #[test] fn test_bundled_rustproto_proto_consistent() { let source = "../proto/rustproto.proto"; let our_copy = "src/proto/rustproto.proto"; assert_equal_recursively(Path::new(source), Path::new(our_copy)); }