1use std::sync::OnceLock;
5
6use alpha2_diagnose::run::{self, Judged, Pack};
7use alpha2_diagnose::schema::Schema;
8use alpha2_diagnose::shape::Finding;
9use alpha2_diagnose::{Code, Diagnostic, Node, Options, Path, Report, Severity, Value, read};
10
11use super::manifest::{MAX_MANIFEST_BYTES, ManifestError, PluginManifest};
12
13pub static MANIFEST_TOO_LARGE: Code = Code {
15 name: "manifest.too_large",
16 severity: Severity::Error,
17 level: 1,
18 summary: "The manifest is longer than a manifest may be; nothing else was checked.",
19};
20
21pub static MANIFEST_UNSUPPORTED_ABI: Code = Code {
23 name: "manifest.unsupported_abi",
24 severity: Severity::Error,
25 level: 1,
26 summary: "The manifest names another version of the plugin ABI than this build implements; nothing else was checked.",
27};
28
29pub static MANIFEST_REFUSED: Code = Code {
31 name: "manifest.refused",
32 severity: Severity::Error,
33 level: 1,
34 summary: "The plugin manifest parser refuses the manifest at this place.",
35};
36
37pub static MANIFEST_CODES: &[&Code] = &[
39 &MANIFEST_TOO_LARGE,
40 &MANIFEST_UNSUPPORTED_ABI,
41 &MANIFEST_REFUSED,
42];
43
44#[must_use]
46pub fn diagnose_manifest(text: &str, options: &Options) -> Report {
47 run::diagnose(&ManifestPack, text, options)
48}
49
50fn manifest_schema() -> &'static Schema {
51 static SCHEMA: OnceLock<Schema> = OnceLock::new();
52 SCHEMA.get_or_init(|| {
53 let read = read::json(
54 include_str!("plugin-manifest-shape.json"),
55 &Path::root("schema"),
56 );
57 let tree = read.tree.expect("the manifest shape is JSON");
58 Schema::compile(&tree, "plugin_manifest").expect("the manifest shape compiles")
59 })
60}
61
62struct ManifestPack;
63
64impl Pack for ManifestPack {
65 fn document(&self) -> &'static str {
66 "plugin_manifest"
67 }
68
69 fn schema(&self) -> Option<&Schema> {
70 Some(manifest_schema())
71 }
72
73 fn refuse(&self, text: &str) -> Option<Diagnostic> {
74 (text.len() > MAX_MANIFEST_BYTES).then(|| {
75 Diagnostic::new(
76 &MANIFEST_TOO_LARGE,
77 Path::root("plugin_manifest"),
78 format!(
79 "the manifest is {} bytes, longer than the {MAX_MANIFEST_BYTES} a manifest may be",
80 text.len()
81 ),
82 )
83 .data(Node::map([
84 ("found", Node::from(text.len())),
85 ("maximum", Node::from(MAX_MANIFEST_BYTES)),
86 ]))
87 })
88 }
89
90 fn refuse_tree(&self, tree: &Node, root: &Path) -> Option<Diagnostic> {
91 let entry = tree.entry("abi")?;
92 let abi = entry.value.as_str()?;
93 let (family, _) = alpha2_plugin_abi::ABI.split_once('/')?;
94 let other_version = abi.split_once('/').is_some_and(|(name, _)| name == family);
95 (other_version && abi != alpha2_plugin_abi::ABI)
96 .then(|| unsupported_abi(root.key("abi"), abi).at(entry.value.span))
97 }
98
99 fn judge(&self, judged: &Judged<'_>, out: &mut Vec<Finding>) -> bool {
100 let diagnostic = match PluginManifest::from_json(judged.written) {
101 Ok(_) => return true,
102 Err(ManifestError::UnsupportedAbi(abi)) => {
103 let path = judged.root.key("abi");
104 let span = judged.tree.at(&path).and_then(|node| node.span);
105 unsupported_abi(path, &abi).at(span)
106 }
107 Err(ManifestError::Invalid(why)) => {
108 let path = serde_place(judged, &why)
109 .unwrap_or_else(|| named_place(judged.tree, judged.root, &why));
110 let span = judged.tree.at(&path).and_then(|node| node.span);
111 Diagnostic::new(&MANIFEST_REFUSED, path, why).at(span)
112 }
113 };
114 if !judged.covered(&diagnostic.path) {
115 out.push(Finding::bare(diagnostic));
116 }
117 false
118 }
119}
120
121fn unsupported_abi(path: Path, abi: &str) -> Diagnostic {
122 Diagnostic::new(
123 &MANIFEST_UNSUPPORTED_ABI,
124 path,
125 format!(
126 "the plugin needs ABI {abi}; this build implements {}",
127 alpha2_plugin_abi::ABI
128 ),
129 )
130 .data(Node::map([
131 ("found", Node::text(abi)),
132 ("implemented", Node::text(alpha2_plugin_abi::ABI)),
133 ]))
134}
135
136fn serde_place(judged: &Judged<'_>, why: &str) -> Option<Path> {
137 let (_, place) = why.rsplit_once(" at line ")?;
138 let (line, column) = place.split_once(" column ")?;
139 let line = line.trim().parse().ok()?;
140 let column = column.trim().parse().ok()?;
141 Some(judged.placement.path_at_line_column(line, column))
142}
143
144fn named_place(tree: &Node, root: &Path, why: &str) -> Path {
145 if let Some(first) = why.split_whitespace().next()
146 && first.contains('.')
147 && let Ok(path) = root.join_text(first)
148 && tree.at(&path).is_some()
149 {
150 return path;
151 }
152 let first_quoted = why
153 .strip_prefix("unknown field `")
154 .and_then(|rest| rest.split_once('`'))
155 .map(|(name, _)| name);
156 let mut best: Option<(usize, usize, Path)> = None;
157 let mut consider = |at: usize, path: Path| {
158 let depth = path.segments().len();
159 if best
160 .as_ref()
161 .is_none_or(|(known, deep, _)| at < *known || (at == *known && depth > *deep))
162 {
163 best = Some((at, depth, path));
164 }
165 };
166 let mut stack = vec![(tree, root.clone())];
167 while let Some((node, path)) = stack.pop() {
168 match &node.value {
169 Value::Text(text) if text.len() >= 3 => {
170 if let Some(at) = token_at(why, text) {
171 consider(at, path);
172 }
173 }
174 Value::List(items) => {
175 for (index, item) in items.iter().enumerate() {
176 stack.push((item, path.index(index)));
177 }
178 }
179 Value::Map(entries) => {
180 for entry in entries {
181 let inner = path.key(entry.key.clone());
182 if first_quoted == Some(entry.key.as_str()) {
183 consider(0, inner.clone());
184 }
185 stack.push((&entry.value, inner));
186 }
187 }
188 _ => {}
189 }
190 }
191 if let Some((_, _, path)) = best {
192 return path;
193 }
194 let field = [
195 ("artifact", "artifacts"),
196 ("resource", "resources"),
197 ("slot", "resources"),
198 ("version", "version"),
199 ("descriptor", "descriptor"),
200 ]
201 .into_iter()
202 .find(|(word, _)| why.contains(word))
203 .map(|(_, field)| root.key(field));
204 field
205 .filter(|path| tree.at(path).is_some())
206 .unwrap_or_else(|| root.clone())
207}
208
209fn token_at(haystack: &str, needle: &str) -> Option<usize> {
210 let name_char = |c: char| c.is_alphanumeric() || matches!(c, '.' | '-' | '_' | '/');
211 haystack
212 .match_indices(needle)
213 .map(|(at, _)| at)
214 .find(|&at| {
215 let rest = &haystack[at + needle.len()..];
216 let ends = match rest.chars().next() {
217 None => true,
218 Some('.') => !rest[1..].starts_with(char::is_alphanumeric),
219 Some(next) => !name_char(next),
220 };
221 ends && !haystack[..at].chars().next_back().is_some_and(name_char)
222 })
223}