1use std::collections::HashSet;
5use std::fmt::Write as _;
6
7use yog_gfx::image::ImageSource;
8
9use super::{Element, err};
10use yog_data::Diagnostic;
11
12pub(crate) fn number(el: &Element, key: &str, value: &str) -> Result<f32, Diagnostic> {
14 value
15 .trim()
16 .parse::<f32>()
17 .or_else(|_| err(el, format_args!("{key}=\"{value}\": expected a number")))
18}
19
20pub(crate) fn boolean(el: &Element, key: &str, value: &str) -> Result<bool, Diagnostic> {
22 match value.trim() {
23 yog_ids::yui_value::TRUE => Ok(true),
24 yog_ids::yui_value::FALSE => Ok(false),
25 _ => err(
26 el,
27 format_args!("{key}=\"{value}\": expected true or false"),
28 ),
29 }
30}
31
32pub fn color(value: &str) -> Option<u32> {
35 yog_ui::attr::written_color(value).map(|c| c.0)
36}
37
38pub const HEX_MARK: &str = yog_ui::attr::HEX_MARKS[0];
40
41pub(crate) fn color_attr(el: &Element, key: &str, value: &str) -> Result<u32, Diagnostic> {
44 if let Some(reference) = value.trim().strip_prefix(yog_ids::reference::RES) {
45 return resource_color(reference).ok_or_else(|| {
46 Diagnostic::from(format!(
47 "<{}> {key}=\"{value}\": no color `{reference}` in resources/*.yres",
48 el.name
49 ))
50 .at_line(el.line)
51 });
52 }
53 color(value).ok_or_else(|| {
54 Diagnostic::from(format!(
55 "<{}> {key}=\"{value}\": expected #RRGGBB, #AARRGGBB or @<Set>.<name>",
56 el.name
57 ))
58 .at_line(el.line)
59 })
60}
61
62pub(super) fn is_resource_text(reference: &str) -> bool {
64 RESOURCE_REFS.with(|r| r.borrow().texts.contains_key(reference.trim()))
65}
66
67pub(super) fn resource_color(reference: &str) -> Option<u32> {
69 RESOURCE_REFS.with(|r| r.borrow().colors.get(reference.trim()).copied())
70}
71
72pub(super) fn pick<'v>(
74 el: &Element,
75 key: &str,
76 value: &str,
77 options: &[&'v str],
78) -> Result<&'v str, Diagnostic> {
79 options
80 .iter()
81 .find(|o| **o == value.trim())
82 .copied()
83 .ok_or_else(|| {
84 Diagnostic::from(format!(
85 "<{}> {key}=\"{value}\": expected one of {}",
86 el.name,
87 options.join(", ")
88 ))
89 .at_line(el.line)
90 })
91}
92
93pub fn text_expr(value: &str) -> Result<String, Diagnostic> {
101 if value.trim() == "@" || !value.starts_with('@') {
102 return Ok(format!("{value:?}"));
103 }
104 let tr = |key: &str| format!("::yog_api::tr({key:?})");
105 match yog_data::typed::classify(value.trim()) {
106 Ok(yog_data::typed::Spelled::Plain(s)) => Ok(format!("{s:?}")),
107 Ok(yog_data::typed::Spelled::Ref(r)) => match yog_data::Text::of_ref(r) {
108 Some(yog_data::Text::Lang(key)) => Ok(tr(&key)),
109 Some(yog_data::Text::Res(r)) => {
110 RESOURCE_REFS.with(|refs| Ok(refs.borrow().text(&r).map(|(k, _)| tr(k))?))
111 }
112 Some(yog_data::Text::NameOf(r)) if matches!(
113 r.kind.as_str(),
114 yog_ids::kind::ITEM | yog_ids::kind::BLOCK | yog_ids::kind::ENTITY
115 ) =>
116 {
117 let id = r.id.split(STATE_OPEN).next().unwrap_or(&r.id);
119 Ok(tr(&yog_ids::lang_key(&r.kind, id)))
120 }
121 _ => Err(format!("`{}` isn't a text", value.trim()).into()),
122 },
123 Ok(other) => Err(format!("{} isn't a text", other.kind()).into()),
124 Err(_) if !value.contains(':') => Err(format!(
125 "write a translation key as `@lang:{}`, a .yres text as `@res:Set.name`, a literal `@` as `@@`",
126 value[1..].trim()
127 ).into()),
128 Err(e) => Err(e.to_string().into()),
129 }
130}
131
132const STATE_OPEN: char = '[';
134
135pub(crate) fn text_attr(el: &Element, key: &str, value: &str) -> Result<String, Diagnostic> {
137 text_expr(value).map_err(|e| {
138 Diagnostic::from(format!("<{}> {key}=\"{value}\": {e}", el.name)).at_line(el.line)
139 })
140}
141
142thread_local! {
143 static RESOURCE_REFS: std::cell::RefCell<crate::yres::Refs> = Default::default();
145}
146
147pub fn set_resource_refs(refs: &crate::yres::Refs) {
150 RESOURCE_REFS.with(|r| *r.borrow_mut() = refs.clone());
151}
152
153pub fn const_name(value: &str) -> String {
155 let mut out = String::new();
156 let mut prev_lower = false;
157 for c in value.chars() {
158 if c.is_ascii_alphanumeric() {
159 if c.is_ascii_uppercase() && prev_lower {
160 out.push('_');
161 }
162 prev_lower = c.is_ascii_lowercase() || c.is_ascii_digit();
163 out.push(c.to_ascii_uppercase());
164 } else {
165 if !out.ends_with('_') {
166 out.push('_');
167 }
168 prev_lower = false;
169 }
170 }
171 let out = out.trim_matches('_').to_string();
172 if out.is_empty() || out.starts_with(|c: char| c.is_ascii_digit()) {
173 format!("_{out}")
174 } else {
175 out
176 }
177}
178
179#[derive(Debug, Default)]
181pub(crate) struct Names {
182 list: Vec<String>,
183 seen: HashSet<String>,
184}
185
186impl Names {
187 pub(crate) fn push(&mut self, name: &str) {
188 if !self.seen.contains(name) {
189 self.seen.insert(name.to_string());
190 self.list.push(name.to_string());
191 }
192 }
193
194 pub(crate) fn as_slice(&self) -> &[String] {
195 &self.list
196 }
197
198 pub(crate) fn into_vec(self) -> Vec<String> {
199 self.list
200 }
201}
202
203pub(crate) fn str_consts(values: &[String]) -> String {
206 let mut out = String::new();
207 let mut used: HashSet<String> = HashSet::new();
208 for v in values {
209 let mut name = const_name(v);
210 while used.contains(&name) {
211 name.push('_');
212 }
213 let _ = writeln!(out, " pub const {name}: &str = {v:?};");
214 used.insert(name);
215 }
216 out
217}
218
219pub(crate) fn is_image_value(v: &str) -> bool {
222 let v = v.trim();
223 match v.strip_prefix(yog_ids::reference::RES) {
224 Some(name) => RESOURCE_REFS.with(|r| r.borrow().images.contains_key(name)),
225 None => !v.starts_with('#') && v.contains(':'),
226 }
227}
228
229pub(crate) fn image_source(
232 el: &Element,
233 attr: &str,
234 source: &str,
235 mod_id: Option<&str>,
236) -> Result<String, Diagnostic> {
237 let line = el.line;
238 let kind = el.name.as_str();
239 let mod_id = mod_id.map(str::to_owned);
240 let resolved;
241 let source = match source.strip_prefix(yog_ids::reference::RES) {
242 Some(name) => {
243 resolved = RESOURCE_REFS
244 .with(|r| r.borrow().images.get(name).cloned())
245 .ok_or_else(|| {
246 Diagnostic::from(format!(
247 "<{kind}> {attr}=\"{source}\": no image `{name}` in resources/*.yres"
248 ))
249 .at_line(line)
250 })?;
251 resolved.as_str()
252 }
253 None => source,
254 };
255 let parsed = ImageSource::parse(source).ok_or_else(|| {
256 Diagnostic::from(format!(
257 "<{kind}> {attr}=\"{source}\": expected item:<id>, block:<id>, \
258 sprite:<name>, mod:<path> or <namespace>:<path>"
259 ))
260 .at_line(line)
261 })?;
262 let source = match parsed {
263 ImageSource::ModPath(path) => match &mod_id {
264 Some(id) => yog_gfx::image::texture_id(id, &path),
265 None => {
266 return Err(Diagnostic::from(format!(
267 "<{kind}> {attr}=\"{source}\": mod: needs the mod id (no yog.toml found)"
268 ))
269 .at_line(line));
270 }
271 },
272 ImageSource::Sprite(name)
273 if !name.contains(':') && yog_gfx::image::sprite(&name).is_none() =>
274 {
275 let names: Vec<&str> = yog_gfx::image::SPRITES
276 .iter()
277 .map(|s| s.name.as_str())
278 .collect();
279 return Err(Diagnostic::from(format!(
280 "<{kind}> {attr}=\"{source}\": unknown sprite (known: {})",
281 names.join(", ")
282 ))
283 .at_line(line));
284 }
285 ImageSource::Texture(_) => {
286 if let Some(alias) = yog_gfx::image::suggest_alias(source) {
287 return Err(Diagnostic::from(format!(
288 "<{kind}> {attr}=\"{source}\" is a raw resource path, which \
289 changes between Minecraft versions — write {attr}=\"{alias}\""
290 ))
291 .at_line(line));
292 }
293 source.to_string()
294 }
295 _ => source.to_string(),
296 };
297 Ok(source)
298}
299
300pub(super) fn font_attr<'a>(el: &Element, v: &'a str) -> Result<&'a str, Diagnostic> {
303 let font = v.trim();
304 match yog_ids::split(font) {
305 (yog_ids::ns::MINECRAFT, name) if !font.is_empty() => err(
306 el,
307 format!(
308 "font=\"{font}\": the game's fonts are named by Yog's alias, {}",
309 yog_ids::font_alias(name)
310 ),
311 ),
312 _ => Ok(font),
313 }
314}