1use crate::{
318 Error, Result,
319 constants::{
320 BOOLEAN_FALSE, BOOLEAN_TRUE, CUSTOM_OPTION_MIN_FIELD_NUMBER, DEFAULT_RECURSION_LIMIT,
321 EDITION_2023, FEATURE_ENUM_TYPE, FEATURE_FIELD_PRESENCE, FEATURE_JSON_FORMAT,
322 FEATURE_MESSAGE_ENCODING, FEATURE_REPEATED_ENCODING, FEATURE_UTF8_VALIDATION,
323 HARDENED_SCHEMA_MAX_NESTING_DEPTH, HARDENED_SCHEMA_MAX_REGISTRY_FILES,
324 HARDENED_SCHEMA_MAX_SOURCE_BYTES, HARDENED_SCHEMA_MAX_TOKENS, KW_EDITION, KW_ENUM,
325 KW_EXTEND, KW_EXTENSIONS, KW_GROUP, KW_IMPORT, KW_MAP, KW_MAX, KW_MESSAGE, KW_ONEOF,
326 KW_OPTION, KW_OPTIONAL, KW_PACKAGE, KW_PUBLIC, KW_REPEATED, KW_REQUIRED, KW_RESERVED,
327 KW_RETURNS, KW_RPC, KW_SERVICE, KW_STREAM, KW_SYNTAX, KW_TO, KW_WEAK,
328 LONG_UNICODE_ESCAPE_DIGITS, MAX_FIELD_NUMBER, MIN_FIELD_NUMBER, OPTION_ALLOW_ALIAS,
329 OPTION_DEFAULT, OPTION_PACKED, RESERVED_FIELD_NUMBER_END, RESERVED_FIELD_NUMBER_START,
330 SHORT_UNICODE_ESCAPE_DIGITS, SYNTAX_PROTO2, SYNTAX_PROTO3, TYPE_BOOL, TYPE_BYTES,
331 TYPE_DOUBLE, TYPE_FIXED32, TYPE_FIXED64, TYPE_FLOAT, TYPE_INT32, TYPE_INT64, TYPE_SFIXED32,
332 TYPE_SFIXED64, TYPE_SINT32, TYPE_SINT64, TYPE_STRING, TYPE_UINT32, TYPE_UINT64,
333 },
334};
335use alloc::{
336 boxed::Box,
337 collections::BTreeMap,
338 format,
339 string::{String, ToString},
340 vec::Vec,
341};
342use pest::{Parser as _, error::InputLocation};
343
344#[derive(pest_derive::Parser)]
346#[grammar = "proto.pest"]
347struct ProtoSyntaxParser;
348
349fn pest_error(error: pest::error::Error<Rule>) -> Error {
351 let offset = match error.location {
352 InputLocation::Pos(offset) | InputLocation::Span((offset, _)) => offset,
353 };
354 Error::new(offset, error.to_string())
355}
356
357fn validate_pest_syntax(source: &str) -> Result<()> {
359 ProtoSyntaxParser::parse(Rule::proto_file, source)
360 .map(|_| ())
361 .map_err(pest_error)
362}
363
364#[derive(Clone, Copy, Debug, Eq, PartialEq)]
366pub enum Syntax {
367 Proto2,
369 Proto3,
371 Edition2023,
373}
374
375impl Syntax {
376 const fn has_modern_defaults(self) -> bool {
378 matches!(self, Self::Proto3 | Self::Edition2023)
379 }
380
381 const fn is_edition(self) -> bool {
383 matches!(self, Self::Edition2023)
384 }
385}
386
387#[derive(Clone, Copy, Debug, Eq, PartialEq)]
389pub enum FieldPresence {
390 Explicit,
392 Implicit,
394 LegacyRequired,
396}
397
398#[derive(Clone, Copy, Debug, Eq, PartialEq)]
400pub enum EnumType {
401 Open,
403 Closed,
405}
406
407#[derive(Clone, Copy, Debug, Eq, PartialEq)]
409pub enum RepeatedFieldEncoding {
410 Packed,
412 Expanded,
414}
415
416#[derive(Clone, Copy, Debug, Eq, PartialEq)]
418pub enum MessageEncoding {
419 LengthPrefixed,
421 Delimited,
423}
424
425#[derive(Clone, Copy, Debug, Eq, PartialEq)]
427pub enum Utf8Validation {
428 Verify,
430 None,
432}
433
434#[derive(Clone, Copy, Debug, Eq, PartialEq)]
436pub enum JsonFormat {
437 Allow,
439 LegacyBestEffort,
441}
442
443#[derive(Clone, Copy, Debug, Eq, PartialEq)]
445pub struct FeatureSet {
446 pub field_presence: FieldPresence,
448 pub enum_type: EnumType,
450 pub repeated_field_encoding: RepeatedFieldEncoding,
452 pub message_encoding: MessageEncoding,
454 pub utf8_validation: Utf8Validation,
456 pub json_format: JsonFormat,
458}
459
460impl FeatureSet {
461 pub const fn for_syntax(syntax: Syntax) -> Self {
463 match syntax {
464 Syntax::Proto2 => Self {
465 field_presence: FieldPresence::Explicit,
466 enum_type: EnumType::Closed,
467 repeated_field_encoding: RepeatedFieldEncoding::Expanded,
468 message_encoding: MessageEncoding::LengthPrefixed,
469 utf8_validation: Utf8Validation::Verify,
470 json_format: JsonFormat::LegacyBestEffort,
471 },
472 Syntax::Proto3 => Self {
473 field_presence: FieldPresence::Implicit,
474 enum_type: EnumType::Open,
475 repeated_field_encoding: RepeatedFieldEncoding::Packed,
476 message_encoding: MessageEncoding::LengthPrefixed,
477 utf8_validation: Utf8Validation::Verify,
478 json_format: JsonFormat::Allow,
479 },
480 Syntax::Edition2023 => Self {
481 field_presence: FieldPresence::Explicit,
482 enum_type: EnumType::Open,
483 repeated_field_encoding: RepeatedFieldEncoding::Packed,
484 message_encoding: MessageEncoding::LengthPrefixed,
485 utf8_validation: Utf8Validation::Verify,
486 json_format: JsonFormat::Allow,
487 },
488 }
489 }
490}
491#[derive(Clone, Copy, Debug, Eq, PartialEq)]
493pub enum Cardinality {
494 Optional,
496 Required,
498 Repeated,
500}
501#[derive(Clone, Debug, Eq, PartialEq)]
503pub enum FieldType {
504 Double,
506 Float,
508 Int32,
510 Int64,
512 Uint32,
514 Uint64,
516 Sint32,
518 Sint64,
520 Fixed32,
522 Fixed64,
524 Sfixed32,
526 Sfixed64,
528 Bool,
530 String,
532 Bytes,
534 Message(String),
536 Enum(String),
538 Map(Box<FieldType>, Box<FieldType>),
540}
541#[derive(Clone, Debug, Eq, PartialEq)]
543pub struct Field {
544 pub name: String,
546 pub number: u32,
548 pub cardinality: Cardinality,
550 pub kind: FieldType,
552 pub packed: Option<bool>,
554 pub packed_explicit: bool,
556 pub oneof: Option<String>,
558 pub explicit_presence: bool,
561 pub default: Option<String>,
563 pub options: Vec<OptionSetting>,
565 pub features: FeatureSet,
567}
568#[derive(Clone, Debug, Eq, PartialEq)]
570pub struct MessageDescriptor {
571 pub name: String,
573 pub full_name: String,
575 pub fields: Vec<Field>,
577 pub extension_ranges: Vec<(u32, u32)>,
579 pub oneofs: Vec<OneofDescriptor>,
581 pub options: Vec<OptionSetting>,
583 pub features: FeatureSet,
585}
586impl MessageDescriptor {
587 pub fn field_by_number(&self, number: u32) -> Option<&Field> {
589 self.fields.iter().find(|field| field.number == number)
590 }
591 pub fn field_by_name(&self, name: &str) -> Option<&Field> {
593 self.fields.iter().find(|field| field.name == name)
594 }
595}
596impl Field {
597 pub fn json_name(&self) -> String {
599 field_json_name(self)
600 }
601}
602#[derive(Clone, Debug, Eq, PartialEq)]
604pub struct EnumValue {
605 pub name: String,
607 pub number: i32,
609 pub options: Vec<OptionSetting>,
611}
612#[derive(Clone, Debug, Eq, PartialEq)]
614pub struct Enum {
615 pub name: String,
617 pub full_name: String,
619 pub values: Vec<EnumValue>,
621 pub syntax: Syntax,
623 pub options: Vec<OptionSetting>,
625 pub features: FeatureSet,
627}
628#[derive(Clone, Debug, Eq, PartialEq)]
630pub struct OptionSetting {
631 pub name: String,
633 pub value: String,
635 pub value_kind: OptionValueKind,
637}
638#[derive(Clone, Copy, Debug, Eq, PartialEq)]
640pub enum OptionValueKind {
641 Identifier,
643 String,
645 Number,
647 Aggregate,
649}
650#[derive(Clone, Debug, Eq, PartialEq)]
652pub struct OneofDescriptor {
653 pub name: String,
655 pub options: Vec<OptionSetting>,
657}
658#[derive(Clone, Debug, Eq, PartialEq)]
660pub struct MethodDescriptor {
661 pub name: String,
663 pub input_type: String,
665 pub output_type: String,
667 pub client_streaming: bool,
669 pub server_streaming: bool,
671 pub options: Vec<OptionSetting>,
673}
674#[derive(Clone, Debug, Eq, PartialEq)]
676pub struct ServiceDescriptor {
677 pub name: String,
679 pub full_name: String,
681 pub methods: Vec<MethodDescriptor>,
683 pub options: Vec<OptionSetting>,
685}
686#[derive(Clone, Debug, Eq, PartialEq)]
688pub struct CustomOptionDescriptor {
689 pub name: String,
691 pub full_name: String,
693 pub extendee: String,
695 pub field: Field,
697}
698#[derive(Clone, Debug, Eq, PartialEq)]
700pub struct ExtensionDescriptor {
701 pub full_name: String,
703 pub extendee: String,
705 pub field: Field,
707}
708#[derive(Clone, Copy, Debug, Eq, PartialEq)]
710pub enum ImportKind {
711 Normal,
713 Public,
715 Weak,
717}
718#[derive(Clone, Debug, Eq, PartialEq)]
720pub struct Import {
721 pub path: String,
723 pub kind: ImportKind,
725}
726#[derive(Clone, Debug)]
728pub struct Schema {
729 pub syntax: Syntax,
731 pub package: Option<String>,
733 pub messages: BTreeMap<String, MessageDescriptor>,
735 pub enums: BTreeMap<String, Enum>,
737 pub services: BTreeMap<String, ServiceDescriptor>,
739 pub custom_options: BTreeMap<String, CustomOptionDescriptor>,
741 pub extensions: BTreeMap<String, ExtensionDescriptor>,
743 pub imports: Vec<Import>,
745 pub options: Vec<OptionSetting>,
747 pub features: FeatureSet,
749}
750
751#[derive(Clone, Debug, Default)]
758pub struct Registry {
759 sources: BTreeMap<String, String>,
760}
761
762#[derive(Clone, Copy, Debug, Eq, PartialEq)]
764pub struct SchemaParseOptions {
765 pub max_source_bytes: usize,
767 pub max_tokens: usize,
769 pub max_nesting_depth: usize,
771 pub max_registry_files: usize,
773}
774
775impl Default for SchemaParseOptions {
776 fn default() -> Self {
777 Self {
778 max_source_bytes: usize::MAX,
779 max_tokens: usize::MAX,
780 max_nesting_depth: DEFAULT_RECURSION_LIMIT,
781 max_registry_files: usize::MAX,
782 }
783 }
784}
785
786impl SchemaParseOptions {
787 pub const fn hardened() -> Self {
789 Self {
790 max_source_bytes: HARDENED_SCHEMA_MAX_SOURCE_BYTES,
791 max_tokens: HARDENED_SCHEMA_MAX_TOKENS,
792 max_nesting_depth: HARDENED_SCHEMA_MAX_NESTING_DEPTH,
793 max_registry_files: HARDENED_SCHEMA_MAX_REGISTRY_FILES,
794 }
795 }
796}
797
798impl Registry {
799 pub const fn new() -> Self {
801 Self {
802 sources: BTreeMap::new(),
803 }
804 }
805
806 pub fn register(
811 &mut self,
812 path: impl Into<String>,
813 source: impl Into<String>,
814 ) -> Option<String> {
815 self.sources.insert(path.into(), source.into())
816 }
817
818 pub fn source(&self, path: &str) -> Option<&str> {
820 self.sources.get(path).map(String::as_str)
821 }
822
823 pub fn parse(&self, root: &str) -> Result<Schema> {
833 self.parse_with_options(root, &SchemaParseOptions::default())
834 }
835
836 pub fn parse_with_options(&self, root: &str, options: &SchemaParseOptions) -> Result<Schema> {
838 parse_registry(root, self, options)
839 }
840
841 pub fn len(&self) -> usize {
843 self.sources.len()
844 }
845
846 pub fn is_empty(&self) -> bool {
848 self.sources.is_empty()
849 }
850}
851impl Schema {
852 pub fn field_by_number<'a>(
854 &'a self,
855 message: &'a MessageDescriptor,
856 number: u32,
857 ) -> Option<&'a Field> {
858 message.field_by_number(number).or_else(|| {
859 self.extensions
860 .values()
861 .find(|extension| {
862 extension.extendee == message.full_name && extension.field.number == number
863 })
864 .map(|extension| &extension.field)
865 })
866 }
867
868 pub fn fields_for<'a>(
870 &'a self,
871 message: &'a MessageDescriptor,
872 ) -> impl Iterator<Item = &'a Field> {
873 message.fields.iter().chain(
874 self.extensions
875 .values()
876 .filter(move |extension| extension.extendee == message.full_name)
877 .map(|extension| &extension.field),
878 )
879 }
880
881 pub fn message(&self, name: &str) -> Option<&MessageDescriptor> {
886 self.messages.get(name).or_else(|| {
887 self.package
888 .as_ref()
889 .and_then(|package| self.messages.get(&format!("{package}.{name}")))
890 })
891 }
892 pub fn service(&self, name: &str) -> Option<&ServiceDescriptor> {
894 self.services.get(name).or_else(|| {
895 self.package
896 .as_ref()
897 .and_then(|package| self.services.get(&format!("{package}.{name}")))
898 })
899 }
900}
901#[derive(Clone)]
903enum Token {
904 Identifier(String),
906 StringLiteral(String),
908 NumberLiteral(String),
910 Symbol(char),
912}
913
914fn is_identifier(value: &str) -> bool {
916 let mut bytes = value.bytes();
917 bytes
918 .next()
919 .is_some_and(|first| first.is_ascii_alphabetic() || first == b'_')
920 && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
921}
922
923fn is_full_identifier(value: &str, allow_leading_dot: bool) -> bool {
925 let value = if allow_leading_dot {
926 value.strip_prefix('.').unwrap_or(value)
927 } else {
928 value
929 };
930 !value.is_empty() && value.split('.').all(is_identifier)
931}
932
933#[derive(Default)]
935struct ReservedDeclarations {
936 names: Vec<String>,
937 ranges: Vec<(i64, i64)>,
938}
939
940fn validate_unicode_escapes(value: &str, offset: usize) -> Result<()> {
946 let bytes = value.as_bytes();
947 let mut cursor = 0;
948 while cursor < bytes.len() {
949 if bytes.get(cursor) != Some(&b'\\') {
950 cursor += 1;
951 continue;
952 }
953 let escape = bytes
954 .get(cursor + 1)
955 .ok_or_else(|| Error::new(offset, "truncated string escape"))?;
956 let digits = match escape {
957 b'u' => SHORT_UNICODE_ESCAPE_DIGITS,
958 b'U' => LONG_UNICODE_ESCAPE_DIGITS,
959 _ => {
960 cursor += 2;
961 continue;
962 }
963 };
964 let digits_start = cursor + 2;
965 let digits_end = digits_start
966 .checked_add(digits)
967 .ok_or_else(|| Error::new(offset, "Unicode escape length overflow"))?;
968 let hexadecimal = value
969 .get(digits_start..digits_end)
970 .ok_or_else(|| Error::new(offset, "truncated Unicode escape"))?;
971 let code_point = u32::from_str_radix(hexadecimal, 16)
972 .map_err(|_| Error::new(offset, "invalid Unicode escape"))?;
973 if char::from_u32(code_point).is_none() {
974 return Err(Error::new(offset, "invalid Unicode scalar value"));
975 }
976 cursor = digits_end;
977 }
978 Ok(())
979}
980
981fn lex(source: &str) -> Result<Vec<(Token, usize)>> {
987 let mut parsed = ProtoSyntaxParser::parse(Rule::token_stream, source).map_err(pest_error)?;
988 let stream = parsed
989 .next()
990 .ok_or_else(|| Error::new(0, "Pest returned no token stream"))?;
991 let mut tokens = Vec::new();
992 for pair in stream.into_inner() {
993 let offset = pair.as_span().start();
994 let text = pair.as_str();
995 let token = match pair.as_rule() {
996 Rule::lex_identifier => Token::Identifier(text.to_string()),
997 Rule::lex_number => Token::NumberLiteral(text.to_string()),
998 Rule::string_literal => {
999 let end = text
1000 .len()
1001 .checked_sub(1)
1002 .ok_or_else(|| Error::new(offset, "invalid Pest string span"))?;
1003 let contents = text
1004 .get(1..end)
1005 .ok_or_else(|| Error::new(offset, "invalid Pest string boundary"))?;
1006 validate_unicode_escapes(contents, offset)?;
1007 Token::StringLiteral(contents.to_string())
1008 }
1009 Rule::lex_symbol => {
1010 let symbol = text
1011 .chars()
1012 .next()
1013 .ok_or_else(|| Error::new(offset, "empty Pest symbol span"))?;
1014 Token::Symbol(symbol)
1015 }
1016 Rule::EOI => continue,
1017 _ => return Err(Error::new(offset, "unexpected Pest token rule")),
1018 };
1019 tokens.push((token, offset));
1020 }
1021 Ok(tokens)
1022}
1023struct DescriptorBuilder {
1025 tokens: Vec<(Token, usize)>,
1027 cursor: usize,
1029 syntax: Syntax,
1031 package: Option<String>,
1033 messages: BTreeMap<String, MessageDescriptor>,
1035 enums: BTreeMap<String, Enum>,
1037 services: BTreeMap<String, ServiceDescriptor>,
1039 custom_options: BTreeMap<String, CustomOptionDescriptor>,
1041 extensions: BTreeMap<String, ExtensionDescriptor>,
1043 imports: Vec<Import>,
1045 options: Vec<OptionSetting>,
1047}
1048impl DescriptorBuilder {
1049 fn offset(&self) -> usize {
1051 self.tokens
1052 .get(self.cursor)
1053 .map(|token| token.1)
1054 .unwrap_or(0)
1055 }
1056 fn peek_identifier(&self, expected: &str) -> bool {
1058 matches!(self.tokens.get(self.cursor),Some((Token::Identifier(value),_))if value==expected)
1059 }
1060 fn peek_symbol(&self, expected: char) -> bool {
1062 matches!(self.tokens.get(self.cursor),Some((Token::Symbol(value),_))if *value==expected)
1063 }
1064 fn identifier(&mut self) -> Result<String> {
1066 match self.tokens.get(self.cursor).cloned() {
1067 Some((Token::Identifier(value), _)) => {
1068 self.cursor += 1;
1069 Ok(value)
1070 }
1071 _ => Err(Error::new(self.offset(), "expected identifier")),
1072 }
1073 }
1074 fn declaration_name(&mut self) -> Result<String> {
1076 let offset = self.offset();
1077 let name = self.identifier()?;
1078 if is_identifier(&name) {
1079 Ok(name)
1080 } else {
1081 Err(Error::new(offset, "invalid protobuf identifier"))
1082 }
1083 }
1084 fn package_name(&mut self) -> Result<String> {
1086 let offset = self.offset();
1087 let name = self.identifier()?;
1088 if is_full_identifier(&name, false) {
1089 Ok(name)
1090 } else {
1091 Err(Error::new(offset, "invalid protobuf package name"))
1092 }
1093 }
1094 fn integer(&mut self) -> Result<i64> {
1096 match self.tokens.get(self.cursor).cloned() {
1097 Some((Token::NumberLiteral(value), offset)) => {
1098 self.cursor += 1;
1099 let (negative, unsigned) = value
1100 .strip_prefix('-')
1101 .map_or((false, value.as_str()), |value| (true, value));
1102 let unsigned = unsigned.strip_prefix('+').unwrap_or(unsigned);
1103 let (digits, radix) = if let Some(digits) = unsigned
1104 .strip_prefix("0x")
1105 .or_else(|| unsigned.strip_prefix("0X"))
1106 {
1107 (digits, 16)
1108 } else if unsigned.len() > 1 && unsigned.starts_with('0') {
1109 (unsigned, 8)
1110 } else {
1111 (unsigned, 10)
1112 };
1113 let magnitude = i128::from_str_radix(digits, radix)
1114 .map_err(|_| Error::new(offset, "expected integer"))?;
1115 let signed = if negative {
1116 magnitude
1117 .checked_neg()
1118 .ok_or_else(|| Error::new(offset, "integer is out of range"))?
1119 } else {
1120 magnitude
1121 };
1122 i64::try_from(signed).map_err(|_| Error::new(offset, "integer is out of range"))
1123 }
1124 _ => Err(Error::new(self.offset(), "expected integer")),
1125 }
1126 }
1127 fn expect_symbol(&mut self, expected: char) -> Result<()> {
1129 if matches!(self.tokens.get(self.cursor),Some((Token::Symbol(value),_))if *value==expected)
1130 {
1131 self.cursor += 1;
1132 Ok(())
1133 } else {
1134 Err(Error::new(self.offset(), format!("expected '{expected}'")))
1135 }
1136 }
1137 fn consume_symbol(&mut self, expected: char) -> bool {
1139 self.expect_symbol(expected).is_ok()
1140 }
1141 fn qualify(&self, scope: &str, name: &str) -> String {
1143 if let Some(name) = name.strip_prefix('.') {
1144 name.to_string()
1145 } else if scope.is_empty() {
1146 self.package
1147 .as_ref()
1148 .map(|package| format!("{package}.{name}"))
1149 .unwrap_or_else(|| name.to_string())
1150 } else {
1151 format!("{scope}.{name}")
1152 }
1153 }
1154 fn option_value(&mut self) -> Result<String> {
1156 match self.tokens.get(self.cursor).cloned() {
1157 Some((Token::StringLiteral(mut value), _)) => {
1158 self.cursor += 1;
1159 while let Some((Token::StringLiteral(next), _)) = self.tokens.get(self.cursor) {
1160 value.push_str(next);
1161 self.cursor += 1;
1162 }
1163 Ok(value)
1164 }
1165 Some((Token::Identifier(value), _)) | Some((Token::NumberLiteral(value), _)) => {
1166 self.cursor += 1;
1167 Ok(value)
1168 }
1169 _ => Err(Error::new(self.offset(), "expected option value")),
1170 }
1171 }
1172
1173 fn option_name(&mut self) -> Result<String> {
1175 if !self.consume_symbol('(') {
1176 return self.identifier();
1177 }
1178 let extension = self.identifier()?;
1179 self.expect_symbol(')')?;
1180 let mut name = format!("({extension})");
1181 while let Some((Token::Identifier(component), _)) = self.tokens.get(self.cursor) {
1182 let Some(component) = component.strip_prefix('.') else {
1183 break;
1184 };
1185 if !is_identifier(component) {
1186 return Err(Error::new(self.offset(), "invalid custom option path"));
1187 }
1188 name.push('.');
1189 name.push_str(component);
1190 self.cursor += 1;
1191 }
1192 Ok(name)
1193 }
1194
1195 fn aggregate_option_value(&mut self) -> Result<String> {
1197 self.expect_symbol('{')?;
1198 let mut value = String::from("{");
1199 let mut depth = 1usize;
1200 while depth != 0 {
1201 let (token, _) = self
1202 .tokens
1203 .get(self.cursor)
1204 .cloned()
1205 .ok_or_else(|| Error::new(self.offset(), "unterminated aggregate option"))?;
1206 self.cursor += 1;
1207 match token {
1208 Token::Symbol('{') => {
1209 depth += 1;
1210 value.push('{');
1211 }
1212 Token::Symbol('}') => {
1213 depth -= 1;
1214 value.push('}');
1215 }
1216 Token::Symbol(symbol) => value.push(symbol),
1217 Token::Identifier(text) | Token::NumberLiteral(text) => value.push_str(&text),
1218 Token::StringLiteral(text) => {
1219 value.push('"');
1220 value.push_str(&text);
1221 value.push('"');
1222 }
1223 }
1224 }
1225 Ok(value)
1226 }
1227
1228 fn option_setting(&mut self) -> Result<OptionSetting> {
1230 let name = self.option_name()?;
1231 self.expect_symbol('=')?;
1232 let (value, value_kind) = if self.peek_symbol('{') {
1233 (self.aggregate_option_value()?, OptionValueKind::Aggregate)
1234 } else {
1235 let value_kind = match self.tokens.get(self.cursor) {
1236 Some((Token::StringLiteral(_), _)) => OptionValueKind::String,
1237 Some((Token::NumberLiteral(_), _)) => OptionValueKind::Number,
1238 Some((Token::Identifier(_), _)) => OptionValueKind::Identifier,
1239 _ => return Err(Error::new(self.offset(), "expected option value")),
1240 };
1241 (self.option_value()?, value_kind)
1242 };
1243 Ok(OptionSetting {
1244 name,
1245 value,
1246 value_kind,
1247 })
1248 }
1249
1250 fn option_declaration(&mut self) -> Result<OptionSetting> {
1252 self.identifier()?;
1253 let option = self.option_setting()?;
1254 self.expect_symbol(';')?;
1255 Ok(option)
1256 }
1257
1258 fn parse_reserved(&mut self, minimum: i64, maximum: i64) -> Result<ReservedDeclarations> {
1260 self.identifier()?;
1261 let mut reserved = ReservedDeclarations::default();
1262 let names = matches!(
1263 self.tokens.get(self.cursor),
1264 Some((Token::StringLiteral(_), _))
1265 ) || (self.syntax.is_edition()
1266 && matches!(
1267 self.tokens.get(self.cursor),
1268 Some((Token::Identifier(_), _))
1269 ));
1270 loop {
1271 if names {
1272 let offset = self.offset();
1273 let name = match self.tokens.get(self.cursor).cloned() {
1274 Some((Token::StringLiteral(name), _)) => {
1275 self.cursor += 1;
1276 name
1277 }
1278 Some((Token::Identifier(name), _)) if self.syntax.is_edition() => {
1279 self.cursor += 1;
1280 name
1281 }
1282 _ => return Err(Error::new(offset, "cannot mix reserved names and numbers")),
1283 };
1284 if !is_identifier(&name) {
1285 return Err(Error::new(offset, "invalid reserved field name"));
1286 }
1287 reserved.names.push(name);
1288 } else {
1289 let start = self.integer()?;
1290 let end = if self.peek_identifier(KW_TO) {
1291 self.identifier()?;
1292 if self.peek_identifier(KW_MAX) {
1293 self.identifier()?;
1294 maximum
1295 } else {
1296 self.integer()?
1297 }
1298 } else {
1299 start
1300 };
1301 if start < minimum || start > end || end > maximum {
1302 return Err(Error::new(self.offset(), "invalid reserved numeric range"));
1303 }
1304 reserved.ranges.push((start, end));
1305 }
1306 if !self.consume_symbol(',') {
1307 break;
1308 }
1309 }
1310 self.expect_symbol(';')?;
1311 Ok(reserved)
1312 }
1313
1314 fn skip_group(&mut self) -> Result<()> {
1319 self.identifier()?;
1320 self.identifier()?;
1321 self.expect_symbol('=')?;
1322 self.integer()?;
1323 self.expect_symbol('{')?;
1324 let mut depth = 1usize;
1325 while depth != 0 {
1326 match self.tokens.get(self.cursor) {
1327 Some((Token::Symbol('{'), _)) => depth += 1,
1328 Some((Token::Symbol('}'), _)) => depth -= 1,
1329 Some(_) => {}
1330 None => return Err(Error::new(self.offset(), "unterminated group")),
1331 }
1332 self.cursor += 1;
1333 }
1334 self.consume_symbol(';');
1335 Ok(())
1336 }
1337 fn parse_enum(&mut self, scope: &str) -> Result<()> {
1342 self.identifier()?;
1343 let name = self.declaration_name()?;
1344 let full_name = self.qualify(scope, &name);
1345 self.expect_symbol('{')?;
1346 let mut values = Vec::new();
1347 let mut reserved = ReservedDeclarations::default();
1348 let mut allow_alias = false;
1349 let mut options = Vec::new();
1350 while !self.consume_symbol('}') {
1351 if self.consume_symbol(';') {
1352 continue;
1353 }
1354 if self.peek_identifier(KW_RESERVED) {
1355 let declaration = self.parse_reserved(i64::from(i32::MIN), i64::from(i32::MAX))?;
1356 reserved.names.extend(declaration.names);
1357 reserved.ranges.extend(declaration.ranges);
1358 continue;
1359 }
1360 if self.peek_identifier(KW_OPTION) {
1361 let option = self.option_declaration()?;
1362 if option.name == OPTION_ALLOW_ALIAS {
1363 allow_alias = match option.value.as_str() {
1364 BOOLEAN_TRUE => true,
1365 BOOLEAN_FALSE => false,
1366 _ => {
1367 return Err(Error::new(
1368 self.offset(),
1369 "allow_alias must be true or false",
1370 ));
1371 }
1372 };
1373 }
1374 options.push(option);
1375 continue;
1376 }
1377 let value_name = self.declaration_name()?;
1378 self.expect_symbol('=')?;
1379 let raw_number = self.integer()?;
1380 let number = i32::try_from(raw_number)
1381 .map_err(|_| Error::new(self.offset(), "enum value is outside int32 range"))?;
1382 let mut value_options = Vec::new();
1383 if self.consume_symbol('[') {
1384 loop {
1385 if self.consume_symbol(']') {
1386 break;
1387 }
1388 value_options.push(self.option_setting()?);
1389 if !self.consume_symbol(']') {
1390 self.expect_symbol(',')?;
1391 } else {
1392 break;
1393 }
1394 }
1395 }
1396 self.expect_symbol(';')?;
1397 values.push(EnumValue {
1398 name: value_name,
1399 number,
1400 options: value_options,
1401 })
1402 }
1403 if values.is_empty() {
1404 return Err(Error::new(
1405 self.offset(),
1406 "enum must declare at least one value",
1407 ));
1408 }
1409 if self.syntax.has_modern_defaults()
1410 && values.first().is_some_and(|value| value.number != 0)
1411 {
1412 return Err(Error::new(
1413 self.offset(),
1414 "first proto3 enum value must be zero",
1415 ));
1416 }
1417 validate_reserved_declarations(&reserved, self.offset())?;
1418 for (index, value) in values.iter().enumerate() {
1419 if values[..index]
1420 .iter()
1421 .any(|previous| previous.name == value.name)
1422 {
1423 return Err(Error::new(self.offset(), "duplicate enum value name"));
1424 }
1425 if !allow_alias
1426 && values[..index]
1427 .iter()
1428 .any(|previous| previous.number == value.number)
1429 {
1430 return Err(Error::new(
1431 self.offset(),
1432 "duplicate enum number requires allow_alias = true",
1433 ));
1434 }
1435 if reserved.names.iter().any(|name| name == &value.name)
1436 || reserved
1437 .ranges
1438 .iter()
1439 .any(|(start, end)| (*start..=*end).contains(&i64::from(value.number)))
1440 {
1441 return Err(Error::new(
1442 self.offset(),
1443 "enum value uses a reserved name or number",
1444 ));
1445 }
1446 }
1447 if self.messages.contains_key(&full_name) || self.enums.contains_key(&full_name) {
1448 return Err(Error::new(self.offset(), "duplicate protobuf type name"));
1449 }
1450 self.enums.insert(
1451 full_name.clone(),
1452 Enum {
1453 name,
1454 full_name,
1455 values,
1456 syntax: self.syntax,
1457 options,
1458 features: FeatureSet::for_syntax(self.syntax),
1459 },
1460 );
1461 Ok(())
1462 }
1463 fn parse_message(&mut self, scope: &str) -> Result<()> {
1468 self.identifier()?;
1469 let name = self.declaration_name()?;
1470 let full_name = self.qualify(scope, &name);
1471 self.expect_symbol('{')?;
1472 let mut fields = Vec::new();
1473 let mut oneofs = Vec::<OneofDescriptor>::new();
1474 let mut reserved = ReservedDeclarations::default();
1475 let mut extension_ranges = Vec::new();
1476 let mut options = Vec::new();
1477 while !self.consume_symbol('}') {
1478 if self.consume_symbol(';') {
1479 continue;
1480 }
1481 if self.peek_identifier(KW_MESSAGE) {
1482 self.parse_message(&full_name)?;
1483 continue;
1484 }
1485 if self.peek_identifier(KW_ENUM) {
1486 self.parse_enum(&full_name)?;
1487 continue;
1488 }
1489 if self.peek_identifier(KW_ONEOF) {
1490 self.identifier()?;
1491 let oneof_name = self.declaration_name()?;
1492 if oneofs.iter().any(|oneof| oneof.name == oneof_name) {
1493 return Err(Error::new(self.offset(), "duplicate oneof name"));
1494 }
1495 self.expect_symbol('{')?;
1496 let mut oneof_options = Vec::new();
1497 while !self.consume_symbol('}') {
1498 if self.consume_symbol(';') {
1499 continue;
1500 }
1501 if self.peek_identifier(KW_OPTION) {
1502 oneof_options.push(self.option_declaration()?);
1503 continue;
1504 }
1505 fields.push(self.parse_field(Some(oneof_name.clone()), None)?)
1506 }
1507 oneofs.push(OneofDescriptor {
1508 name: oneof_name,
1509 options: oneof_options,
1510 });
1511 continue;
1512 }
1513 if self.peek_identifier(KW_RESERVED) {
1514 let declaration =
1515 self.parse_reserved(i64::from(MIN_FIELD_NUMBER), i64::from(MAX_FIELD_NUMBER))?;
1516 reserved.names.extend(declaration.names);
1517 reserved.ranges.extend(declaration.ranges);
1518 continue;
1519 }
1520 if self.peek_identifier(KW_OPTION) {
1521 options.push(self.option_declaration()?);
1522 continue;
1523 }
1524 if self.peek_identifier(KW_EXTEND) {
1525 self.parse_custom_option_extensions(&full_name)?;
1526 continue;
1527 }
1528 if self.peek_identifier(KW_EXTENSIONS) {
1529 if self.syntax == Syntax::Proto3 {
1530 return Err(Error::new(
1531 self.offset(),
1532 "proto3 extensions are permitted only for custom options",
1533 ));
1534 }
1535 let declaration =
1536 self.parse_reserved(i64::from(MIN_FIELD_NUMBER), i64::from(MAX_FIELD_NUMBER))?;
1537 for (start, end) in declaration.ranges {
1538 extension_ranges.push((start as u32, end as u32));
1539 }
1540 continue;
1541 }
1542 let cardinality = if self.peek_identifier(KW_REQUIRED) {
1543 if self.syntax.is_edition() {
1544 return Err(Error::new(
1545 self.offset(),
1546 "required labels are not used in Editions",
1547 ));
1548 }
1549 self.identifier()?;
1550 Some(Cardinality::Required)
1551 } else if self.peek_identifier(KW_OPTIONAL) {
1552 if self.syntax.is_edition() {
1553 return Err(Error::new(
1554 self.offset(),
1555 "optional labels are not used in Editions",
1556 ));
1557 }
1558 self.identifier()?;
1559 Some(Cardinality::Optional)
1560 } else if self.peek_identifier(KW_REPEATED) {
1561 self.identifier()?;
1562 Some(Cardinality::Repeated)
1563 } else {
1564 None
1565 };
1566 if self.peek_identifier(KW_GROUP) {
1567 if self.syntax == Syntax::Proto3 {
1568 return Err(Error::new(
1569 self.offset(),
1570 "groups are not allowed in proto3",
1571 ));
1572 }
1573 self.skip_group()?;
1574 continue;
1575 }
1576 fields.push(self.parse_field(None, cardinality)?)
1577 }
1578 let oneof_names: Vec<String> = oneofs.iter().map(|oneof| oneof.name.clone()).collect();
1579 validate_message_fields(&fields, &oneof_names, &reserved, self.offset())?;
1580 if self.syntax.has_modern_defaults() {
1581 validate_json_field_names(&fields, self.offset())?;
1582 }
1583 if self.messages.contains_key(&full_name) || self.enums.contains_key(&full_name) {
1584 return Err(Error::new(self.offset(), "duplicate protobuf type name"));
1585 }
1586 self.messages.insert(
1587 full_name.clone(),
1588 MessageDescriptor {
1589 name,
1590 full_name,
1591 fields,
1592 extension_ranges,
1593 oneofs,
1594 options,
1595 features: FeatureSet::for_syntax(self.syntax),
1596 },
1597 );
1598 Ok(())
1599 }
1600
1601 fn parse_custom_option_extensions(&mut self, scope: &str) -> Result<()> {
1603 self.identifier()?;
1604 let extendee = self.identifier()?;
1605 let extendee = extendee.trim_start_matches('.').to_string();
1606 let custom_option = is_custom_option_extendee(&extendee);
1607 if !custom_option && self.syntax == Syntax::Proto3 {
1608 return Err(Error::new(
1609 self.offset(),
1610 "proto3 extend target must be a descriptor options message",
1611 ));
1612 }
1613 self.expect_symbol('{')?;
1614 while !self.consume_symbol('}') {
1615 if self.consume_symbol(';') {
1616 continue;
1617 }
1618 let cardinality = if self.peek_identifier(KW_OPTIONAL) {
1619 if self.syntax.is_edition() {
1620 return Err(Error::new(
1621 self.offset(),
1622 "optional labels are not used in Editions",
1623 ));
1624 }
1625 self.identifier()?;
1626 Cardinality::Optional
1627 } else if self.peek_identifier(KW_REPEATED) {
1628 self.identifier()?;
1629 Cardinality::Repeated
1630 } else if self.peek_identifier(KW_REQUIRED) {
1631 if self.syntax.has_modern_defaults() {
1632 return Err(Error::new(
1633 self.offset(),
1634 "required extension fields are not allowed here",
1635 ));
1636 }
1637 self.identifier()?;
1638 Cardinality::Required
1639 } else {
1640 Cardinality::Optional
1641 };
1642 if self.peek_identifier(KW_GROUP) {
1643 self.skip_group()?;
1644 continue;
1645 }
1646 let mut field = self.parse_field(None, Some(cardinality))?;
1647 if custom_option && field.number < CUSTOM_OPTION_MIN_FIELD_NUMBER {
1648 return Err(Error::new(
1649 self.offset(),
1650 "custom option number is outside the descriptor extension range",
1651 ));
1652 }
1653 let full_name = self.qualify(scope, &field.name);
1654 if custom_option
1655 && (self.custom_options.contains_key(&full_name)
1656 || self.custom_options.values().any(|option| {
1657 option.extendee == extendee && option.field.number == field.number
1658 }))
1659 {
1660 return Err(Error::new(
1661 self.offset(),
1662 "duplicate custom option name or number",
1663 ));
1664 }
1665 if custom_option {
1666 self.custom_options.insert(
1667 full_name.clone(),
1668 CustomOptionDescriptor {
1669 name: field.name.clone(),
1670 full_name,
1671 extendee: extendee.clone(),
1672 field,
1673 },
1674 );
1675 } else {
1676 if self.extensions.contains_key(&full_name) {
1677 return Err(Error::new(
1678 self.offset(),
1679 "duplicate extension name or number",
1680 ));
1681 }
1682 field.name = full_name.clone();
1683 self.extensions.insert(
1684 full_name.clone(),
1685 ExtensionDescriptor {
1686 full_name,
1687 extendee: extendee.clone(),
1688 field,
1689 },
1690 );
1691 }
1692 }
1693 Ok(())
1694 }
1695
1696 fn parse_service(&mut self) -> Result<()> {
1698 self.identifier()?;
1699 let name = self.declaration_name()?;
1700 let full_name = self.qualify("", &name);
1701 self.expect_symbol('{')?;
1702 let mut methods = Vec::new();
1703 let mut options = Vec::new();
1704 while !self.consume_symbol('}') {
1705 if self.consume_symbol(';') {
1706 continue;
1707 }
1708 if self.peek_identifier(KW_OPTION) {
1709 options.push(self.option_declaration()?);
1710 continue;
1711 }
1712 if !self.peek_identifier(KW_RPC) {
1713 return Err(Error::new(self.offset(), "expected service option or rpc"));
1714 }
1715 self.identifier()?;
1716 let method_name = self.declaration_name()?;
1717 if methods
1718 .iter()
1719 .any(|method: &MethodDescriptor| method.name == method_name)
1720 {
1721 return Err(Error::new(self.offset(), "duplicate rpc method name"));
1722 }
1723 self.expect_symbol('(')?;
1724 let client_streaming = if self.peek_identifier(KW_STREAM) {
1725 self.identifier()?;
1726 true
1727 } else {
1728 false
1729 };
1730 let input_type = self.identifier()?;
1731 if !is_full_identifier(&input_type, true) {
1732 return Err(Error::new(self.offset(), "invalid rpc request type"));
1733 }
1734 self.expect_symbol(')')?;
1735 if !self.peek_identifier(KW_RETURNS) {
1736 return Err(Error::new(
1737 self.offset(),
1738 "expected returns in rpc declaration",
1739 ));
1740 }
1741 self.identifier()?;
1742 self.expect_symbol('(')?;
1743 let server_streaming = if self.peek_identifier(KW_STREAM) {
1744 self.identifier()?;
1745 true
1746 } else {
1747 false
1748 };
1749 let output_type = self.identifier()?;
1750 if !is_full_identifier(&output_type, true) {
1751 return Err(Error::new(self.offset(), "invalid rpc response type"));
1752 }
1753 self.expect_symbol(')')?;
1754 let mut method_options = Vec::new();
1755 if !self.consume_symbol(';') {
1756 self.expect_symbol('{')?;
1757 while !self.consume_symbol('}') {
1758 if self.consume_symbol(';') {
1759 continue;
1760 }
1761 if !self.peek_identifier(KW_OPTION) {
1762 return Err(Error::new(self.offset(), "expected rpc option"));
1763 }
1764 method_options.push(self.option_declaration()?);
1765 }
1766 }
1767 methods.push(MethodDescriptor {
1768 name: method_name,
1769 input_type,
1770 output_type,
1771 client_streaming,
1772 server_streaming,
1773 options: method_options,
1774 });
1775 }
1776 if self.services.contains_key(&full_name) {
1777 return Err(Error::new(self.offset(), "duplicate service name"));
1778 }
1779 self.services.insert(
1780 full_name.clone(),
1781 ServiceDescriptor {
1782 name,
1783 full_name,
1784 methods,
1785 options,
1786 },
1787 );
1788 Ok(())
1789 }
1790
1791 fn parse_field(
1797 &mut self,
1798 oneof: Option<String>,
1799 declared_cardinality: Option<Cardinality>,
1800 ) -> Result<Field> {
1801 let is_map = self.peek_identifier(KW_MAP);
1802 if self.syntax == Syntax::Proto2
1803 && declared_cardinality.is_none()
1804 && oneof.is_none()
1805 && !is_map
1806 {
1807 return Err(Error::new(
1808 self.offset(),
1809 "proto2 field requires a cardinality label",
1810 ));
1811 }
1812 if self.syntax.has_modern_defaults() && declared_cardinality == Some(Cardinality::Required)
1813 {
1814 return Err(Error::new(
1815 self.offset(),
1816 "required fields are not allowed in proto3",
1817 ));
1818 }
1819 if is_map && (declared_cardinality.is_some() || oneof.is_some()) {
1820 return Err(Error::new(
1821 self.offset(),
1822 "map fields cannot have labels or belong to oneof",
1823 ));
1824 }
1825 let kind = if is_map {
1826 self.identifier()?;
1827 self.expect_symbol('<')?;
1828 let key_type = self.parse_type()?;
1829 self.expect_symbol(',')?;
1830 let value_type = self.parse_type()?;
1831 self.expect_symbol('>')?;
1832 if !matches!(
1833 key_type,
1834 FieldType::Int32
1835 | FieldType::Int64
1836 | FieldType::Uint32
1837 | FieldType::Uint64
1838 | FieldType::Sint32
1839 | FieldType::Sint64
1840 | FieldType::Fixed32
1841 | FieldType::Fixed64
1842 | FieldType::Sfixed32
1843 | FieldType::Sfixed64
1844 | FieldType::Bool
1845 | FieldType::String
1846 ) {
1847 return Err(Error::new(self.offset(), "invalid protobuf map key type"));
1848 }
1849 FieldType::Map(Box::new(key_type), Box::new(value_type))
1850 } else {
1851 self.parse_type()?
1852 };
1853 let name = self.declaration_name()?;
1854 self.expect_symbol('=')?;
1855 let number = self.integer()?;
1856 let valid_range = i64::from(MIN_FIELD_NUMBER)..=i64::from(MAX_FIELD_NUMBER);
1857 let reserved_range =
1858 i64::from(RESERVED_FIELD_NUMBER_START)..=i64::from(RESERVED_FIELD_NUMBER_END);
1859 if !valid_range.contains(&number) || reserved_range.contains(&number) {
1860 return Err(Error::new(self.offset(), "invalid field number"));
1861 }
1862 let mut packed = None;
1863 let mut packed_explicit = false;
1864 let mut default = None;
1865 let mut options = Vec::new();
1866 if self.consume_symbol('[') {
1867 loop {
1868 if self.consume_symbol(']') {
1869 break;
1870 }
1871 let option = self.option_setting()?;
1872 if option.name == OPTION_PACKED {
1873 if packed.is_some() {
1874 return Err(Error::new(self.offset(), "duplicate packed option"));
1875 }
1876 packed = match option.value.as_str() {
1877 BOOLEAN_TRUE => Some(true),
1878 BOOLEAN_FALSE => Some(false),
1879 _ => {
1880 return Err(Error::new(
1881 self.offset(),
1882 "packed option must be true or false",
1883 ));
1884 }
1885 };
1886 packed_explicit = true;
1887 } else if option.name == OPTION_DEFAULT {
1888 if default.is_some() {
1889 return Err(Error::new(self.offset(), "duplicate default option"));
1890 }
1891 default = Some(option.value.clone())
1892 }
1893 options.push(option);
1894 if !self.consume_symbol(']') {
1895 self.expect_symbol(',')?;
1896 } else {
1897 break;
1898 }
1899 }
1900 }
1901 self.expect_symbol(';')?;
1902 let cardinality = if matches!(kind, FieldType::Map(..)) {
1903 Cardinality::Repeated
1904 } else {
1905 declared_cardinality.unwrap_or(Cardinality::Optional)
1906 };
1907 if default.is_some()
1908 && (self.syntax == Syntax::Proto3
1909 || cardinality == Cardinality::Repeated
1910 || oneof.is_some()
1911 || matches!(kind, FieldType::Map(..)))
1912 {
1913 return Err(Error::new(
1914 self.offset(),
1915 "default option is not valid for this field",
1916 ));
1917 }
1918 if packed.is_some()
1919 && (cardinality != Cardinality::Repeated
1920 || matches!(
1921 kind,
1922 FieldType::String | FieldType::Bytes | FieldType::Map(..)
1923 ))
1924 {
1925 return Err(Error::new(
1926 self.offset(),
1927 "packed option requires a repeated primitive field",
1928 ));
1929 }
1930 let explicit_presence = declared_cardinality.is_some() || oneof.is_some();
1931 if packed.is_none()
1932 && cardinality == Cardinality::Repeated
1933 && !matches!(
1934 kind,
1935 FieldType::String | FieldType::Bytes | FieldType::Map(..)
1936 )
1937 {
1938 packed = Some(self.syntax.has_modern_defaults());
1939 }
1940 Ok(Field {
1941 name,
1942 number: number as u32,
1943 cardinality,
1944 kind,
1945 packed,
1946 packed_explicit,
1947 oneof,
1948 explicit_presence,
1949 default,
1950 options,
1951 features: FeatureSet::for_syntax(self.syntax),
1952 })
1953 }
1954 fn parse_type(&mut self) -> Result<FieldType> {
1960 let name = self.identifier()?;
1961 Ok(match name.as_str() {
1962 TYPE_DOUBLE => FieldType::Double,
1963 TYPE_FLOAT => FieldType::Float,
1964 TYPE_INT32 => FieldType::Int32,
1965 TYPE_INT64 => FieldType::Int64,
1966 TYPE_UINT32 => FieldType::Uint32,
1967 TYPE_UINT64 => FieldType::Uint64,
1968 TYPE_SINT32 => FieldType::Sint32,
1969 TYPE_SINT64 => FieldType::Sint64,
1970 TYPE_FIXED32 => FieldType::Fixed32,
1971 TYPE_FIXED64 => FieldType::Fixed64,
1972 TYPE_SFIXED32 => FieldType::Sfixed32,
1973 TYPE_SFIXED64 => FieldType::Sfixed64,
1974 TYPE_BOOL => FieldType::Bool,
1975 TYPE_STRING => FieldType::String,
1976 TYPE_BYTES => FieldType::Bytes,
1977 _ => FieldType::Message(name),
1980 })
1981 }
1982}
1983
1984fn validate_reserved_declarations(reserved: &ReservedDeclarations, offset: usize) -> Result<()> {
1986 for (index, name) in reserved.names.iter().enumerate() {
1987 if reserved
1988 .names
1989 .iter()
1990 .take(index)
1991 .any(|previous| previous == name)
1992 {
1993 return Err(Error::new(offset, "duplicate reserved name"));
1994 }
1995 }
1996 for (index, (start, end)) in reserved.ranges.iter().enumerate() {
1997 if reserved
1998 .ranges
1999 .iter()
2000 .take(index)
2001 .any(|(previous_start, previous_end)| start <= previous_end && previous_start <= end)
2002 {
2003 return Err(Error::new(offset, "overlapping reserved ranges"));
2004 }
2005 }
2006 Ok(())
2007}
2008
2009#[derive(Clone, Copy)]
2011enum OptionTarget {
2012 File,
2013 Message,
2014 Field,
2015 Oneof,
2016 Enum,
2017 EnumValue,
2018 Service,
2019 Method,
2020}
2021
2022#[derive(Clone, Copy)]
2024enum BuiltinOptionType {
2025 Bool,
2026 String,
2027 Identifier,
2028 AnyScalar,
2029 Any,
2031}
2032
2033fn builtin_option_type(target: OptionTarget, name: &str) -> Option<BuiltinOptionType> {
2035 use BuiltinOptionType::{Any, AnyScalar, Bool, Identifier, String as StringOption};
2036 if matches!(
2037 name,
2038 FEATURE_FIELD_PRESENCE
2039 | FEATURE_ENUM_TYPE
2040 | FEATURE_REPEATED_ENCODING
2041 | FEATURE_MESSAGE_ENCODING
2042 | FEATURE_UTF8_VALIDATION
2043 | FEATURE_JSON_FORMAT
2044 ) {
2045 return Some(Identifier);
2046 }
2047 match target {
2048 OptionTarget::File => match name {
2049 "java_package"
2050 | "java_outer_classname"
2051 | "go_package"
2052 | "objc_class_prefix"
2053 | "csharp_namespace"
2054 | "swift_prefix"
2055 | "php_class_prefix"
2056 | "php_namespace"
2057 | "php_metadata_namespace"
2058 | "ruby_package" => Some(StringOption),
2059 "java_multiple_files"
2060 | "java_generate_equals_and_hash"
2061 | "java_string_check_utf8"
2062 | "cc_generic_services"
2063 | "java_generic_services"
2064 | "py_generic_services"
2065 | "php_generic_services"
2066 | "deprecated"
2067 | "cc_enable_arenas" => Some(Bool),
2068 "optimize_for" => Some(Identifier),
2069 _ => None,
2070 },
2071 OptionTarget::Message => match name {
2072 "message_set_wire_format"
2073 | "no_standard_descriptor_accessor"
2074 | "deprecated"
2075 | "map_entry"
2076 | "deprecated_legacy_json_field_conflicts" => Some(Bool),
2077 _ => None,
2078 },
2079 OptionTarget::Field => match name {
2080 OPTION_PACKED | "lazy" | "unverified_lazy" | "deprecated" | "weak" | "debug_redact" => {
2081 Some(Bool)
2082 }
2083 OPTION_DEFAULT => Some(AnyScalar),
2084 "json_name" => Some(StringOption),
2085 "ctype" | "jstype" | "retention" => Some(Identifier),
2086 "targets" => Some(Identifier),
2087 "edition_defaults" | "feature_support" => Some(Any),
2088 _ => None,
2089 },
2090 OptionTarget::Oneof => None,
2091 OptionTarget::Enum => match name {
2092 OPTION_ALLOW_ALIAS | "deprecated" | "deprecated_legacy_json_field_conflicts" => {
2093 Some(Bool)
2094 }
2095 _ => None,
2096 },
2097 OptionTarget::EnumValue => match name {
2098 "deprecated" | "debug_redact" => Some(Bool),
2099 "feature_support" => Some(Any),
2100 _ => None,
2101 },
2102 OptionTarget::Service => match name {
2103 "deprecated" => Some(Bool),
2104 _ => None,
2105 },
2106 OptionTarget::Method => match name {
2107 "deprecated" => Some(Bool),
2108 "idempotency_level" => Some(Identifier),
2109 _ => None,
2110 },
2111 }
2112}
2113
2114fn apply_feature_options(
2116 inherited: FeatureSet,
2117 options: &[OptionSetting],
2118 target: OptionTarget,
2119 edition: bool,
2120) -> Result<FeatureSet> {
2121 let mut features = inherited;
2122 for option in options {
2123 let recognized = match option.name.as_str() {
2124 FEATURE_FIELD_PRESENCE => {
2125 if !matches!(
2126 target,
2127 OptionTarget::File | OptionTarget::Message | OptionTarget::Field
2128 ) {
2129 return Err(Error::new(0, "field_presence feature is misplaced"));
2130 }
2131 features.field_presence = match option.value.as_str() {
2132 "EXPLICIT" => FieldPresence::Explicit,
2133 "IMPLICIT" => FieldPresence::Implicit,
2134 "LEGACY_REQUIRED" => FieldPresence::LegacyRequired,
2135 _ => return Err(Error::new(0, "invalid field_presence feature value")),
2136 };
2137 true
2138 }
2139 FEATURE_ENUM_TYPE => {
2140 if !matches!(target, OptionTarget::File | OptionTarget::Enum) {
2141 return Err(Error::new(0, "enum_type feature is misplaced"));
2142 }
2143 features.enum_type = match option.value.as_str() {
2144 "OPEN" => EnumType::Open,
2145 "CLOSED" => EnumType::Closed,
2146 _ => return Err(Error::new(0, "invalid enum_type feature value")),
2147 };
2148 true
2149 }
2150 FEATURE_REPEATED_ENCODING => {
2151 if !matches!(target, OptionTarget::File | OptionTarget::Field) {
2152 return Err(Error::new(
2153 0,
2154 "repeated_field_encoding feature is misplaced",
2155 ));
2156 }
2157 features.repeated_field_encoding = match option.value.as_str() {
2158 "PACKED" => RepeatedFieldEncoding::Packed,
2159 "EXPANDED" => RepeatedFieldEncoding::Expanded,
2160 _ => {
2161 return Err(Error::new(
2162 0,
2163 "invalid repeated_field_encoding feature value",
2164 ));
2165 }
2166 };
2167 true
2168 }
2169 FEATURE_MESSAGE_ENCODING => {
2170 if !matches!(target, OptionTarget::File | OptionTarget::Field) {
2171 return Err(Error::new(0, "message_encoding feature is misplaced"));
2172 }
2173 features.message_encoding = match option.value.as_str() {
2174 "LENGTH_PREFIXED" => MessageEncoding::LengthPrefixed,
2175 "DELIMITED" => MessageEncoding::Delimited,
2176 _ => return Err(Error::new(0, "invalid message_encoding feature value")),
2177 };
2178 true
2179 }
2180 FEATURE_UTF8_VALIDATION => {
2181 if !matches!(target, OptionTarget::File | OptionTarget::Field) {
2182 return Err(Error::new(0, "utf8_validation feature is misplaced"));
2183 }
2184 features.utf8_validation = match option.value.as_str() {
2185 "VERIFY" => Utf8Validation::Verify,
2186 "NONE" => Utf8Validation::None,
2187 _ => return Err(Error::new(0, "invalid utf8_validation feature value")),
2188 };
2189 true
2190 }
2191 FEATURE_JSON_FORMAT => {
2192 if !matches!(
2193 target,
2194 OptionTarget::File | OptionTarget::Message | OptionTarget::Enum
2195 ) {
2196 return Err(Error::new(0, "json_format feature is misplaced"));
2197 }
2198 features.json_format = match option.value.as_str() {
2199 "ALLOW" => JsonFormat::Allow,
2200 "LEGACY_BEST_EFFORT" => JsonFormat::LegacyBestEffort,
2201 _ => return Err(Error::new(0, "invalid json_format feature value")),
2202 };
2203 true
2204 }
2205 _ => false,
2206 };
2207 if recognized && !edition {
2208 return Err(Error::new(
2209 0,
2210 "features are available only in Editions sources",
2211 ));
2212 }
2213 }
2214 Ok(features)
2215}
2216
2217fn resolve_features(schema: &mut Schema) -> Result<()> {
2219 let edition = schema.syntax.is_edition();
2220 let root = apply_feature_options(
2221 FeatureSet::for_syntax(schema.syntax),
2222 &schema.options,
2223 OptionTarget::File,
2224 edition,
2225 )?;
2226 schema.features = root;
2227 let message_names: Vec<String> = schema.messages.keys().cloned().collect();
2228 let mut resolved_messages = BTreeMap::<String, FeatureSet>::new();
2229 for name in &message_names {
2230 let parent = message_names
2231 .iter()
2232 .filter(|candidate| {
2233 name.starts_with(candidate.as_str()) && name.as_str() != candidate.as_str()
2234 })
2235 .filter(|candidate| name.as_bytes().get(candidate.len()) == Some(&b'.'))
2236 .max_by_key(|candidate| candidate.len())
2237 .and_then(|candidate| resolved_messages.get(candidate))
2238 .copied()
2239 .unwrap_or(root);
2240 let descriptor = schema
2241 .messages
2242 .get_mut(name)
2243 .ok_or_else(|| Error::new(0, "message disappeared during feature resolution"))?;
2244 descriptor.features =
2245 apply_feature_options(parent, &descriptor.options, OptionTarget::Message, edition)?;
2246 for field in &mut descriptor.fields {
2247 field.features = apply_feature_options(
2248 descriptor.features,
2249 &field.options,
2250 OptionTarget::Field,
2251 edition,
2252 )?;
2253 if field.features.message_encoding == MessageEncoding::Delimited
2254 && !matches!(field.kind, FieldType::Message(_))
2255 && field
2256 .options
2257 .iter()
2258 .any(|option| option.name == FEATURE_MESSAGE_ENCODING)
2259 {
2260 return Err(Error::new(
2261 0,
2262 format!(
2263 "field {} applies DELIMITED encoding to a non-message",
2264 field.name
2265 ),
2266 ));
2267 }
2268 if field
2269 .options
2270 .iter()
2271 .any(|option| option.name == FEATURE_UTF8_VALIDATION)
2272 && !matches!(field.kind, FieldType::String)
2273 {
2274 return Err(Error::new(
2275 0,
2276 format!(
2277 "field {} applies UTF-8 validation to a non-string",
2278 field.name
2279 ),
2280 ));
2281 }
2282 if field
2283 .options
2284 .iter()
2285 .any(|option| option.name == FEATURE_REPEATED_ENCODING)
2286 && field.cardinality != Cardinality::Repeated
2287 {
2288 return Err(Error::new(
2289 0,
2290 format!(
2291 "field {} applies repeated encoding to a singular field",
2292 field.name
2293 ),
2294 ));
2295 }
2296 field.explicit_presence = field.explicit_presence
2297 || field.oneof.is_some()
2298 || matches!(field.kind, FieldType::Message(_))
2299 || field.features.field_presence != FieldPresence::Implicit;
2300 if field.default.is_some() && field.features.field_presence == FieldPresence::Implicit {
2301 return Err(Error::new(
2302 0,
2303 format!(
2304 "field {} cannot combine implicit presence with a default",
2305 field.name
2306 ),
2307 ));
2308 }
2309 if field.cardinality == Cardinality::Repeated
2310 && !field.packed_explicit
2311 && !matches!(
2312 field.kind,
2313 FieldType::String
2314 | FieldType::Bytes
2315 | FieldType::Message(_)
2316 | FieldType::Map(..)
2317 )
2318 {
2319 field.packed =
2320 Some(field.features.repeated_field_encoding == RepeatedFieldEncoding::Packed);
2321 }
2322 }
2323 resolved_messages.insert(name.clone(), descriptor.features);
2324 }
2325 for enumeration in schema.enums.values_mut() {
2326 let parent = message_names
2327 .iter()
2328 .filter(|candidate| enumeration.full_name.starts_with(candidate.as_str()))
2329 .filter(|candidate| {
2330 enumeration.full_name.as_bytes().get(candidate.len()) == Some(&b'.')
2331 })
2332 .max_by_key(|candidate| candidate.len())
2333 .and_then(|candidate| resolved_messages.get(candidate))
2334 .copied()
2335 .unwrap_or(root);
2336 enumeration.features =
2337 apply_feature_options(parent, &enumeration.options, OptionTarget::Enum, edition)?;
2338 }
2339 for extension in schema.extensions.values_mut() {
2340 let scope = extension
2341 .full_name
2342 .rsplit_once('.')
2343 .map_or("", |(parent, _)| parent);
2344 let inherited = resolved_messages.get(scope).copied().unwrap_or(root);
2345 extension.field.features = apply_feature_options(
2346 inherited,
2347 &extension.field.options,
2348 OptionTarget::Field,
2349 edition,
2350 )?;
2351 extension.field.explicit_presence = extension.field.cardinality != Cardinality::Repeated
2352 && extension.field.features.field_presence != FieldPresence::Implicit;
2353 if extension.field.cardinality == Cardinality::Repeated
2354 && !extension.field.packed_explicit
2355 && !matches!(
2356 extension.field.kind,
2357 FieldType::String | FieldType::Bytes | FieldType::Message(_) | FieldType::Map(..)
2358 )
2359 {
2360 extension.field.packed = Some(
2361 extension.field.features.repeated_field_encoding == RepeatedFieldEncoding::Packed,
2362 );
2363 }
2364 }
2365 Ok(())
2366}
2367
2368fn validate_options(options: &[OptionSetting], target: OptionTarget) -> Result<()> {
2370 for (index, option) in options.iter().enumerate() {
2371 if option.name.starts_with('(') {
2372 continue;
2373 }
2374 let expected = builtin_option_type(target, &option.name).ok_or_else(|| {
2375 Error::new(0, format!("unknown or misplaced option: {}", option.name))
2376 })?;
2377 if options[..index]
2378 .iter()
2379 .any(|previous| previous.name == option.name)
2380 {
2381 return Err(Error::new(0, format!("duplicate option: {}", option.name)));
2382 }
2383 let valid = match expected {
2384 BuiltinOptionType::Bool => {
2385 option.value_kind == OptionValueKind::Identifier
2386 && matches!(option.value.as_str(), BOOLEAN_TRUE | BOOLEAN_FALSE)
2387 }
2388 BuiltinOptionType::String => option.value_kind == OptionValueKind::String,
2389 BuiltinOptionType::Identifier => option.value_kind == OptionValueKind::Identifier,
2390 BuiltinOptionType::AnyScalar => option.value_kind != OptionValueKind::Aggregate,
2391 BuiltinOptionType::Any => true,
2392 };
2393 if !valid {
2394 return Err(Error::new(
2395 0,
2396 format!("invalid value for option: {}", option.name),
2397 ));
2398 }
2399 if option.name == "optimize_for"
2400 && !matches!(
2401 option.value.as_str(),
2402 "SPEED" | "CODE_SIZE" | "LITE_RUNTIME"
2403 )
2404 {
2405 return Err(Error::new(0, "invalid optimize_for value"));
2406 }
2407 if option.name == "ctype"
2408 && !matches!(option.value.as_str(), "STRING" | "CORD" | "STRING_PIECE")
2409 {
2410 return Err(Error::new(0, "invalid ctype value"));
2411 }
2412 if option.name == "jstype"
2413 && !matches!(
2414 option.value.as_str(),
2415 "JS_NORMAL" | "JS_STRING" | "JS_NUMBER"
2416 )
2417 {
2418 return Err(Error::new(0, "invalid jstype value"));
2419 }
2420 if option.name == "idempotency_level"
2421 && !matches!(
2422 option.value.as_str(),
2423 "IDEMPOTENCY_UNKNOWN" | "NO_SIDE_EFFECTS" | "IDEMPOTENT"
2424 )
2425 {
2426 return Err(Error::new(0, "invalid idempotency_level value"));
2427 }
2428 }
2429 Ok(())
2430}
2431
2432fn is_custom_option_extendee(name: &str) -> bool {
2434 matches!(
2435 name,
2436 "google.protobuf.FileOptions"
2437 | "google.protobuf.MessageOptions"
2438 | "google.protobuf.FieldOptions"
2439 | "google.protobuf.OneofOptions"
2440 | "google.protobuf.EnumOptions"
2441 | "google.protobuf.EnumValueOptions"
2442 | "google.protobuf.ServiceOptions"
2443 | "google.protobuf.MethodOptions"
2444 | "google.protobuf.ExtensionRangeOptions"
2445 )
2446}
2447
2448fn option_target_extendee(target: OptionTarget) -> &'static str {
2450 match target {
2451 OptionTarget::File => "google.protobuf.FileOptions",
2452 OptionTarget::Message => "google.protobuf.MessageOptions",
2453 OptionTarget::Field => "google.protobuf.FieldOptions",
2454 OptionTarget::Oneof => "google.protobuf.OneofOptions",
2455 OptionTarget::Enum => "google.protobuf.EnumOptions",
2456 OptionTarget::EnumValue => "google.protobuf.EnumValueOptions",
2457 OptionTarget::Service => "google.protobuf.ServiceOptions",
2458 OptionTarget::Method => "google.protobuf.MethodOptions",
2459 }
2460}
2461
2462fn custom_option_parts(name: &str) -> Option<(&str, &str)> {
2464 let contents = name.strip_prefix('(')?;
2465 let closing = contents.find(')')?;
2466 let extension = &contents[..closing];
2467 let suffix = contents.get(closing + 1..)?;
2468 Some((extension, suffix.strip_prefix('.').unwrap_or(suffix)))
2469}
2470
2471fn resolve_custom_option<'a>(
2473 source_name: &str,
2474 scope: &str,
2475 options: &'a BTreeMap<String, CustomOptionDescriptor>,
2476) -> Option<&'a CustomOptionDescriptor> {
2477 let absolute = source_name.starts_with('.');
2478 let raw = source_name.trim_start_matches('.');
2479 if absolute {
2480 return options.get(raw);
2481 }
2482 let mut current = scope;
2483 loop {
2484 let candidate = if current.is_empty() {
2485 raw.to_string()
2486 } else {
2487 format!("{current}.{raw}")
2488 };
2489 if let Some(option) = options.get(&candidate) {
2490 return Some(option);
2491 }
2492 let Some((parent, _)) = current.rsplit_once('.') else {
2493 break;
2494 };
2495 current = parent;
2496 }
2497 options.get(raw)
2498}
2499
2500fn custom_option_value_type<'a>(
2502 descriptor: &'a CustomOptionDescriptor,
2503 path: &str,
2504 messages: &'a BTreeMap<String, MessageDescriptor>,
2505) -> Result<&'a FieldType> {
2506 let mut field_type = &descriptor.field.kind;
2507 if path.is_empty() {
2508 return Ok(field_type);
2509 }
2510 for component in path.split('.') {
2511 let FieldType::Message(message_name) = field_type else {
2512 return Err(Error::new(0, "custom option path traverses a scalar value"));
2513 };
2514 let message = messages.get(message_name).ok_or_else(|| {
2515 Error::new(0, format!("unknown custom option message: {message_name}"))
2516 })?;
2517 field_type = &message
2518 .field_by_name(component)
2519 .ok_or_else(|| Error::new(0, format!("unknown custom option field: {component}")))?
2520 .kind;
2521 }
2522 Ok(field_type)
2523}
2524
2525fn custom_option_value_is_valid(
2527 field_type: &FieldType,
2528 kind: OptionValueKind,
2529 value: &str,
2530) -> bool {
2531 match field_type {
2532 FieldType::Bool => {
2533 kind == OptionValueKind::Identifier && matches!(value, BOOLEAN_TRUE | BOOLEAN_FALSE)
2534 }
2535 FieldType::String | FieldType::Bytes => kind == OptionValueKind::String,
2536 FieldType::Enum(_) => matches!(kind, OptionValueKind::Identifier | OptionValueKind::Number),
2537 FieldType::Message(_) => kind == OptionValueKind::Aggregate,
2538 FieldType::Map(..) => false,
2539 _ => kind == OptionValueKind::Number,
2540 }
2541}
2542
2543fn validate_custom_options(
2545 settings: &[OptionSetting],
2546 target: OptionTarget,
2547 scope: &str,
2548 options: &BTreeMap<String, CustomOptionDescriptor>,
2549 messages: &BTreeMap<String, MessageDescriptor>,
2550) -> Result<()> {
2551 for (index, setting) in settings.iter().enumerate() {
2552 let Some((extension_name, path)) = custom_option_parts(&setting.name) else {
2553 continue;
2554 };
2555 let descriptor = resolve_custom_option(extension_name, scope, options)
2556 .ok_or_else(|| Error::new(0, format!("unknown custom option: {}", setting.name)))?;
2557 if descriptor.extendee != option_target_extendee(target) {
2558 return Err(Error::new(
2559 0,
2560 format!("custom option is not valid at this scope: {}", setting.name),
2561 ));
2562 }
2563 if descriptor.field.cardinality != Cardinality::Repeated
2564 && settings[..index]
2565 .iter()
2566 .any(|previous| previous.name == setting.name)
2567 {
2568 return Err(Error::new(
2569 0,
2570 format!("duplicate custom option: {}", setting.name),
2571 ));
2572 }
2573 let field_type = custom_option_value_type(descriptor, path, messages)?;
2574 if !custom_option_value_is_valid(field_type, setting.value_kind, &setting.value) {
2575 return Err(Error::new(
2576 0,
2577 format!("invalid value for custom option: {}", setting.name),
2578 ));
2579 }
2580 }
2581 Ok(())
2582}
2583
2584fn validate_schema_options(
2586 schema: &Schema,
2587 custom_options: &BTreeMap<String, CustomOptionDescriptor>,
2588 messages: &BTreeMap<String, MessageDescriptor>,
2589) -> Result<()> {
2590 let file_scope = schema.package.as_deref().unwrap_or("");
2591 validate_options(&schema.options, OptionTarget::File)?;
2592 validate_custom_options(
2593 &schema.options,
2594 OptionTarget::File,
2595 file_scope,
2596 custom_options,
2597 messages,
2598 )?;
2599 for message in schema.messages.values() {
2600 validate_options(&message.options, OptionTarget::Message)?;
2601 validate_custom_options(
2602 &message.options,
2603 OptionTarget::Message,
2604 &message.full_name,
2605 custom_options,
2606 messages,
2607 )?;
2608 for oneof in &message.oneofs {
2609 validate_options(&oneof.options, OptionTarget::Oneof)?;
2610 validate_custom_options(
2611 &oneof.options,
2612 OptionTarget::Oneof,
2613 &message.full_name,
2614 custom_options,
2615 messages,
2616 )?;
2617 }
2618 for field in &message.fields {
2619 validate_options(&field.options, OptionTarget::Field)?;
2620 validate_custom_options(
2621 &field.options,
2622 OptionTarget::Field,
2623 &message.full_name,
2624 custom_options,
2625 messages,
2626 )?;
2627 }
2628 }
2629 for enumeration in schema.enums.values() {
2630 validate_options(&enumeration.options, OptionTarget::Enum)?;
2631 validate_custom_options(
2632 &enumeration.options,
2633 OptionTarget::Enum,
2634 &enumeration.full_name,
2635 custom_options,
2636 messages,
2637 )?;
2638 for value in &enumeration.values {
2639 validate_options(&value.options, OptionTarget::EnumValue)?;
2640 validate_custom_options(
2641 &value.options,
2642 OptionTarget::EnumValue,
2643 &enumeration.full_name,
2644 custom_options,
2645 messages,
2646 )?;
2647 }
2648 }
2649 for service in schema.services.values() {
2650 validate_options(&service.options, OptionTarget::Service)?;
2651 validate_custom_options(
2652 &service.options,
2653 OptionTarget::Service,
2654 &service.full_name,
2655 custom_options,
2656 messages,
2657 )?;
2658 for method in &service.methods {
2659 validate_options(&method.options, OptionTarget::Method)?;
2660 validate_custom_options(
2661 &method.options,
2662 OptionTarget::Method,
2663 &service.full_name,
2664 custom_options,
2665 messages,
2666 )?;
2667 }
2668 }
2669 Ok(())
2670}
2671
2672fn field_json_name(field: &Field) -> String {
2678 if let Some(option) = field
2679 .options
2680 .iter()
2681 .find(|option| option.name == "json_name")
2682 {
2683 return option.value.clone();
2684 }
2685 let mut name = String::new();
2686 let mut capitalize = false;
2687 for character in field.name.chars() {
2688 if character == '_' {
2689 capitalize = true;
2690 } else if capitalize {
2691 name.push(character.to_ascii_uppercase());
2692 capitalize = false;
2693 } else {
2694 name.push(character);
2695 }
2696 }
2697 name
2698}
2699
2700fn validate_json_field_names(fields: &[Field], offset: usize) -> Result<()> {
2707 for (index, field) in fields.iter().enumerate() {
2708 let json_name = field_json_name(field);
2709 if fields[..index]
2710 .iter()
2711 .any(|previous| field_json_name(previous) == json_name)
2712 {
2713 return Err(Error::new(
2714 offset,
2715 format!("duplicate proto3 JSON field name: {json_name}"),
2716 ));
2717 }
2718 }
2719 Ok(())
2720}
2721
2722fn validate_message_fields(
2724 fields: &[Field],
2725 oneof_names: &[String],
2726 reserved: &ReservedDeclarations,
2727 offset: usize,
2728) -> Result<()> {
2729 validate_reserved_declarations(reserved, offset)?;
2730 for (index, field) in fields.iter().enumerate() {
2731 if fields
2732 .iter()
2733 .take(index)
2734 .any(|previous| previous.name == field.name)
2735 {
2736 return Err(Error::new(offset, "duplicate field name"));
2737 }
2738 if fields
2739 .iter()
2740 .take(index)
2741 .any(|previous| previous.number == field.number)
2742 {
2743 return Err(Error::new(offset, "duplicate field number"));
2744 }
2745 if oneof_names.iter().any(|name| name == &field.name) {
2746 return Err(Error::new(offset, "field name conflicts with oneof name"));
2747 }
2748 if reserved.names.iter().any(|name| name == &field.name)
2749 || reserved
2750 .ranges
2751 .iter()
2752 .any(|(start, end)| (*start..=*end).contains(&i64::from(field.number)))
2753 {
2754 return Err(Error::new(offset, "field uses a reserved name or number"));
2755 }
2756 }
2757 Ok(())
2758}
2759
2760fn validate_source_resource_limits(source: &str, options: &SchemaParseOptions) -> Result<()> {
2764 if source.len() > options.max_source_bytes {
2765 return Err(Error::new(0, "schema source exceeds configured size limit"));
2766 }
2767 let bytes = source.as_bytes();
2768 let mut cursor = 0usize;
2769 let mut depth = 0usize;
2770 let mut quote = None;
2771 let mut escaped = false;
2772 let mut line_comment = false;
2773 let mut block_comment = false;
2774 while cursor < bytes.len() {
2775 let byte = bytes[cursor];
2776 let next = bytes.get(cursor + 1).copied();
2777 if line_comment {
2778 line_comment = byte != b'\n';
2779 } else if block_comment {
2780 if byte == b'*' && next == Some(b'/') {
2781 block_comment = false;
2782 cursor += 1;
2783 }
2784 } else if let Some(delimiter) = quote {
2785 if escaped {
2786 escaped = false;
2787 } else if byte == b'\\' {
2788 escaped = true;
2789 } else if byte == delimiter {
2790 quote = None;
2791 }
2792 } else if byte == b'/' && next == Some(b'/') {
2793 line_comment = true;
2794 cursor += 1;
2795 } else if byte == b'/' && next == Some(b'*') {
2796 block_comment = true;
2797 cursor += 1;
2798 } else if matches!(byte, b'\'' | b'"') {
2799 quote = Some(byte);
2800 } else if byte == b'{' {
2801 depth = depth
2802 .checked_add(1)
2803 .ok_or_else(|| Error::new(cursor, "schema nesting counter overflow"))?;
2804 if depth > options.max_nesting_depth {
2805 return Err(Error::new(
2806 cursor,
2807 "schema exceeds configured nesting limit",
2808 ));
2809 }
2810 } else if byte == b'}' {
2811 depth = depth.saturating_sub(1);
2812 }
2813 cursor += 1;
2814 }
2815 Ok(())
2816}
2817
2818fn parse_file(source: &str, options: &SchemaParseOptions) -> Result<Schema> {
2819 validate_source_resource_limits(source, options)?;
2820 validate_pest_syntax(source)?;
2821 let tokens = lex(source)?;
2822 if tokens.len() > options.max_tokens {
2823 return Err(Error::new(0, "schema exceeds configured token limit"));
2824 }
2825 let mut parser = DescriptorBuilder {
2826 tokens,
2827 cursor: 0,
2828 syntax: Syntax::Proto2,
2829 package: None,
2830 messages: BTreeMap::new(),
2831 enums: BTreeMap::new(),
2832 services: BTreeMap::new(),
2833 custom_options: BTreeMap::new(),
2834 extensions: BTreeMap::new(),
2835 imports: Vec::new(),
2836 options: Vec::new(),
2837 };
2838 let mut seen_language = false;
2839 let mut seen_package = false;
2840 let mut seen_non_syntax = false;
2841 while parser.cursor < parser.tokens.len() {
2842 if parser.peek_identifier(KW_SYNTAX) || parser.peek_identifier(KW_EDITION) {
2843 if seen_language || seen_non_syntax {
2844 return Err(Error::new(
2845 parser.offset(),
2846 "syntax or edition declaration must occur once at the start of the file",
2847 ));
2848 }
2849 seen_language = true;
2850 let declaration = parser.identifier()?;
2851 parser.expect_symbol('=')?;
2852 let language_name = match parser.tokens.get(parser.cursor).cloned() {
2853 Some((Token::StringLiteral(value), _)) => {
2854 parser.cursor += 1;
2855 value
2856 }
2857 _ => {
2858 return Err(Error::new(
2859 parser.offset(),
2860 "expected language version string",
2861 ));
2862 }
2863 };
2864 parser.syntax = match (declaration.as_str(), language_name.as_str()) {
2865 (KW_SYNTAX, SYNTAX_PROTO2) => Syntax::Proto2,
2866 (KW_SYNTAX, SYNTAX_PROTO3) => Syntax::Proto3,
2867 (KW_EDITION, EDITION_2023) => Syntax::Edition2023,
2868 (KW_EDITION, _) => return Err(Error::new(parser.offset(), "unsupported edition")),
2869 _ => return Err(Error::new(parser.offset(), "unsupported syntax")),
2870 };
2871 parser.expect_symbol(';')?
2872 } else if parser.peek_identifier(KW_PACKAGE) {
2873 seen_non_syntax = true;
2874 if seen_package {
2875 return Err(Error::new(parser.offset(), "duplicate package declaration"));
2876 }
2877 seen_package = true;
2878 parser.identifier()?;
2879 parser.package = Some(parser.package_name()?);
2880 parser.expect_symbol(';')?
2881 } else if parser.peek_identifier(KW_IMPORT) {
2882 seen_non_syntax = true;
2883 parser.identifier()?;
2884 let kind = if parser.peek_identifier(KW_PUBLIC) {
2885 parser.identifier()?;
2886 ImportKind::Public
2887 } else if parser.peek_identifier(KW_WEAK) {
2888 parser.identifier()?;
2889 ImportKind::Weak
2890 } else {
2891 ImportKind::Normal
2892 };
2893 let path = match parser.tokens.get(parser.cursor).cloned() {
2894 Some((Token::StringLiteral(path), _)) => {
2895 parser.cursor += 1;
2896 path
2897 }
2898 _ => return Err(Error::new(parser.offset(), "expected import path string")),
2899 };
2900 parser.expect_symbol(';')?;
2901 parser.imports.push(Import { path, kind });
2902 } else if parser.peek_identifier(KW_MESSAGE) {
2903 seen_non_syntax = true;
2904 parser.parse_message("")?
2905 } else if parser.peek_identifier(KW_ENUM) {
2906 seen_non_syntax = true;
2907 parser.parse_enum("")?
2908 } else if parser.peek_identifier(KW_SERVICE) {
2909 seen_non_syntax = true;
2910 parser.parse_service()?
2911 } else if parser.peek_identifier(KW_OPTION) {
2912 seen_non_syntax = true;
2913 let option = parser.option_declaration()?;
2914 parser.options.push(option)
2915 } else if parser.peek_identifier(KW_EXTEND) {
2916 seen_non_syntax = true;
2917 parser.parse_custom_option_extensions("")?
2918 } else if parser.consume_symbol(';') {
2919 seen_non_syntax = true;
2920 } else {
2921 return Err(Error::new(
2922 parser.offset(),
2923 "unexpected top-level declaration",
2924 ));
2925 }
2926 }
2927 Ok(Schema {
2928 syntax: parser.syntax,
2929 package: parser.package,
2930 messages: parser.messages,
2931 enums: parser.enums,
2932 services: parser.services,
2933 custom_options: parser.custom_options,
2934 extensions: parser.extensions,
2935 imports: parser.imports,
2936 options: parser.options,
2937 features: FeatureSet::for_syntax(parser.syntax),
2938 })
2939}
2940
2941pub fn parse(source: &str) -> Result<Schema> {
2950 parse_with_options(source, &SchemaParseOptions::default())
2951}
2952
2953pub fn parse_with_options(source: &str, options: &SchemaParseOptions) -> Result<Schema> {
2955 let mut schema = parse_file(source, options)?;
2956 resolve_schema(&mut schema)?;
2957 Ok(schema)
2958}
2959
2960fn parse_registry(root: &str, registry: &Registry, options: &SchemaParseOptions) -> Result<Schema> {
2966 let mut pending = alloc::vec![root.to_string()];
2967 let mut files = BTreeMap::<String, Schema>::new();
2968 while let Some(path) = pending.pop() {
2969 if files.contains_key(&path) {
2970 continue;
2971 }
2972 let source = registry
2973 .source(&path)
2974 .ok_or_else(|| Error::new(0, format!("import not found: {path}")))?;
2975 if files.len() >= options.max_registry_files {
2976 return Err(Error::new(0, "registry exceeds configured file limit"));
2977 }
2978 let file = parse_file(source, options).map_err(|error| {
2979 Error::new(
2980 error.offset,
2981 format!("while parsing registry source {path}: {}", error.message),
2982 )
2983 })?;
2984 for import in &file.imports {
2985 if registry.source(&import.path).is_none() {
2986 if import.kind == ImportKind::Weak {
2987 continue;
2988 }
2989 return Err(Error::new(0, format!("import not found: {}", import.path)));
2990 }
2991 pending.push(import.path.clone());
2992 }
2993 files.insert(path, file);
2994 }
2995 validate_import_cycles(root, &files, &mut BTreeMap::new())?;
2996
2997 let paths: Vec<String> = files.keys().cloned().collect();
2998 let mut visibility = BTreeMap::<String, Vec<String>>::new();
2999 for path in &paths {
3000 visibility.insert(path.clone(), visible_import_paths(path, &files)?);
3001 }
3002 for path in &paths {
3003 let visible_paths = visibility
3004 .get(path)
3005 .ok_or_else(|| Error::new(0, "import visibility disappeared"))?;
3006 let mut visible_messages = BTreeMap::<String, MessageDescriptor>::new();
3007 let mut visible_enums = BTreeMap::<String, Syntax>::new();
3008 for visible_path in visible_paths {
3009 let visible = files
3010 .get(visible_path)
3011 .ok_or_else(|| Error::new(0, "visible source disappeared"))?;
3012 visible_messages.extend(visible.messages.clone());
3013 for (name, enumeration) in &visible.enums {
3014 visible_enums.insert(name.clone(), enumeration.syntax);
3015 }
3016 }
3017 let file = files
3018 .get_mut(path)
3019 .ok_or_else(|| Error::new(0, "registered source disappeared"))?;
3020 validate_symbol_namespaces(file)?;
3021 resolve_schema_declarations(file, &visible_messages, &visible_enums)?;
3022 resolve_features(file)?;
3023 }
3024 for path in &paths {
3025 let visible_paths = visibility
3026 .get(path)
3027 .ok_or_else(|| Error::new(0, "import visibility disappeared"))?;
3028 let mut visible_messages = BTreeMap::<String, MessageDescriptor>::new();
3029 let mut visible_custom_options = BTreeMap::<String, CustomOptionDescriptor>::new();
3030 for visible_path in visible_paths {
3031 let visible = files
3032 .get(visible_path)
3033 .ok_or_else(|| Error::new(0, "visible source disappeared"))?;
3034 visible_messages.extend(visible.messages.clone());
3035 visible_custom_options.extend(visible.custom_options.clone());
3036 }
3037 let file = files
3038 .get(path)
3039 .ok_or_else(|| Error::new(0, "registered source disappeared"))?;
3040 validate_schema_options(file, &visible_custom_options, &visible_messages)?;
3041 }
3042
3043 let mut schema = files
3044 .remove(root)
3045 .ok_or_else(|| Error::new(0, "root schema not found"))?;
3046 for (_, file) in files {
3047 for (name, descriptor) in file.messages {
3048 if schema.messages.insert(name.clone(), descriptor).is_some() {
3049 return Err(Error::new(0, format!("duplicate message: {name}")));
3050 }
3051 }
3052 for (name, enumeration) in file.enums {
3053 if schema.enums.insert(name.clone(), enumeration).is_some() {
3054 return Err(Error::new(0, format!("duplicate enum: {name}")));
3055 }
3056 }
3057 for (name, service) in file.services {
3058 if schema.services.insert(name.clone(), service).is_some() {
3059 return Err(Error::new(0, format!("duplicate service: {name}")));
3060 }
3061 }
3062 for (name, option) in file.custom_options {
3063 if schema.custom_options.contains_key(&name)
3064 || schema.custom_options.values().any(|existing| {
3065 existing.extendee == option.extendee
3066 && existing.field.number == option.field.number
3067 })
3068 {
3069 return Err(Error::new(0, format!("duplicate custom option: {name}")));
3070 }
3071 schema.custom_options.insert(name, option);
3072 }
3073 for (name, extension) in file.extensions {
3074 if schema.extensions.contains_key(&name)
3075 || schema.extensions.values().any(|existing| {
3076 existing.extendee == extension.extendee
3077 && existing.field.number == extension.field.number
3078 })
3079 {
3080 return Err(Error::new(0, format!("duplicate extension: {name}")));
3081 }
3082 schema.extensions.insert(name, extension);
3083 }
3084 schema.imports.extend(file.imports);
3085 }
3086 validate_symbol_namespaces(&schema)?;
3087 Ok(schema)
3088}
3089
3090fn visible_import_paths(path: &str, files: &BTreeMap<String, Schema>) -> Result<Vec<String>> {
3092 let file = files
3093 .get(path)
3094 .ok_or_else(|| Error::new(0, "registered source disappeared"))?;
3095 let mut visible_paths = alloc::vec![path.to_string()];
3096 let mut public_frontier = Vec::<String>::new();
3097 for import in &file.imports {
3098 if files.contains_key(&import.path) && !visible_paths.contains(&import.path) {
3099 visible_paths.push(import.path.clone());
3100 public_frontier.push(import.path.clone());
3101 }
3102 }
3103 while let Some(imported_path) = public_frontier.pop() {
3104 let imported = files
3105 .get(&imported_path)
3106 .ok_or_else(|| Error::new(0, "visible import disappeared"))?;
3107 for public_import in imported
3108 .imports
3109 .iter()
3110 .filter(|import| import.kind == ImportKind::Public)
3111 {
3112 if files.contains_key(&public_import.path)
3113 && !visible_paths.contains(&public_import.path)
3114 {
3115 visible_paths.push(public_import.path.clone());
3116 public_frontier.push(public_import.path.clone());
3117 }
3118 }
3119 }
3120 Ok(visible_paths)
3121}
3122
3123fn validate_import_cycles(
3125 path: &str,
3126 files: &BTreeMap<String, Schema>,
3127 states: &mut BTreeMap<String, u8>,
3128) -> Result<()> {
3129 match states.get(path) {
3130 Some(1) => return Err(Error::new(0, format!("cyclic protobuf import: {path}"))),
3131 Some(2) => return Ok(()),
3132 _ => {}
3133 }
3134 states.insert(path.to_string(), 1);
3135 let file = files
3136 .get(path)
3137 .ok_or_else(|| Error::new(0, format!("import not found: {path}")))?;
3138 for import in &file.imports {
3139 if files.contains_key(&import.path) {
3140 validate_import_cycles(&import.path, files, states)?;
3141 }
3142 }
3143 states.insert(path.to_string(), 2);
3144 Ok(())
3145}
3146
3147fn resolve_schema(schema: &mut Schema) -> Result<()> {
3153 validate_symbol_namespaces(schema)?;
3154 let messages = schema.messages.clone();
3155 let enums: BTreeMap<String, Syntax> = schema
3156 .enums
3157 .iter()
3158 .map(|(name, enumeration)| (name.clone(), enumeration.syntax))
3159 .collect();
3160 resolve_schema_declarations(schema, &messages, &enums)?;
3161 resolve_features(schema)?;
3162 let resolved_messages = schema.messages.clone();
3163 let custom_options = schema.custom_options.clone();
3164 validate_schema_options(schema, &custom_options, &resolved_messages)
3165}
3166
3167fn resolve_schema_declarations(
3169 schema: &mut Schema,
3170 messages: &BTreeMap<String, MessageDescriptor>,
3171 enums: &BTreeMap<String, Syntax>,
3172) -> Result<()> {
3173 let message_names: Vec<String> = messages.keys().cloned().collect();
3174 let enum_names: Vec<String> = enums.keys().cloned().collect();
3175 for descriptor in schema.messages.values_mut() {
3176 for field in &mut descriptor.fields {
3177 resolve(
3178 &mut field.kind,
3179 &descriptor.full_name,
3180 &message_names,
3181 &enum_names,
3182 )?;
3183 if schema.syntax.has_modern_defaults() {
3184 reject_proto2_enum_reference(&field.kind, enums)?;
3185 }
3186 if field.packed_explicit
3187 && field.packed == Some(true)
3188 && matches!(
3189 field.kind,
3190 FieldType::String
3191 | FieldType::Bytes
3192 | FieldType::Message(_)
3193 | FieldType::Map(..)
3194 )
3195 {
3196 return Err(Error::new(
3197 0,
3198 format!("field {} cannot use packed encoding", field.name),
3199 ));
3200 }
3201 if field.default.is_some()
3202 && matches!(field.kind, FieldType::Message(_) | FieldType::Map(..))
3203 {
3204 return Err(Error::new(
3205 0,
3206 format!("field {} cannot declare a default", field.name),
3207 ));
3208 }
3209 if matches!(field.kind, FieldType::Message(_)) {
3210 field.explicit_presence = true;
3211 }
3212 if field.cardinality == Cardinality::Repeated
3213 && matches!(
3214 field.kind,
3215 FieldType::String
3216 | FieldType::Bytes
3217 | FieldType::Message(_)
3218 | FieldType::Map(..)
3219 )
3220 {
3221 field.packed = Some(false);
3222 }
3223 }
3224 }
3225 for option in schema.custom_options.values_mut() {
3226 if !messages.contains_key(&option.extendee) {
3227 return Err(Error::new(
3228 0,
3229 format!("custom option extendee is not visible: {}", option.extendee),
3230 ));
3231 }
3232 let scope = option
3233 .full_name
3234 .rsplit_once('.')
3235 .map_or("", |(parent, _)| parent);
3236 resolve(&mut option.field.kind, scope, &message_names, &enum_names)?;
3237 validate_options(&option.field.options, OptionTarget::Field)?;
3238 }
3239 for extension in schema.extensions.values_mut() {
3240 let mut extendee_type = FieldType::Message(extension.extendee.clone());
3241 let scope = extension
3242 .full_name
3243 .rsplit_once('.')
3244 .map_or("", |(parent, _)| parent);
3245 resolve(&mut extendee_type, scope, &message_names, &enum_names)?;
3246 let FieldType::Message(extendee) = extendee_type else {
3247 return Err(Error::new(0, "extension target must be a message"));
3248 };
3249 let target = messages
3250 .get(&extendee)
3251 .ok_or_else(|| Error::new(0, "extension target is not visible"))?;
3252 if !target
3253 .extension_ranges
3254 .iter()
3255 .any(|(start, end)| (*start..=*end).contains(&extension.field.number))
3256 {
3257 return Err(Error::new(
3258 0,
3259 format!(
3260 "extension {} is outside the target's extension ranges",
3261 extension.full_name
3262 ),
3263 ));
3264 }
3265 if target.field_by_number(extension.field.number).is_some() {
3266 return Err(Error::new(
3267 0,
3268 "extension number collides with a regular field",
3269 ));
3270 }
3271 extension.extendee = extendee;
3272 resolve(
3273 &mut extension.field.kind,
3274 scope,
3275 &message_names,
3276 &enum_names,
3277 )?;
3278 validate_options(&extension.field.options, OptionTarget::Field)?;
3279 }
3280 let extensions: Vec<&ExtensionDescriptor> = schema.extensions.values().collect();
3281 for (index, extension) in extensions.iter().enumerate() {
3282 if extensions[..index].iter().any(|previous| {
3283 previous.extendee == extension.extendee
3284 && previous.field.number == extension.field.number
3285 }) {
3286 return Err(Error::new(
3287 0,
3288 format!(
3289 "duplicate extension number {} for {}",
3290 extension.field.number, extension.extendee
3291 ),
3292 ));
3293 }
3294 }
3295 for service in schema.services.values_mut() {
3296 for method in &mut service.methods {
3297 method.input_type = resolve_rpc_message(
3298 &method.input_type,
3299 &service.full_name,
3300 &message_names,
3301 &enum_names,
3302 )?;
3303 method.output_type = resolve_rpc_message(
3304 &method.output_type,
3305 &service.full_name,
3306 &message_names,
3307 &enum_names,
3308 )?;
3309 }
3310 }
3311 Ok(())
3312}
3313
3314fn reject_proto2_enum_reference(
3316 field_type: &FieldType,
3317 enums: &BTreeMap<String, Syntax>,
3318) -> Result<()> {
3319 match field_type {
3320 FieldType::Enum(name) if enums.get(name) == Some(&Syntax::Proto2) => Err(Error::new(
3321 0,
3322 format!("proto3 field cannot reference proto2 enum: {name}"),
3323 )),
3324 FieldType::Map(key, value) => {
3325 reject_proto2_enum_reference(key, enums)?;
3326 reject_proto2_enum_reference(value, enums)
3327 }
3328 _ => Ok(()),
3329 }
3330}
3331
3332fn resolve_rpc_message(
3334 source_name: &str,
3335 scope: &str,
3336 messages: &[String],
3337 enums: &[String],
3338) -> Result<String> {
3339 let mut field_type = FieldType::Message(source_name.to_string());
3340 resolve(&mut field_type, scope, messages, enums)?;
3341 match field_type {
3342 FieldType::Message(name) => Ok(name),
3343 FieldType::Enum(name) => Err(Error::new(
3344 0,
3345 format!("rpc endpoint must be a message, not enum: {name}"),
3346 )),
3347 _ => Err(Error::new(0, "rpc endpoint must be a message")),
3348 }
3349}
3350
3351fn validate_symbol_namespaces(schema: &Schema) -> Result<()> {
3353 let mut symbols = BTreeMap::<String, &'static str>::new();
3354 for name in schema.messages.keys() {
3355 if symbols.insert(name.clone(), "message").is_some() || schema.enums.contains_key(name) {
3356 return Err(Error::new(
3357 0,
3358 format!("conflicting declaration name: {name}"),
3359 ));
3360 }
3361 }
3362 for name in schema.enums.keys() {
3363 if symbols.insert(name.clone(), "enum").is_some() {
3364 return Err(Error::new(
3365 0,
3366 format!("conflicting declaration name: {name}"),
3367 ));
3368 }
3369 }
3370 for name in schema.services.keys() {
3371 if symbols.insert(name.clone(), "service").is_some() {
3372 return Err(Error::new(
3373 0,
3374 format!("conflicting declaration name: {name}"),
3375 ));
3376 }
3377 }
3378 for name in schema.custom_options.keys() {
3379 if symbols.insert(name.clone(), "custom option").is_some() {
3380 return Err(Error::new(
3381 0,
3382 format!("conflicting declaration name: {name}"),
3383 ));
3384 }
3385 }
3386 for descriptor in schema.messages.values() {
3387 for field in &descriptor.fields {
3388 let name = format!("{}.{}", descriptor.full_name, field.name);
3389 if symbols.insert(name.clone(), "field").is_some() {
3390 return Err(Error::new(
3391 0,
3392 format!("conflicting declaration name: {name}"),
3393 ));
3394 }
3395 }
3396 let mut oneofs = Vec::<&str>::new();
3397 for oneof in descriptor
3398 .fields
3399 .iter()
3400 .filter_map(|field| field.oneof.as_deref())
3401 {
3402 if oneofs.contains(&oneof) {
3403 continue;
3404 }
3405 oneofs.push(oneof);
3406 let name = format!("{}.{}", descriptor.full_name, oneof);
3407 if symbols.insert(name.clone(), "oneof").is_some() {
3408 return Err(Error::new(
3409 0,
3410 format!("conflicting declaration name: {name}"),
3411 ));
3412 }
3413 }
3414 }
3415 for enumeration in schema.enums.values() {
3416 let parent = enumeration
3417 .full_name
3418 .rsplit_once('.')
3419 .map_or("", |(parent, _)| parent);
3420 for value in &enumeration.values {
3421 let name = if parent.is_empty() {
3422 value.name.clone()
3423 } else {
3424 format!("{parent}.{}", value.name)
3425 };
3426 if symbols.insert(name.clone(), "enum value").is_some() {
3427 return Err(Error::new(
3428 0,
3429 format!("conflicting declaration name: {name}"),
3430 ));
3431 }
3432 }
3433 }
3434 Ok(())
3435}
3436
3437fn resolve(t: &mut FieldType, scope: &str, messages: &[String], enums: &[String]) -> Result<()> {
3443 match t {
3444 FieldType::Message(n) => {
3445 let absolute = n.starts_with('.');
3446 let raw = n.trim_start_matches('.');
3447 let mut candidates = Vec::new();
3448 if absolute {
3449 candidates.push(raw.to_string());
3450 } else {
3451 let mut current = scope;
3452 loop {
3453 candidates.push(format!("{current}.{raw}"));
3454 if let Some(index) = current.rfind('.') {
3455 current = ¤t[..index];
3456 } else {
3457 break;
3458 }
3459 }
3460 candidates.push(raw.to_string());
3461 }
3462 if let Some(name) = candidates.iter().find(|x| messages.contains(x)) {
3463 *n = name.clone();
3464 } else if let Some(name) = candidates.iter().find(|x| enums.contains(x)) {
3465 *t = FieldType::Enum(name.clone());
3466 } else {
3467 return Err(Error::new(0, format!("unknown type {n} in {scope}")));
3468 }
3469 }
3470 FieldType::Map(a, b) => {
3471 resolve(a, scope, messages, enums)?;
3472 resolve(b, scope, messages, enums)?;
3473 }
3474 _ => {}
3475 }
3476 Ok(())
3477}