Skip to main content

tabnas_proto/
detect_version.rs

1/* Copyright (c) 2026 Richard Rodger and other contributors, MIT License */
2
3//! Protobuf version detection and option reconciliation.
4//!
5//! Rust port of `ts/src/detect-version.ts`.
6
7use std::fmt;
8
9use serde::{Deserialize, Deserializer, Serialize};
10use tabnas::Value;
11
12use crate::error::ProtoError;
13use crate::node::nsrc;
14
15/// The protobuf version a file is read as.
16///
17/// The canonical runtime spells this as the string union
18/// `'proto2' | 'proto3' | '2023' | '2024'`, and [`ProtoVersion::as_str`]
19/// gives the same four strings.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
21pub enum ProtoVersion {
22    #[serde(rename = "proto2")]
23    Proto2,
24    #[serde(rename = "proto3")]
25    Proto3,
26    #[serde(rename = "2023")]
27    Edition2023,
28    #[serde(rename = "2024")]
29    Edition2024,
30}
31
32impl ProtoVersion {
33    /// The canonical spelling: `proto2`, `proto3`, `2023` or `2024`.
34    pub fn as_str(self) -> &'static str {
35        match self {
36            ProtoVersion::Proto2 => "proto2",
37            ProtoVersion::Proto3 => "proto3",
38            ProtoVersion::Edition2023 => "2023",
39            ProtoVersion::Edition2024 => "2024",
40        }
41    }
42
43    /// The version a declaration value names, or `None` for anything
44    /// outside the four this package supports.
45    pub fn from_declared(value: &str) -> Option<ProtoVersion> {
46        match value {
47            "proto2" => Some(ProtoVersion::Proto2),
48            "proto3" => Some(ProtoVersion::Proto3),
49            "2023" => Some(ProtoVersion::Edition2023),
50            "2024" => Some(ProtoVersion::Edition2024),
51            _ => None,
52        }
53    }
54}
55
56impl fmt::Display for ProtoVersion {
57    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
58        formatter.write_str(self.as_str())
59    }
60}
61
62impl<'de> Deserialize<'de> for ProtoVersion {
63    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
64        let text = String::deserialize(deserializer)?;
65        ProtoVersion::from_declared(&text)
66            .ok_or_else(|| serde::de::Error::custom(format!("proto: unknown version {:?}", text)))
67    }
68}
69
70/// Whether `version` is an edition version (2023 or 2024).
71pub fn is_edition(version: ProtoVersion) -> bool {
72    matches!(
73        version,
74        ProtoVersion::Edition2023 | ProtoVersion::Edition2024
75    )
76}
77
78/// The `FileDescriptorProto` edition enum name for a version, such as
79/// `EDITION_2023`.
80///
81/// A syntax file records `syntax`; an edition file records both
82/// `syntax: "editions"` and this.
83pub fn edition_enum(version: ProtoVersion) -> String {
84    format!("EDITION_{}", version.as_str())
85}
86
87/// The declared version in a `syntaxOrEdition` CST node, or `None` when
88/// the file has no leading `syntax` or `edition` declaration.
89///
90/// The node's `src` is whitespace-stripped, for example
91/// `syntax="proto3";` or `edition="2023";`.
92pub fn declared_version(node: &Value) -> Result<Option<ProtoVersion>, ProtoError> {
93    declared_version_src(nsrc(node))
94}
95
96/// [`declared_version`] over the node's `src` directly.
97///
98/// The canonical runtime answers `null` for a node with no string `src`,
99/// which here is the empty string and the same answer.
100pub fn declared_version_src(src: &str) -> Result<Option<ProtoVersion>, ProtoError> {
101    // The canonical `/^(syntax|edition)=["']([^"']+)["']/`, written out:
102    // the regexp crate reads a character class Unicode-aware where this
103    // one is plain ASCII, and the whole pattern is four literal steps.
104    let Some((keyword, rest)) = keyword_of(src) else {
105        return Ok(None);
106    };
107    let Some(rest) = rest.strip_prefix('=') else {
108        return Ok(None);
109    };
110    let mut chars = rest.char_indices();
111    match chars.next() {
112        Some((_, '"' | '\'')) => {}
113        _ => return Ok(None),
114    }
115    // `[^"']+` is greedy and the closing `["']` can only land where the
116    // run stops, so there is no backtracking to reproduce: scan to the
117    // first quote of either kind and require at least one character
118    // before it.
119    let body = &rest[1..];
120    let Some(end) = body.find(['"', '\'']) else {
121        return Ok(None);
122    };
123    if 0 == end {
124        return Ok(None);
125    }
126    let value = &body[..end];
127
128    match ProtoVersion::from_declared(value) {
129        Some(version) => Ok(Some(version)),
130        None => Err(ProtoError::Version(format!(
131            "proto: unknown {keyword} version \"{value}\""
132        ))),
133    }
134}
135
136/// The `(syntax|edition)` alternation at the head of `src`.
137fn keyword_of(src: &str) -> Option<(&'static str, &str)> {
138    if let Some(rest) = src.strip_prefix("syntax") {
139        return Some(("syntax", rest));
140    }
141    src.strip_prefix("edition").map(|rest| ("edition", rest))
142}
143
144/// Reconcile the version declared in the source with the version supplied
145/// through the options.
146///
147/// With `reconcile` true (the default) a mismatch is an error; otherwise
148/// the declaration wins when present. Falls back to proto2, which is what
149/// protoc assumes for a file with neither.
150pub fn resolve_version(
151    declared: Option<ProtoVersion>,
152    option: Option<ProtoVersion>,
153    reconcile: bool,
154) -> Result<ProtoVersion, ProtoError> {
155    if let (Some(declared), Some(option)) = (declared, option) {
156        if declared != option {
157            if reconcile {
158                return Err(ProtoError::Version(format!(
159                    "proto: version mismatch \u{2014} option \"{option}\" but the file \
160                     declares \"{declared}\". Set reconcile:false to let the file win."
161                )));
162            }
163            return Ok(declared);
164        }
165    }
166    Ok(declared.or(option).unwrap_or(ProtoVersion::Proto2))
167}