use tabnas::Value;
use crate::descriptor::{
scalar_type, DescriptorProto, DescriptorRange, EnumDescriptorProto, EnumValueDescriptorProto,
FieldDescriptorProto, FieldLabel, FieldType, FileDescriptorProto, MethodDescriptorProto,
OneofDescriptorProto, OptionValue, Options, ServiceDescriptorProto, SymbolVisibility,
MAX_ENUM_NUMBER, MAX_FIELD_NUMBER_END, MAX_MESSAGE_SET_END,
};
use crate::detect_version::{edition_enum, is_edition, ProtoVersion};
use crate::error::ProtoError;
use crate::jsnum::{is_js_whitespace, js_number};
use crate::node::{child, child_rules, children, gaps_before, kw, nrule, nsrc, src_or};
use crate::order::Order;
pub const MAX_NESTING_DEPTH: usize = 100;
struct Walk {
depth: usize,
too_deep: bool,
}
impl Walk {
fn new() -> Self {
Walk {
depth: 0,
too_deep: false,
}
}
fn enter(&mut self) -> bool {
if self.depth >= MAX_NESTING_DEPTH {
self.too_deep = true;
return false;
}
self.depth += 1;
true
}
fn leave(&mut self) {
self.depth -= 1;
}
}
fn strip_ws(src: &str) -> String {
src.chars().filter(|ch| !is_js_whitespace(*ch)).collect()
}
fn unquote(text: &str) -> &str {
let quote = |ch: char| '"' == ch || '\'' == ch;
let mut forward = text.char_indices();
let Some((_, first)) = forward.next() else {
return text;
};
if !quote(first) {
return text;
}
let Some((last_at, last)) = text.char_indices().next_back() else {
return text;
};
if 0 == last_at || !quote(last) {
return text;
}
&text[first.len_utf8()..last_at]
}
fn numeric_lead(text: &str) -> bool {
let bytes = text.as_bytes();
let mut at = 0;
if at < bytes.len() && (b'-' == bytes[at] || b'+' == bytes[at]) {
at += 1;
}
let Some(&first) = bytes.get(at) else {
return false;
};
if first.is_ascii_digit() {
return true;
}
if b'.' == first {
return bytes.get(at + 1).is_some_and(u8::is_ascii_digit);
}
if b'0' == first {
return matches!(
bytes.get(at + 1),
Some(b'x' | b'X' | b'o' | b'O' | b'b' | b'B')
);
}
false
}
fn number_of(node: Option<&Value>) -> f64 {
match node {
None => 0.0,
Some(node) => js_number(nsrc(node)).unwrap_or(f64::NAN),
}
}
fn constant_value(node: &Value) -> OptionValue {
if let Value::Object(entries) = node {
if let Some(Value::String(text)) = entries.get("aggregate") {
return OptionValue::Str(text.clone());
}
}
let src = nsrc(node);
if "true" == src {
return OptionValue::Bool(true);
}
if "false" == src {
return OptionValue::Bool(false);
}
if src.starts_with(['"', '\'']) {
return OptionValue::Str(unquote(src).to_string());
}
if numeric_lead(src) {
if let Some(number) = js_number(src.strip_prefix('+').unwrap_or(src)) {
return OptionValue::Number(number);
}
}
OptionValue::Str(src.to_string())
}
fn option_name_of<'a>(stmt: &'a Value, value: Option<&Value>) -> &'a str {
if let Some(named) = child(stmt, "optionName") {
return nsrc(named);
}
let Some(value) = value else {
return "";
};
let src = nsrc(stmt);
let head = src.strip_suffix(';').unwrap_or(src);
let tail = format!("={}", nsrc(value));
if let Some(name) = head.strip_suffix(&tail) {
return name;
}
match head.find(nsrc(value)) {
None | Some(0) => "",
Some(at) => {
let name = &head[..at];
name.strip_suffix('=').unwrap_or(name)
}
}
}
#[derive(Default)]
struct PseudoOptions {
options: Option<Options>,
json_name: Option<String>,
default_value: Option<String>,
}
fn read_field_options(opts: Option<&Value>) -> PseudoOptions {
let mut out = PseudoOptions::default();
let Some(opts) = opts else {
return out;
};
let mut map = Options::new();
for option in child_rules(opts) {
let constant = child(option, "constant");
let name = option_name_of(option, constant);
let (Some(constant), false) = (constant, name.is_empty()) else {
continue;
};
if "json_name" == name {
out.json_name = Some(unquote(nsrc(constant)).to_string());
continue;
}
if "default" == name {
out.default_value = Some(unquote(nsrc(constant)).to_string());
continue;
}
if "__proto__" == name {
continue;
}
map.insert(name.to_string(), constant_value(constant));
}
if !map.is_empty() {
out.options = Some(map);
}
out
}
fn plain_options(opts: Option<&Value>) -> Option<Options> {
read_field_options(opts).options
}
fn option_from(element: &Value) -> Option<(String, OptionValue)> {
let constant = child(element, "constant")?;
let name = option_name_of(element, Some(constant));
if name.is_empty() {
return None;
}
Some((name.to_string(), constant_value(constant)))
}
fn merge_option(target: &mut Option<Options>, element: &Value) {
let options = target.get_or_insert_with(Options::new);
if let Some((name, value)) = option_from(element) {
options.insert(name, value);
}
}
fn features(opts: Option<&Options>) -> Option<Options> {
let opts = opts?;
let out: Options = opts
.iter()
.filter(|(name, _)| "features" == name.as_str() || name.starts_with("features."))
.map(|(name, value)| (name.clone(), value.clone()))
.collect();
if out.is_empty() {
None
} else {
Some(out)
}
}
fn field_label(label: Option<&Value>, version: ProtoVersion) -> (FieldLabel, bool) {
match src_or(label) {
"required" => (FieldLabel::Required, false),
"repeated" => (FieldLabel::Repeated, false),
"optional" => (FieldLabel::Optional, ProtoVersion::Proto3 == version),
_ => (FieldLabel::Optional, false),
}
}
fn field_type_name(type_text: &str) -> (Option<FieldType>, Option<String>) {
if !type_text.starts_with('.') {
if let Some(scalar) = scalar_type(type_text) {
return (Some(scalar), None);
}
}
(None, Some(type_text.to_string()))
}
fn type_node_of(node: &Value) -> Option<&Value> {
child(node, "fieldType")
.or_else(|| child(node, "messageType"))
.or_else(|| child(node, "fullIdent"))
}
fn apply_field_options(field: &mut FieldDescriptorProto, opts: Option<&Value>) {
let pseudo = read_field_options(opts);
if let Some(json_name) = pseudo.json_name {
field.json_name = Some(json_name);
}
if let Some(default_value) = pseudo.default_value {
field.default_value = Some(default_value);
}
if let Some(options) = pseudo.options {
field.options = Some(options);
}
}
fn build_field(node: &Value, version: ProtoVersion) -> FieldDescriptorProto {
let (label, proto3_optional) = field_label(child(node, "label"), version);
let (field_type, type_name) = field_type_name(src_or(type_node_of(node)));
let mut field = FieldDescriptorProto {
name: src_or(child(node, "ident")).to_string(),
number: number_of(child(node, "fieldNumber")),
label: Some(label),
r#type: field_type,
type_name,
proto3_optional,
..FieldDescriptorProto::default()
};
apply_field_options(&mut field, child(node, "fieldOptions"));
field
}
fn build_group(
node: &Value,
version: ProtoVersion,
into: &mut DescriptorProto,
into_order: &mut Order,
walk: &mut Walk,
) -> FieldDescriptorProto {
let group_name = src_or(child(node, "ident")).to_string();
let (nested, nested_order) = message_from_body(
group_name.clone(),
child(node, "messageBody"),
version,
walk,
);
into_order.put("nestedType", into.nested_type.len(), nested_order);
into.nested_type.push(nested);
let (label, proto3_optional) = field_label(child(node, "label"), version);
let mut field = FieldDescriptorProto {
name: group_name.to_lowercase(),
number: number_of(child(node, "fieldNumber")),
label: Some(label),
r#type: Some(FieldType::Group),
type_name: Some(group_name),
proto3_optional,
..FieldDescriptorProto::default()
};
apply_field_options(&mut field, child(node, "fieldOptions"));
field
}
fn is_group(node: &Value) -> bool {
child(node, "fieldNumber").is_some() && child(node, "messageBody").is_some()
}
fn map_entry_name(field_name: &str) -> String {
let mut out = String::with_capacity(field_name.len() + 5);
let mut cap_next = true;
for ch in field_name.chars() {
if '_' == ch {
cap_next = true;
continue;
}
if cap_next && ch.is_ascii_lowercase() {
out.push(ch.to_ascii_uppercase());
} else {
out.push(ch);
}
cap_next = false;
}
out.push_str("Entry");
out
}
fn build_map_field(node: &Value, into: &mut DescriptorProto) -> FieldDescriptorProto {
let types = children(node, "fieldType");
let key_text = types.first().map_or("", |node| nsrc(node));
let value_text = types.get(1).map_or("", |node| nsrc(node));
let field_name = src_or(child(node, "ident")).to_string();
let entry_name = map_entry_name(&field_name);
let (key_type, key_type_name) = field_type_name(key_text);
let (value_type, value_type_name) = field_type_name(value_text);
let mut entry = DescriptorProto::new(entry_name.clone());
entry.field.push(FieldDescriptorProto {
name: "key".to_string(),
number: 1.0,
label: Some(FieldLabel::Optional),
r#type: key_type,
type_name: key_type_name,
..FieldDescriptorProto::default()
});
entry.field.push(FieldDescriptorProto {
name: "value".to_string(),
number: 2.0,
label: Some(FieldLabel::Optional),
r#type: value_type,
type_name: value_type_name,
..FieldDescriptorProto::default()
});
let mut entry_options = Options::new();
entry_options.insert("mapEntry".to_string(), OptionValue::Bool(true));
entry.options = Some(entry_options);
let mut field = FieldDescriptorProto {
name: field_name,
number: number_of(child(node, "fieldNumber")),
label: Some(FieldLabel::Repeated),
type_name: Some(entry_name),
..FieldDescriptorProto::default()
};
apply_field_options(&mut field, child(node, "fieldOptions"));
if let Some(feature_options) = features(field.options.as_ref()) {
entry.field[0].options = Some(feature_options.clone());
entry.field[1].options = Some(feature_options);
}
into.nested_type.push(entry);
field
}
fn build_enum(node: &Value) -> (EnumDescriptorProto, Order) {
let mut out = EnumDescriptorProto::new(src_or(child(node, "ident")));
let mut order = Order::default();
for element in children(node, "enumElement") {
let kids = child_rules(element);
let Some(first) = kids.first() else {
continue;
};
match nrule(first) {
"ranges" | "fieldNames" => {
add_reserved(
element,
&mut out.reserved_range,
&mut out.reserved_name,
&mut order,
RangeOpts {
exclusive: false,
max: MAX_ENUM_NUMBER,
},
);
continue;
}
"optionName" => {
order.record("options");
merge_option(&mut out.options, element);
continue;
}
"fieldNumber" => {}
_ => continue,
}
let gap = gaps_before(element, "fieldNumber")
.first()
.copied()
.unwrap_or("");
let name = strip_from_equals(gap);
if name.is_empty() {
continue;
}
let value = number_of(Some(first));
out.value.push(EnumValueDescriptorProto {
name: name.to_string(),
number: if gap.ends_with('-') { -value } else { value },
options: plain_options(child(element, "fieldOptions")),
});
}
(out, order)
}
fn strip_from_equals(text: &str) -> &str {
let terminator = |ch: char| matches!(ch, '\n' | '\r' | '\u{2028}' | '\u{2029}');
for (at, ch) in text.char_indices() {
if '=' == ch && !text[at..].contains(terminator) {
return &text[..at];
}
}
text
}
#[derive(Clone, Copy)]
struct RangeOpts {
exclusive: bool,
max: f64,
}
fn ranges(node: Option<&Value>, opts: RangeOpts) -> Vec<DescriptorRange> {
let Some(node) = node else {
return Vec::new();
};
let flat = strip_ws(nsrc(node));
let mut out = Vec::new();
for part in flat.split(',') {
let Some((start_text, bound)) = split_range(part) else {
continue;
};
let start = js_number(start_text).unwrap_or(f64::NAN);
let end = match bound {
None => {
if opts.exclusive {
start + 1.0
} else {
start
}
}
Some("max") => opts.max,
Some(text) => {
let value = js_number(text).unwrap_or(f64::NAN);
if opts.exclusive {
value + 1.0
} else {
value
}
}
};
out.push(DescriptorRange::new(start, end));
}
out
}
fn split_range(part: &str) -> Option<(&str, Option<&str>)> {
let bytes = part.as_bytes();
let mut at = 0;
if at < bytes.len() && b'-' == bytes[at] {
at += 1;
}
let digits_from = at;
while at < bytes.len() && bytes[at].is_ascii_digit() {
at += 1;
}
if digits_from == at {
return None;
}
let start = &part[..at];
if at == bytes.len() {
return Some((start, None));
}
let rest = part[at..].strip_prefix("to")?;
if "max" == rest {
return Some((start, Some("max")));
}
let bytes = rest.as_bytes();
let mut at = 0;
if at < bytes.len() && b'-' == bytes[at] {
at += 1;
}
let digits_from = at;
while at < bytes.len() && bytes[at].is_ascii_digit() {
at += 1;
}
if digits_from == at || at != bytes.len() {
return None;
}
Some((start, Some(rest)))
}
fn reserved_names(node: &Value) -> Vec<String> {
let src = nsrc(node);
let body = src.strip_prefix("reserved").unwrap_or(src);
let body = body.strip_suffix(';').unwrap_or(body);
let mut out = Vec::new();
let bytes = body.as_bytes();
let mut at = 0;
while at < bytes.len() {
if let Some((text, next)) = scan_quoted(body, at, b'"') {
out.push(text.to_string());
at = next;
continue;
}
if let Some((text, next)) = scan_quoted(body, at, b'\'') {
out.push(text.to_string());
at = next;
continue;
}
if let Some((text, next)) = scan_identifier(body, at) {
out.push(text.to_string());
at = next;
continue;
}
at += 1;
while at < bytes.len() && !body.is_char_boundary(at) {
at += 1;
}
}
out
}
fn scan_quoted(body: &str, at: usize, quote: u8) -> Option<(&str, usize)> {
let bytes = body.as_bytes();
if bytes.get(at) != Some("e) {
return None;
}
let start = at + 1;
let mut cursor = start;
while cursor < bytes.len() {
let byte = bytes[cursor];
if byte == quote {
return Some((&body[start..cursor], cursor + 1));
}
if b'\\' == byte {
let rest = &body[cursor + 1..];
let next = rest.chars().next()?;
if matches!(next, '\n' | '\r' | '\u{2028}' | '\u{2029}') {
return None;
}
cursor += 1 + next.len_utf8();
continue;
}
cursor += 1;
while cursor < bytes.len() && !body.is_char_boundary(cursor) {
cursor += 1;
}
}
None
}
fn scan_identifier(body: &str, at: usize) -> Option<(&str, usize)> {
let bytes = body.as_bytes();
let first = *bytes.get(at)?;
if !(first.is_ascii_alphabetic() || b'_' == first) {
return None;
}
let mut cursor = at + 1;
while cursor < bytes.len() && (bytes[cursor].is_ascii_alphanumeric() || b'_' == bytes[cursor]) {
cursor += 1;
}
Some((&body[at..cursor], cursor))
}
fn add_reserved(
node: &Value,
reserved_range: &mut Option<Vec<DescriptorRange>>,
reserved_name: &mut Option<Vec<String>>,
order: &mut Order,
opts: RangeOpts,
) {
if let Some(node_ranges) = child(node, "ranges") {
order.record("reservedRange");
reserved_range
.get_or_insert_with(Vec::new)
.extend(ranges(Some(node_ranges), opts));
return;
}
let names = reserved_names(node);
if !names.is_empty() {
order.record("reservedName");
reserved_name.get_or_insert_with(Vec::new).extend(names);
}
}
fn build_message(node: &Value, version: ProtoVersion, walk: &mut Walk) -> (DescriptorProto, Order) {
message_from_body(
src_or(child(node, "ident")).to_string(),
child(node, "messageBody"),
version,
walk,
)
}
fn message_from_body(
name: String,
body: Option<&Value>,
version: ProtoVersion,
walk: &mut Walk,
) -> (DescriptorProto, Order) {
let mut message = DescriptorProto::new(name);
let mut order = Order::default();
if !walk.enter() {
return (message, order);
}
let elements = body.map_or_else(Vec::new, |body| children(body, "messageElement"));
for element in &elements {
if is_option_stmt(element) {
merge_option(&mut message.options, element);
}
}
let opts = RangeOpts {
exclusive: true,
max: if is_message_set(&message) {
MAX_MESSAGE_SET_END
} else {
MAX_FIELD_NUMBER_END
},
};
for element in &elements {
if !is_option_stmt(element) {
add_message_element(element, version, &mut message, &mut order, opts, walk);
}
}
generate_synthetic_oneofs(&mut message);
walk.leave();
(message, order)
}
fn is_message_set(message: &DescriptorProto) -> bool {
matches!(
message
.options
.as_ref()
.and_then(|options| options.get("message_set_wire_format")),
Some(OptionValue::Bool(true))
)
}
fn is_option_stmt(element: &Value) -> bool {
kw(element).starts_with("option")
}
fn generate_synthetic_oneofs(message: &mut DescriptorProto) {
let mut names: Vec<String> = Vec::new();
for field in &message.field {
names.push(field.name.clone());
}
for oneof in &message.oneof_decl {
names.push(oneof.name.clone());
}
for index in 0..message.field.len() {
if !message.field[index].proto3_optional || message.field[index].oneof_index.is_some() {
continue;
}
let mut oneof_name = format!("_{}", message.field[index].name);
while names.contains(&oneof_name) {
oneof_name = format!("X{oneof_name}");
}
names.push(oneof_name.clone());
message.field[index].oneof_index = Some(message.oneof_decl.len());
message.oneof_decl.push(OneofDescriptorProto {
name: oneof_name,
options: None,
});
}
}
fn add_message_element(
element: &Value,
version: ProtoVersion,
message: &mut DescriptorProto,
order: &mut Order,
opts: RangeOpts,
walk: &mut Walk,
) {
let keyword = kw(element);
let first = child_rules(element).first().copied();
if keyword.starts_with("map<") {
let field = build_map_field(element, message);
message.field.push(field);
return;
}
if keyword.starts_with("oneof") {
add_oneof(element, version, message, order, walk);
return;
}
if keyword.starts_with("export") || keyword.starts_with("local") {
let (messages, enums) = (&mut message.nested_type, &mut message.enum_type);
let lists = Lists {
messages,
enums,
order,
message_list: "nestedType",
};
add_visible(element, keyword, version, lists, walk);
return;
}
if is_group(element) {
let field = build_group(element, version, message, order, walk);
message.field.push(field);
return;
}
if keyword.starts_with("message") {
let (nested, nested_order) = build_message(element, version, walk);
order.put("nestedType", message.nested_type.len(), nested_order);
message.nested_type.push(nested);
return;
}
if keyword.starts_with("enum") {
let (built, built_order) = build_enum(element);
order.put("enumType", message.enum_type.len(), built_order);
message.enum_type.push(built);
return;
}
if keyword.starts_with("reserved") {
add_reserved(
element,
&mut message.reserved_range,
&mut message.reserved_name,
order,
opts,
);
return;
}
if keyword.starts_with("extensions") {
let extension_options = plain_options(child(element, "fieldOptions"));
let mut rs = ranges(child(element, "ranges"), opts);
if let Some(extension_options) = extension_options {
for range in &mut rs {
range.options = Some(extension_options.clone());
}
}
order.record("extensionRange");
message
.extension_range
.get_or_insert_with(Vec::new)
.extend(rs);
return;
}
if keyword.starts_with("extend") {
add_extend(element, version, &mut message.extension);
return;
}
if ";" == nsrc(element) {
return; }
if let Some(first) = first {
if "fieldType" == nrule(first) || "label" == nrule(first) {
message.field.push(build_field(element, version));
}
}
}
struct Lists<'a> {
messages: &'a mut Vec<DescriptorProto>,
enums: &'a mut Vec<EnumDescriptorProto>,
order: &'a mut Order,
message_list: &'static str,
}
fn add_visible(
element: &Value,
keyword: &str,
version: ProtoVersion,
lists: Lists<'_>,
walk: &mut Walk,
) {
let visibility = if keyword.starts_with("export") {
SymbolVisibility::Export
} else {
SymbolVisibility::Local
};
if let Some(node) = child(element, "message") {
let (mut built, built_order) = build_message(node, version, walk);
built.visibility = Some(visibility);
lists
.order
.put(lists.message_list, lists.messages.len(), built_order);
lists.messages.push(built);
} else if let Some(node) = child(element, "enumDef") {
let (mut built, built_order) = build_enum(node);
built.visibility = Some(visibility);
lists.order.put("enumType", lists.enums.len(), built_order);
lists.enums.push(built);
}
}
fn add_oneof(
element: &Value,
version: ProtoVersion,
message: &mut DescriptorProto,
order: &mut Order,
walk: &mut Walk,
) {
let name = src_or(child(element, "ident")).to_string();
let index = message.oneof_decl.len();
message.oneof_decl.push(OneofDescriptorProto {
name,
options: None,
});
let mut decl_options: Option<Options> = None;
for member in children(element, "oneofElement") {
if kw(member).starts_with("option") {
merge_option(&mut decl_options, member);
continue;
}
if ";" == nsrc(member) {
continue;
}
let mut field = if is_group(member) {
build_group(member, version, message, order, walk)
} else {
build_field(member, version)
};
field.oneof_index = Some(index);
field.proto3_optional = false;
message.field.push(field);
}
message.oneof_decl[index].options = decl_options;
}
fn add_extend(element: &Value, version: ProtoVersion, into: &mut Vec<FieldDescriptorProto>) {
let extendee = child(element, "messageType").map(|node| nsrc(node).to_string());
for node in child_rules(element) {
let rule = nrule(node);
if "field" != rule && "messageElement" != rule {
continue;
}
let mut field = build_field(node, version);
field.extendee = extendee.clone();
into.push(field);
}
}
fn build_service(node: &Value) -> ServiceDescriptorProto {
let mut service = ServiceDescriptorProto {
name: src_or(child(node, "ident")).to_string(),
method: Vec::new(),
options: None,
};
for element in children(node, "serviceElement") {
if kw(element).starts_with("rpc") {
service.method.push(build_rpc(element));
} else if is_option_stmt(element) {
merge_option(&mut service.options, element);
}
}
service
}
fn parenthesised(src: &str) -> Vec<&str> {
let mut out = Vec::new();
let mut at = 0;
while out.len() < 2 {
let Some(open) = src[at..].find('(').map(|i| i + at) else {
break;
};
let Some(close) = src[open + 1..].find(')').map(|i| i + open + 1) else {
break;
};
out.push(&src[open + 1..close]);
at = close + 1;
}
out
}
fn build_rpc(element: &Value) -> MethodDescriptorProto {
let ids = children(element, "ident");
let types = children(element, "messageType");
let mut method = MethodDescriptorProto {
name: ids
.first()
.map_or(String::new(), |node| nsrc(node).to_string()),
input_type: types
.first()
.map_or(String::new(), |node| nsrc(node).to_string()),
output_type: types
.get(1)
.map_or(String::new(), |node| nsrc(node).to_string()),
client_streaming: false,
server_streaming: false,
options: None,
};
let spans = parenthesised(nsrc(element));
if spans
.first()
.is_some_and(|span| *span == format!("stream{}", method.input_type))
{
method.client_streaming = true;
}
if spans
.get(1)
.is_some_and(|span| *span == format!("stream{}", method.output_type))
{
method.server_streaming = true;
}
for option in children(element, "optionStmt") {
merge_option(&mut method.options, option);
}
method
}
pub fn build_file(proto: &Value, version: ProtoVersion) -> Result<FileDescriptorProto, ProtoError> {
build_file_ordered(proto, version).map(|(file, _)| file)
}
pub(crate) fn build_file_ordered(
proto: &Value,
version: ProtoVersion,
) -> Result<(FileDescriptorProto, Order), ProtoError> {
let mut walk = Walk::new();
let mut file = FileDescriptorProto::default();
let mut order = Order::default();
if is_edition(version) {
file.edition = Some(edition_enum(version));
file.syntax = Some("editions".to_string());
} else {
file.syntax = Some(version.as_str().to_string());
}
for def in children(proto, "topLevelDef") {
let keyword = kw(def);
if keyword.starts_with("package") {
order.record("package");
if let Some(node) = child(def, "fullIdent") {
file.package = Some(nsrc(node).to_string());
}
} else if keyword.starts_with("import") {
if let Some(node) = child(def, "strLit") {
let target = unquote(nsrc(node)).to_string();
if keyword.contains("option") {
order.record("optionDependency");
file.option_dependency
.get_or_insert_with(Vec::new)
.push(target);
} else {
let index = file.dependency.len();
file.dependency.push(target);
if keyword.contains("public") {
file.public_dependency.push(index);
}
if keyword.contains("weak") {
file.weak_dependency.push(index);
}
}
}
} else if is_option_stmt(def) {
order.record("options");
merge_option(&mut file.options, def);
} else if keyword.starts_with("export") || keyword.starts_with("local") {
let (messages, enums) = (&mut file.message_type, &mut file.enum_type);
let lists = Lists {
messages,
enums,
order: &mut order,
message_list: "messageType",
};
add_visible(def, keyword, version, lists, &mut walk);
} else if keyword.starts_with("message") {
let (built, built_order) = build_message(def, version, &mut walk);
order.put("messageType", file.message_type.len(), built_order);
file.message_type.push(built);
} else if keyword.starts_with("enum") {
let (built, built_order) = build_enum(def);
order.put("enumType", file.enum_type.len(), built_order);
file.enum_type.push(built);
} else if keyword.starts_with("service") {
file.service.push(build_service(def));
} else if keyword.starts_with("extend") {
add_extend(def, version, &mut file.extension);
}
}
if walk.too_deep {
return Err(ProtoError::TooDeep(format!(
"proto: document nests deeper than {MAX_NESTING_DEPTH} levels"
)));
}
Ok((file, order))
}
const KEYWORDS: [&str; 26] = [
"edition",
"enum",
"export",
"extend",
"extensions",
"group",
"import",
"local",
"map",
"max",
"message",
"oneof",
"option",
"optional",
"package",
"public",
"repeated",
"required",
"reserved",
"returns",
"rpc",
"service",
"stream",
"syntax",
"to",
"weak",
];
const SEPARATORS: &[u8] = b" \t\r\n[]:,;=()<>-.+";
fn is_word(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || b'_' == byte
}
pub(crate) fn brace_depth(src: &str) -> usize {
let bytes = src.as_bytes();
let mut at = 0;
let mut depth: usize = 0;
let mut deepest: usize = 0;
let mut start = true;
while at < bytes.len() {
match bytes[at] {
b'{' => {
depth += 1;
deepest = deepest.max(depth);
at += 1;
start = true;
}
b'}' => {
depth = depth.saturating_sub(1);
at += 1;
start = true;
}
byte if SEPARATORS.contains(&byte) => {
at += 1;
start = true;
}
byte @ (b'#' | b'/') if b'#' == byte || Some(&b'/') == bytes.get(at + 1) => {
while at < bytes.len() && b'\n' != bytes[at] && b'\r' != bytes[at] {
at += 1;
}
start = true;
}
b'/' if Some(&b'*') == bytes.get(at + 1) => {
at += 2;
while at < bytes.len() && !(b'*' == bytes[at] && Some(&b'/') == bytes.get(at + 1)) {
at += 1;
}
at += 2;
start = true;
}
quote @ (b'"' | b'\'' | b'`') if start => {
at += 1;
while at < bytes.len() && bytes[at] != quote {
at += if b'\\' == bytes[at] { 2 } else { 1 };
}
at += 1;
start = true;
}
byte if start && is_word(byte) => {
let from = at;
while at < bytes.len() && is_word(bytes[at]) {
at += 1;
}
start = KEYWORDS.contains(&&src[from..at]);
}
_ => {
at += 1;
start = false;
}
}
}
deepest
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unquote_needs_two_characters() {
assert_eq!(unquote("\"abc\""), "abc");
assert_eq!(unquote("'abc'"), "abc");
assert_eq!(unquote("\"abc'"), "abc");
assert_eq!(unquote("\"\""), "");
assert_eq!(unquote("\""), "\"");
assert_eq!(unquote("abc"), "abc");
assert_eq!(unquote("\"\u{1F600}"), "\"\u{1F600}");
assert_eq!(unquote("\"\u{1F600}\""), "\u{1F600}");
}
#[test]
fn strip_from_equals_stops_at_a_line_terminator() {
assert_eq!(strip_from_equals("A="), "A");
assert_eq!(strip_from_equals("A"), "A");
assert_eq!(strip_from_equals("a=b\nc=d"), "a=b\nc");
}
#[test]
fn brace_depth_skips_strings_and_comments() {
assert_eq!(brace_depth("message M { message N { } }"), 2);
assert_eq!(brace_depth("option a = \"{{{{\";"), 0);
assert_eq!(brace_depth("// {{{{\nmessage M {}"), 1);
assert_eq!(brace_depth("/* {{{{ */ message M {}"), 1);
assert_eq!(brace_depth("# {{{{\nmessage M {}"), 1);
assert_eq!(brace_depth("}}}}"), 0);
assert_eq!(brace_depth("// x\rmessage M {}"), 1);
assert_eq!(brace_depth("# x\rmessage M {}"), 1);
assert_eq!(brace_depth("option a = `{{\n{{`;"), 0);
assert_eq!(brace_depth("option a = `\\`{{`;"), 0);
assert_eq!(brace_depth("message a\"b { }"), 1);
assert_eq!(brace_depth("message M { reserved\"}\"; message N { } }"), 2);
assert_eq!(brace_depth("message M { reserve\"}\"; message N { } }"), 1);
}
}