Skip to main content

nichlink/registry_core/declaration/
owned.rs

1//! Owned (heap-backed) twins of the declaration vocabulary.
2//! 声明词表的 owned(堆分配)孪生类型。
3
4use super::*;
5use crate::registry_core::lexicon::path_is_under;
6
7impl fmt::Display for OwnedSourceLocation {
8    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
9        write!(
10            formatter,
11            "{}:{}:{}",
12            portable_path(&self.file),
13            self.line,
14            self.column
15        )
16    }
17}
18
19impl OwnedSourceLocation {
20    /// The declaration's source path with `/` separators on every platform.
21    /// 该声明的源码路径,在任何平台上都以 `/` 分隔。
22    pub fn portable_file(&self) -> String {
23        portable_path(&self.file)
24    }
25
26    /// Render the source location with its logical function name.
27    /// 渲染带逻辑函数名的源码位置。
28    pub fn describe(&self) -> String {
29        format!("{} function={}", self, self.function)
30    }
31}
32
33/// Owned twin of [`LocalizedText`] for reloadable declarations.
34/// [`LocalizedText`] 的 owned 孪生,供可热重载声明使用。
35#[derive(Clone, Debug, PartialEq, Eq)]
36pub struct OwnedLocalizedText {
37    /// Label text shown to Chinese readers.
38    /// 面向中文读者的标签文本。
39    pub zh: String,
40    /// Label text shown to English readers.
41    /// 面向英文读者的标签文本。
42    pub en: String,
43}
44
45/// Owned twin of [`RequirementSpec`] for reloadable declarations.
46/// [`RequirementSpec`] 的 owned 孪生,供可热重载声明使用。
47#[derive(Clone, Debug, PartialEq, Eq)]
48pub struct OwnedRequirementSpec {
49    /// Capability name this declaration requires.
50    /// 本声明所要求的能力名称。
51    pub capability: String,
52    /// Object expected to provide that capability.
53    /// 本应提供该能力的对象。
54    pub provider: String,
55}
56
57/// Owned twin of [`Admission`], the external-dependency gate.
58/// [`Admission`] 的 owned 孪生:外部依赖门禁。
59#[derive(Clone, Debug, PartialEq, Eq)]
60pub struct OwnedAdmission {
61    /// Path prefixes this gate admits; empty admits every path.
62    /// 本门禁允许的路径前缀;为空表示允许任何路径。
63    pub allowed_paths: Vec<String>,
64    /// Path prefixes this gate rejects before consulting the allow list.
65    /// 在查看允许列表之前即被拒绝的路径前缀。
66    pub denied_paths: Vec<String>,
67}
68
69/// Owned twin of [`RegistrationRule`], the structural entry rule.
70/// [`RegistrationRule`] 的 owned 孪生:注册面的结构入门规范。
71#[derive(Clone, Debug, PartialEq, Eq)]
72pub struct OwnedRegistrationRule {
73    /// Preset name the face must declare, when one is required.
74    /// 注册面必须声明的 preset 名称(若有要求)。
75    pub required_preset: Option<String>,
76    /// Structural parts the face must provide.
77    /// 注册面必须提供的结构 parts。
78    pub required_parts: Vec<String>,
79    /// Export names the face must declare.
80    /// 注册面必须声明的导出名称。
81    pub required_exports: Vec<String>,
82    /// Interfaces the handle type must implement, for example `ControlHandle`.
83    /// handle 类型必须实现的接口,例如 `ControlHandle`。
84    pub required_handle_traits: Vec<String>,
85    /// Interfaces the parts type must implement, for example `ActionParts`.
86    /// parts 类型必须实现的接口,例如 `ActionParts`。
87    pub required_part_traits: Vec<String>,
88}
89
90/// Owned twin of [`ObjectContract`], the construction contract.
91/// [`ObjectContract`] 的 owned 孪生:构造合同。
92#[derive(Clone, Debug, PartialEq, Eq)]
93pub struct OwnedObjectContract {
94    /// Construction parts the preset requires.
95    /// preset 要求的构造 parts。
96    pub required_parts: Vec<String>,
97    /// Construction parts the parts type supplies.
98    /// parts 类型实际提供的构造 parts。
99    pub provided_parts: Vec<String>,
100}
101
102impl OwnedAdmission {
103    /// Check an external path without borrowing static declaration data.
104    /// 不借用静态声明数据,直接检查外部依赖路径。
105    pub fn accepts(&self, path: &str) -> bool {
106        if self
107            .denied_paths
108            .iter()
109            .any(|prefix| path_is_under(path, prefix))
110        {
111            return false;
112        }
113        self.allowed_paths.is_empty()
114            || self
115                .allowed_paths
116                .iter()
117                .any(|prefix| path_is_under(path, prefix))
118    }
119}
120
121impl OwnedRegistrationRule {
122    /// Validate all structural requirements and return every failure.
123    /// 校验全部结构要求,并一次返回所有失败项。
124    pub fn validate(&self, snapshot: &RegistrationSnapshot) -> Vec<String> {
125        validate_registration_requirements(RegistrationRequirementCheck {
126            required_preset: self.required_preset.as_deref(),
127            required_parts: &self.required_parts,
128            required_exports: &self.required_exports,
129            required_handle_traits: &self.required_handle_traits,
130            required_part_traits: &self.required_part_traits,
131            preset: &snapshot.preset,
132            provided_parts: &snapshot.contract.provided_parts,
133            exports: &snapshot.exports,
134            handle: &snapshot.handle,
135            handle_traits: &snapshot.handle_traits,
136            parts: &snapshot.parts,
137            part_traits: &snapshot.part_traits,
138        })
139    }
140}
141
142impl OwnedObjectContract {
143    /// Validate the relationship between required and supplied parts.
144    /// 校验所需 parts、实际提供 parts 以及返回值合同。
145    pub fn validate(&self, object: &str) -> Vec<String> {
146        validate_object_contract(&self.required_parts, &self.provided_parts, object)
147    }
148}
149
150/// Owned declaration location used by reloadable registration faces.
151/// 可重载注册面使用的自有声明位置。
152#[derive(Clone, Debug, PartialEq, Eq)]
153pub struct OwnedSourceLocation {
154    /// Source path recorded at the declaration site.
155    /// 声明点记录的源码路径。
156    pub file: String,
157    /// One-based line number of the declaration.
158    /// 声明所在的行号(从 1 开始)。
159    pub line: u32,
160    /// One-based column number of the declaration.
161    /// 声明所在的列号(从 1 开始)。
162    pub column: u32,
163    /// The registration-face handle or logical function associated with this declaration.
164    /// 与该注册面声明关联的 handle 或逻辑函数名。
165    pub function: String,
166}
167
168/// Owned registration metadata used by file-backed authoring and reloads.
169/// 文件创作与热刷新使用的拥有所有权注册元数据。
170///
171/// Compile-time declarations keep `RegistrationInfo` as a small static value.
172/// Runtime-authored values must not borrow from a process-global intern pool,
173/// so this type owns every reloadable field and can be dropped with the
174/// snapshot that produced it.
175/// 编译期声明继续使用小型静态 `RegistrationInfo`;运行时创作值不能借用进程级
176/// intern 池,因此这里拥有所有可重载字段,并随快照一起释放。
177#[derive(Clone, Debug, PartialEq, Eq)]
178pub struct RegistrationSnapshot {
179    /// Package namespace that owns this declaration.
180    /// 拥有本声明的包命名空间。
181    pub namespace: String,
182    /// Stable node id assigned to this declaration.
183    /// 分配给本声明的稳定节点 id。
184    pub id: NodeId,
185    /// Node id of the registry owner this declaration is mounted under.
186    /// 本声明挂载到的注册机拥有者的节点 id。
187    pub parent: NodeId,
188    /// Face kind name the declaration was authored with.
189    /// 声明书写时使用的注册面种类名。
190    pub kind: String,
191    /// Preset name selected for construction.
192    /// 构造时所选的 preset 名称。
193    pub preset: String,
194    /// Parts type name supplying the construction shape.
195    /// 提供构造形状的 parts 类型名。
196    pub parts: String,
197    /// Params type name carrying this face's parameters.
198    /// 承载该注册面参数的 params 类型名。
199    pub params: String,
200    /// Handle type name owning this face's runtime state.
201    /// 拥有该注册面运行期状态的 handle 类型名。
202    pub handle: String,
203    /// Optional author-owned identity that survives source moves.
204    /// 可选的作者逻辑身份,可跨源码文件移动保持不变。
205    pub stable_name: Option<String>,
206    /// Bilingual display name of the face.
207    /// 注册面的双语显示名称。
208    pub name: OwnedLocalizedText,
209    /// Bilingual one-line summary of the face.
210    /// 注册面的双语单行摘要。
211    pub summary: OwnedLocalizedText,
212    /// Export names this face publishes.
213    /// 本注册面公开的导出名称。
214    pub exports: Vec<String>,
215    /// Whether this face owns a registry others may register into.
216    /// 本注册面是否拥有一个可供他人注册的注册机。
217    pub needs_registry: bool,
218    /// Registry slot name this face is registered under, defaulting to the kind.
219    /// 本注册面所注册到的注册机槽位名,默认为 kind。
220    pub registry_name: String,
221    /// Name of the external registry this face takes its dependency from.
222    /// 本注册面从哪个外部注册机取得依赖的名称。
223    pub getting_from_other_registry: Option<String>,
224    /// Source path of the declaration that supplied the registry rule.
225    /// 提供注册规范的声明所在源码路径。
226    pub registry_rule_path: String,
227    /// Rule for faces entering the registry owned by this face.
228    /// 进入本注册面所拥有的注册机时必须满足的规范。
229    pub registry_rule: OwnedRegistrationRule,
230    /// External dependency gate for this face's registry.
231    /// 本注册面所属注册机对外部依赖的门禁。
232    pub admission: OwnedAdmission,
233    /// Capabilities this face requires from its dependencies.
234    /// 本注册面要求其依赖提供的能力。
235    pub requires: Vec<OwnedRequirementSpec>,
236    /// Names of the capabilities this face provides.
237    /// 本注册面所提供能力的名称。
238    pub provides: Vec<String>,
239    /// Construction contract between preset and parts.
240    /// preset 与 parts 之间的构造合同。
241    pub contract: OwnedObjectContract,
242    /// Automatically comparable input/output contract for grafting.
243    /// 供嫁接自动比较的输入/输出合同。
244    pub flow: crate::OwnedFlowContract,
245    /// Type that supplied the compile-time flow contract, when explicit.
246    /// 显式提供编译期数据流合同的类型路径(如果有)。
247    pub flow_provider: Option<String>,
248    /// Interface names declared by the handle type.
249    /// handle 类型声明实现的接口名称。
250    pub handle_traits: Vec<String>,
251    /// Interface names declared by the parts type.
252    /// parts 类型声明实现的接口名称。
253    pub part_traits: Vec<String>,
254    /// Runtime checks the host must run on values from this face.
255    /// 宿主必须对本注册面产出的取值执行的运行期校验。
256    pub runtime_checks: Vec<RuntimeCheckSpec>,
257    /// Optional provenance for a face supplied by an external plugin crate.
258    /// 外部插件 crate 提供注册面时,可附带插件来源元数据。
259    pub plugin: Option<crate::PluginManifest>,
260    /// Declaration site captured for diagnostics.
261    /// 为诊断捕获的声明位置。
262    pub source: OwnedSourceLocation,
263}
264
265impl RegistrationSnapshot {
266    /// Return the same logical identity used by compiled declarations.
267    /// 返回与编译期声明一致的逻辑稳定身份。
268    pub fn stable_face_id(&self) -> StableFaceId {
269        StableFaceId::from_name(self.stable_name.as_deref().unwrap_or(&self.kind))
270    }
271
272    /// Return the explicit stable identity, if this snapshot declared one.
273    /// 返回快照显式声明的稳定身份。
274    pub fn explicit_stable_face_id(&self) -> Option<StableFaceId> {
275        self.stable_name.as_deref().map(StableFaceId::from_name)
276    }
277
278    /// Apply file-authored fields while retaining executable compiled metadata.
279    /// 应用文件中可编辑的字段,同时保留编译产物中的可执行元数据。
280    pub fn merge_authored(mut self, authored: Self) -> Self {
281        self.namespace = authored.namespace;
282        self.kind = authored.kind;
283        self.preset = authored.preset;
284        self.parts = authored.parts;
285        self.params = authored.params;
286        self.handle = authored.handle;
287        self.stable_name = authored.stable_name;
288        self.name = authored.name;
289        self.summary = authored.summary;
290        self.exports = authored.exports;
291        self.needs_registry = authored.needs_registry;
292        self.registry_name = authored.registry_name;
293        self.getting_from_other_registry = authored.getting_from_other_registry;
294        self.registry_rule_path = authored.registry_rule_path;
295        self.registry_rule = authored.registry_rule;
296        self.admission = authored.admission;
297        self.requires = authored.requires;
298        self.provides = authored.provides;
299        // The part lists come from the compiled PresetContract and
300        // PartsContract associated constants. A source-only reload cannot
301        // reconstruct them, so keep that executable evidence while applying
302        // the editable output labels.
303        // part 列表来自已编译 trait 的关联常量;只读源码的热刷新无法可靠重建,
304        // 因此保留这份可执行证据,只更新可编辑的输出标签。
305        if authored.flow.is_declared() {
306            self.flow = authored.flow;
307        }
308        if authored.flow_provider.is_some() {
309            self.flow_provider = authored.flow_provider;
310        }
311        self.handle_traits = authored.handle_traits;
312        self.part_traits = authored.part_traits;
313        self.source = authored.source;
314        self
315    }
316}