1use std::collections::BTreeMap;
26
27use gts::GtsId;
28
29pub use toolkit_gts_macros::{
30 local_gts_instance as gts_instance, local_gts_instance_raw as gts_instance_raw,
31 local_gts_type_schema as gts_type_schema,
32};
33
34pub use crate::declare_gts_inventory;
35
36#[macro_export]
40macro_rules! declare_gts_inventory {
41 () => {
42 #[doc(hidden)]
43 pub mod __toolkit_gts_inventory {
44 pub struct TypeSchema(pub $crate::InventoryTypeSchema);
46 pub struct Instance(pub $crate::InventoryInstance);
48 $crate::inventory::collect!(TypeSchema);
49 $crate::inventory::collect!(Instance);
50 }
51
52 #[must_use]
58 pub fn gts_declarations() -> ::std::vec::Vec<(::std::string::String, ::std::string::String)>
59 {
60 $crate::local::__assert_local_declarations(
61 ::std::module_path!(),
62 ::std::env!("CARGO_MANIFEST_DIR"),
63 );
64 $crate::local::__collect(
65 $crate::inventory::iter::<__toolkit_gts_inventory::TypeSchema>
66 .into_iter()
67 .map(|entry| &entry.0),
68 $crate::inventory::iter::<__toolkit_gts_inventory::Instance>
69 .into_iter()
70 .map(|entry| &entry.0),
71 )
72 }
73 };
74}
75
76#[doc(hidden)]
78pub struct GlobalOnlyDeclaration {
79 pub module_path: &'static str,
80 pub manifest_dir: &'static str,
81 pub gts_id: &'static str,
82}
83
84crate::inventory::collect!(GlobalOnlyDeclaration);
85
86#[doc(hidden)]
91pub fn __assert_local_declarations(crate_root: &str, manifest_dir: &str) {
92 let mut omitted: Vec<_> = crate::inventory::iter::<GlobalOnlyDeclaration>
93 .into_iter()
94 .filter(|entry| {
95 entry.manifest_dir == manifest_dir
96 && entry.module_path.split("::").next() == Some(crate_root)
97 })
98 .map(|entry| entry.gts_id)
99 .collect();
100 omitted.sort_unstable();
101 omitted.dedup();
102 assert!(
103 omitted.is_empty(),
104 "crate `{crate_root}` has global-only GTS declarations: {}; use \
105 toolkit_gts::local::gts_type_schema, toolkit_gts::local::gts_instance! or \
106 toolkit_gts::local::gts_instance_raw! for every declaration in a published crate",
107 omitted.join(", ")
108 );
109}
110
111#[doc(hidden)]
113pub fn __collect<'a>(
114 schemas: impl Iterator<Item = &'a crate::InventoryTypeSchema>,
115 instances: impl Iterator<Item = &'a crate::InventoryInstance>,
116) -> Vec<(String, String)> {
117 let mut out: Vec<(String, String)> = schemas
118 .map(|entry| (entry.type_id.to_owned(), (entry.schema_fn)()))
119 .chain(instances.map(|entry| {
120 (
121 entry.instance_id.to_owned(),
122 (entry.payload_fn)().to_string(),
123 )
124 }))
125 .collect();
126 out.sort();
127 out
128}
129
130pub struct DeclarationSource {
133 pub origin: String,
135 pub declarations: Vec<(String, String)>,
137}
138
139impl DeclarationSource {
140 #[must_use]
141 pub fn new(origin: impl Into<String>, declarations: Vec<(String, String)>) -> Self {
142 Self {
143 origin: origin.into(),
144 declarations,
145 }
146 }
147}
148
149#[derive(Debug, Default)]
156pub struct DeclarationMerge {
157 merged: BTreeMap<String, (GtsId, serde_json::Value, String)>,
158 problems: Vec<String>,
159}
160
161impl DeclarationMerge {
162 pub fn add_source(&mut self, source: DeclarationSource) -> &mut Self {
164 for (id, text) in source.declarations {
165 let parsed = match GtsId::try_new(&id) {
166 Ok(parsed) => parsed,
167 Err(e) => {
168 self.problems
169 .push(format!("{id} from {}: invalid GTS id: {e}", source.origin));
170 continue;
171 }
172 };
173 match serde_json::from_str(&text) {
174 Ok(content) => self.insert(parsed, content, &source.origin),
175 Err(e) => self
176 .problems
177 .push(format!("{id} from {}: invalid JSON: {e}", source.origin)),
178 }
179 }
180 self
181 }
182
183 pub fn add_documents(
185 &mut self,
186 origin: &str,
187 documents: impl IntoIterator<Item = (GtsId, serde_json::Value)>,
188 ) -> &mut Self {
189 for (id, content) in documents {
190 self.insert(id, content, origin);
191 }
192 self
193 }
194
195 fn insert(&mut self, id: GtsId, content: serde_json::Value, origin: &str) {
196 match self.merged.get(id.id()) {
197 None => {
198 self.merged
199 .insert(id.id().to_owned(), (id, content, origin.to_owned()));
200 }
201 Some((_, kept, _)) if same_canonical_content(kept, &content) => {}
202 Some((_, _, kept_origin)) => self.problems.push(format!(
203 "{id} is declared with different content by {kept_origin} and {origin}"
204 )),
205 }
206 }
207
208 pub fn finish(self) -> anyhow::Result<Vec<(GtsId, serde_json::Value)>> {
213 if !self.problems.is_empty() {
214 anyhow::bail!(
215 "conflicting or invalid GTS declarations:\n- {}",
216 self.problems.join("\n- ")
217 );
218 }
219 Ok(self
220 .merged
221 .into_values()
222 .map(|(id, content, _)| (id, content))
223 .collect())
224 }
225}
226
227pub fn merge_declarations(
232 sources: impl IntoIterator<Item = DeclarationSource>,
233) -> anyhow::Result<Vec<(GtsId, serde_json::Value)>> {
234 let mut merge = DeclarationMerge::default();
235 for source in sources {
236 merge.add_source(source);
237 }
238 merge.finish()
239}
240
241#[must_use]
246pub fn same_canonical_content(left: &serde_json::Value, right: &serde_json::Value) -> bool {
247 use serde_json::Value;
248 match (left, right) {
249 (Value::Number(l), Value::Number(r)) => l.to_string() == r.to_string(),
250 (Value::Array(l), Value::Array(r)) => {
251 l.len() == r.len() && l.iter().zip(r).all(|(l, r)| same_canonical_content(l, r))
252 }
253 (Value::Object(l), Value::Object(r)) => {
254 l.len() == r.len()
255 && l.iter()
256 .all(|(key, l)| r.get(key).is_some_and(|r| same_canonical_content(l, r)))
257 }
258 _ => left == right,
259 }
260}
261
262#[cfg(test)]
263#[path = "local_tests.rs"]
264mod local_tests;