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('@') {
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::Value::Str(s)) => Ok(format!("{s:?}")),
107 Ok(yog_data::Value::Lang(key)) => Ok(tr(&key)),
108 Ok(yog_data::Value::Res(r)) => {
109 RESOURCE_REFS.with(|refs| Ok(refs.borrow().text(&r).map(|(k, _)| tr(k))?))
110 }
111 Ok(yog_data::Value::Ref(r))
112 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 Ok(other) => Err(format!("{} isn't a text", other.kind_name()).into()),
122 Err(_) if !value.contains(':') => Err(format!(
123 "write a translation key as `@lang:{}`, a .yres text as `@Set.name`, a literal `@` as `@@`",
124 value[1..].trim()
125 ).into()),
126 Err(e) => Err(e.into()),
127 }
128}
129
130const STATE_OPEN: char = '[';
132
133pub(crate) fn text_attr(el: &Element, key: &str, value: &str) -> Result<String, Diagnostic> {
135 text_expr(value).map_err(|e| {
136 Diagnostic::from(format!("<{}> {key}=\"{value}\": {e}", el.name)).at_line(el.line)
137 })
138}
139
140thread_local! {
141 static RESOURCE_REFS: std::cell::RefCell<crate::yres::Refs> = Default::default();
143}
144
145pub fn set_resource_refs(refs: &crate::yres::Refs) {
148 RESOURCE_REFS.with(|r| *r.borrow_mut() = refs.clone());
149}
150
151pub fn const_name(value: &str) -> String {
153 let mut out = String::new();
154 let mut prev_lower = false;
155 for c in value.chars() {
156 if c.is_ascii_alphanumeric() {
157 if c.is_ascii_uppercase() && prev_lower {
158 out.push('_');
159 }
160 prev_lower = c.is_ascii_lowercase() || c.is_ascii_digit();
161 out.push(c.to_ascii_uppercase());
162 } else {
163 if !out.ends_with('_') {
164 out.push('_');
165 }
166 prev_lower = false;
167 }
168 }
169 let out = out.trim_matches('_').to_string();
170 if out.is_empty() || out.starts_with(|c: char| c.is_ascii_digit()) {
171 format!("_{out}")
172 } else {
173 out
174 }
175}
176
177#[derive(Debug, Default)]
179pub(crate) struct Names {
180 list: Vec<String>,
181 seen: HashSet<String>,
182}
183
184impl Names {
185 pub(crate) fn push(&mut self, name: &str) {
186 if !self.seen.contains(name) {
187 self.seen.insert(name.to_string());
188 self.list.push(name.to_string());
189 }
190 }
191
192 pub(crate) fn as_slice(&self) -> &[String] {
193 &self.list
194 }
195
196 pub(crate) fn into_vec(self) -> Vec<String> {
197 self.list
198 }
199}
200
201pub(crate) fn str_consts(values: &[String]) -> String {
204 let mut out = String::new();
205 let mut used: HashSet<String> = HashSet::new();
206 for v in values {
207 let mut name = const_name(v);
208 while used.contains(&name) {
209 name.push('_');
210 }
211 let _ = writeln!(out, " pub const {name}: &str = {v:?};");
212 used.insert(name);
213 }
214 out
215}
216
217pub(crate) fn is_image_value(v: &str) -> bool {
220 let v = v.trim();
221 match v.strip_prefix('@') {
222 Some(name) => RESOURCE_REFS.with(|r| r.borrow().images.contains_key(name)),
223 None => !v.starts_with('#') && v.contains(':'),
224 }
225}
226
227pub(crate) fn image_source(
230 el: &Element,
231 attr: &str,
232 source: &str,
233 mod_id: Option<&str>,
234) -> Result<String, Diagnostic> {
235 let line = el.line;
236 let kind = el.name.as_str();
237 let mod_id = mod_id.map(str::to_owned);
238 let resolved;
239 let source = match source.strip_prefix('@') {
240 Some(name) => {
241 resolved = RESOURCE_REFS
242 .with(|r| r.borrow().images.get(name).cloned())
243 .ok_or_else(|| {
244 Diagnostic::from(format!(
245 "<{kind}> {attr}=\"{source}\": no image `{name}` in resources/*.yres"
246 ))
247 .at_line(line)
248 })?;
249 resolved.as_str()
250 }
251 None => source,
252 };
253 let parsed = ImageSource::parse(source).ok_or_else(|| {
254 Diagnostic::from(format!(
255 "<{kind}> {attr}=\"{source}\": expected item:<id>, block:<id>, \
256 sprite:<name>, mod:<path> or <namespace>:<path>"
257 ))
258 .at_line(line)
259 })?;
260 let source = match parsed {
261 ImageSource::ModPath(path) => match &mod_id {
262 Some(id) => yog_gfx::image::texture_id(id, &path),
263 None => {
264 return Err(Diagnostic::from(format!(
265 "<{kind}> {attr}=\"{source}\": mod: needs the mod id (no yog.toml found)"
266 ))
267 .at_line(line));
268 }
269 },
270 ImageSource::Sprite(name)
271 if !name.contains(':') && yog_gfx::image::sprite(&name).is_none() =>
272 {
273 let names: Vec<&str> = yog_gfx::image::SPRITES
274 .iter()
275 .map(|s| s.name.as_str())
276 .collect();
277 return Err(Diagnostic::from(format!(
278 "<{kind}> {attr}=\"{source}\": unknown sprite (known: {})",
279 names.join(", ")
280 ))
281 .at_line(line));
282 }
283 ImageSource::Texture(_) => {
284 if let Some(alias) = yog_gfx::image::suggest_alias(source) {
285 return Err(Diagnostic::from(format!(
286 "<{kind}> {attr}=\"{source}\" is a raw resource path, which \
287 changes between Minecraft versions — write {attr}=\"{alias}\""
288 ))
289 .at_line(line));
290 }
291 source.to_string()
292 }
293 _ => source.to_string(),
294 };
295 Ok(source)
296}
297
298pub(super) fn font_attr<'a>(el: &Element, v: &'a str) -> Result<&'a str, Diagnostic> {
301 let font = v.trim();
302 match yog_ids::split(font) {
303 (yog_ids::ns::MINECRAFT, name) if !font.is_empty() => err(
304 el,
305 format!(
306 "font=\"{font}\": the game's fonts are named by Yog's alias, {}",
307 yog_ids::font_alias(name)
308 ),
309 ),
310 _ => Ok(font),
311 }
312}