Shader packs, clean room 2: macros and #if conditions

The integer arithmetic of #if/#elif that a pack's .properties files and,
later, its GLSL preprocessor share: defined X and defined(X), decimal,
hexadecimal and octal literals, the C operators with C precedence, macros
expanded to their values (a macro is not expanded inside its own
expansion), and an identifier that is not a macro read as 0. A bad
condition says why. The standard macros that need no renderer:
MC_VERSION, from the pinned version by the documented rule (26.3 is
260300), and the system's MC_OS_*.

Nothing uses it yet: players see no change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-24 20:42:05 +02:00
parent 07e46daa59
commit eb0a6f74e6
5 changed files with 403 additions and 0 deletions
Generated
+1
View File
@@ -1434,6 +1434,7 @@ dependencies = [
name = "horizon-shaders"
version = "0.1.0"
dependencies = [
"horizon-core",
"zip",
]
+1
View File
@@ -7,6 +7,7 @@ rust-version = "1.85"
description = "Shader packs (the shaders/ folder format): reading packs, their .properties and .lang files, and later their GLSL"
[dependencies]
horizon-core = { path = "../horizon-core" }
zip = { version = "2", default-features = false, features = ["deflate"] }
[lints]
+265
View File
@@ -0,0 +1,265 @@
//! The integer arithmetic of `#if` and `#elif` (spec 1.5, GLSL 4.60 §3.3): `defined`, integer
//! literals, macros expanded to their values, and the C operators with C precedence.
//! An identifier that is not a macro counts as 0, as in C: GLSL would reject the line, and a
//! pack would then lose a whole section of its settings over one unknown name.
use crate::Macros;
use crate::macros::{is_ident, is_ident_start};
/// The value of a condition; `Err` says what is wrong with it.
pub fn eval_condition(expr: &str, macros: &Macros) -> Result<i64, String> {
let tokens = tokens(&resolve_defined(expr, macros)?, macros)?;
let mut parser = Parser {
tokens: &tokens,
at: 0,
};
let value = parser.binary(0)?;
match parser.tokens.get(parser.at) {
None => Ok(value),
Some(t) => Err(format!("unexpected `{}`", t.text())),
}
}
/// `defined X` and `defined(X)` become `1` or `0` before anything is expanded.
fn resolve_defined(expr: &str, macros: &Macros) -> Result<String, String> {
let mut out = String::with_capacity(expr.len());
let mut rest = expr;
while let Some(at) = find_word(rest, "defined") {
out.push_str(&rest[..at]);
let after = rest[at + "defined".len()..].trim_start();
let (inner, tail) = match after.strip_prefix('(') {
Some(open) => {
let close = open.find(')').ok_or("`defined(` without `)`")?;
(open[..close].trim(), &open[close + 1..])
}
None => {
let len = after.find(|c: char| !is_ident(c)).unwrap_or(after.len());
(&after[..len], &after[len..])
}
};
if inner.is_empty() || !inner.starts_with(is_ident_start) || !inner.chars().all(is_ident) {
return Err("`defined` needs a macro name".into());
}
out.push_str(if macros.is_defined(inner) {
" 1 "
} else {
" 0 "
});
rest = tail;
}
out.push_str(rest);
Ok(out)
}
/// Where `word` starts in `text` as a whole identifier.
fn find_word(text: &str, word: &str) -> Option<usize> {
let mut from = 0;
while let Some(i) = text[from..].find(word).map(|i| i + from) {
let before = text[..i].chars().next_back().is_some_and(is_ident);
let after = text[i + word.len()..].chars().next().is_some_and(is_ident);
if !before && !after {
return Some(i);
}
from = i + word.len();
}
None
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Token {
Num(i64),
Op(&'static str),
}
impl Token {
fn text(&self) -> String {
match self {
Token::Num(n) => n.to_string(),
Token::Op(op) => (*op).to_owned(),
}
}
}
const OPS: [&str; 22] = [
"<<", ">>", "<=", ">=", "==", "!=", "&&", "||", "(", ")", "!", "~", "+", "-", "*", "/", "%",
"<", ">", "&", "^", "|",
];
fn tokens(expr: &str, macros: &Macros) -> Result<Vec<Token>, String> {
let expanded = macros.expand(expr);
let mut out = Vec::new();
let mut rest = expanded.trim_start();
while let Some(c) = rest.chars().next() {
if c.is_ascii_digit() {
let len = rest
.find(|c: char| !c.is_ascii_alphanumeric())
.unwrap_or(rest.len());
if rest[len..].starts_with('.') {
return Err(format!("`{}`: `#if` takes integers only", &rest[..len + 1]));
}
out.push(Token::Num(int_literal(&rest[..len])?));
rest = &rest[len..];
} else if is_ident_start(c) {
// Not a macro: 0, as the C preprocessor counts it.
let len = rest.find(|c: char| !is_ident(c)).unwrap_or(rest.len());
out.push(Token::Num(0));
rest = &rest[len..];
} else {
let op = OPS
.iter()
.find(|op| rest.starts_with(**op))
.ok_or_else(|| format!("unexpected `{c}`"))?;
out.push(Token::Op(op));
rest = &rest[op.len()..];
}
rest = rest.trim_start();
}
Ok(out)
}
/// Decimal, `0x` hexadecimal or leading-zero octal, with an optional `u` suffix.
fn int_literal(text: &str) -> Result<i64, String> {
let digits = text.strip_suffix(['u', 'U']).unwrap_or(text);
let parsed = if let Some(hex) = digits.strip_prefix("0x").or(digits.strip_prefix("0X")) {
i64::from_str_radix(hex, 16)
} else if digits.len() > 1 && digits.starts_with('0') {
i64::from_str_radix(&digits[1..], 8)
} else {
digits.parse()
};
parsed.map_err(|_| format!("`{text}` is not an integer"))
}
struct Parser<'a> {
tokens: &'a [Token],
at: usize,
}
/// Binary operators from the loosest to the tightest (GLSL §5.1 / §3.3).
const LEVELS: [&[&str]; 10] = [
&["||"],
&["&&"],
&["|"],
&["^"],
&["&"],
&["==", "!="],
&["<", ">", "<=", ">="],
&["<<", ">>"],
&["+", "-"],
&["*", "/", "%"],
];
impl Parser<'_> {
fn next(&mut self) -> Option<Token> {
let t = self.tokens.get(self.at).copied();
self.at += 1;
t
}
fn binary(&mut self, level: usize) -> Result<i64, String> {
if level == LEVELS.len() {
return self.unary();
}
let mut left = self.binary(level + 1)?;
while let Some(&Token::Op(op)) = self.tokens.get(self.at) {
if !LEVELS[level].contains(&op) {
break;
}
self.at += 1;
let right = self.binary(level + 1)?;
left = apply(op, left, right)?;
}
Ok(left)
}
fn unary(&mut self) -> Result<i64, String> {
match self.next() {
Some(Token::Num(n)) => Ok(n),
Some(Token::Op("(")) => {
let value = self.binary(0)?;
match self.next() {
Some(Token::Op(")")) => Ok(value),
_ => Err("missing `)`".into()),
}
}
Some(Token::Op("-")) => Ok(self.unary()?.wrapping_neg()),
Some(Token::Op("+")) => self.unary(),
Some(Token::Op("!")) => Ok((self.unary()? == 0) as i64),
Some(Token::Op("~")) => Ok(!self.unary()?),
Some(t) => Err(format!("unexpected `{}`", t.text())),
None => Err("the condition ends too early".into()),
}
}
}
fn apply(op: &str, a: i64, b: i64) -> Result<i64, String> {
Ok(match op {
"||" => (a != 0 || b != 0) as i64,
"&&" => (a != 0 && b != 0) as i64,
"|" => a | b,
"^" => a ^ b,
"&" => a & b,
"==" => (a == b) as i64,
"!=" => (a != b) as i64,
"<" => (a < b) as i64,
">" => (a > b) as i64,
"<=" => (a <= b) as i64,
">=" => (a >= b) as i64,
"<<" => a.wrapping_shl(b as u32),
">>" => a.wrapping_shr(b as u32),
"+" => a.wrapping_add(b),
"-" => a.wrapping_sub(b),
"*" => a.wrapping_mul(b),
"/" | "%" if b == 0 => return Err("division by zero".into()),
"/" => a.wrapping_div(b),
_ => a.wrapping_rem(b),
})
}
#[cfg(test)]
mod tests {
use super::*;
fn eval(expr: &str) -> Result<i64, String> {
let mut m = Macros::standard();
m.define("SHADOW_RES", "2048");
m.define("WAVES", "");
m.define("QUALITY", "SHADOW_RES / 1024");
eval_condition(expr, &m)
}
#[test]
fn precedence_and_operators_follow_c() {
assert_eq!(eval("1 + 2 * 3"), Ok(7));
assert_eq!(eval("(1 + 2) * 3"), Ok(9));
assert_eq!(eval("1 << 2 + 1"), Ok(8));
assert_eq!(eval("6 & 3 == 3"), Ok(0));
assert_eq!(eval("1 || 0 && 0"), Ok(1));
assert_eq!(eval("-7 / 2"), Ok(-3));
assert_eq!(eval("-7 % 2"), Ok(-1));
assert_eq!(eval("!0 + ~0"), Ok(0));
assert_eq!(eval("0x10 + 010 + 3u"), Ok(27));
}
#[test]
fn macros_and_defined() {
assert_eq!(eval("MC_VERSION >= 11300"), Ok(1));
assert_eq!(eval("MC_VERSION <= 12111"), Ok(0));
assert_eq!(eval("QUALITY == 2"), Ok(1));
assert_eq!(eval("defined WAVES && defined(SHADOW_RES)"), Ok(1));
assert_eq!(eval("!defined NOPE"), Ok(1));
assert_eq!(eval("NOPE == 0"), Ok(1));
assert_eq!(eval("undefinedFeature"), Ok(0));
}
#[test]
fn bad_conditions_say_why() {
assert!(eval("1 / 0").is_err());
assert!(eval("SHADOW_RES == 0.5").is_err());
assert!(eval("(1 + 2").is_err());
assert!(eval("1 2").is_err());
assert!(eval("").is_err());
assert!(eval("defined").is_err());
assert!(eval("1 @ 2").is_err());
}
}
+5
View File
@@ -5,11 +5,16 @@
//! - [`Pack`]: a pack as a folder or a zip, with paths relative to its `shaders` folder (spec 1.1).
//! - [`discover`]: the packs in a `shaderpacks` folder.
//! - [`Lang`]: the pack's translated names (8.4).
//! - [`Macros`] and [`eval_condition`]: the macros packs test, and the `#if` arithmetic (1.5).
mod condition;
mod discover;
mod lang;
mod macros;
mod pack;
pub use condition::eval_condition;
pub use discover::{Found, discover};
pub use lang::Lang;
pub use macros::{MC_VERSION, Macros};
pub use pack::{Pack, PackError};
+131
View File
@@ -0,0 +1,131 @@
//! Object-like macros: the ones packs test in `#if` lines and use inside property values
//! (spec 1.5, 1.5.1). The GLSL preprocessor's function-like macros are not needed here.
use std::collections::BTreeMap;
/// `MC_VERSION` of the version Horizon plays: 26.3 → 260300.
pub const MC_VERSION: u32 = mc_version(horizon_core::version::VERSION_ID);
/// The documented rule, `major * 10000 + minor * 100 + patch` (spec 1.5.1, OQ-1): `1.21` → 12100,
/// `1.7.10` → 10710. Parts that are not digits count as 0.
pub const fn mc_version(id: &str) -> u32 {
let bytes = id.as_bytes();
let (mut parts, mut part, mut i) = ([0u32; 3], 0, 0);
while i < bytes.len() && part < 3 {
match bytes[i] {
b'.' => part += 1,
b @ b'0'..=b'9' => parts[part] = parts[part] * 10 + (b - b'0') as u32,
_ => break,
}
i += 1;
}
parts[0] * 10000 + parts[1] * 100 + parts[2]
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Macros(BTreeMap<String, String>);
impl Macros {
/// The standard macros that need no renderer: `MC_VERSION` and this system's `MC_OS_*`.
/// The graphics ones arrive with the renderer.
pub fn standard() -> Self {
let mut m = Self::default();
m.define("MC_VERSION", MC_VERSION.to_string());
let os = match std::env::consts::OS {
"windows" => "MC_OS_WINDOWS",
"macos" => "MC_OS_MAC",
"linux" => "MC_OS_LINUX",
_ => "MC_OS_OTHER",
};
m.define(os, "");
m
}
pub fn define(&mut self, name: impl Into<String>, value: impl Into<String>) {
self.0.insert(name.into(), value.into());
}
pub fn undef(&mut self, name: &str) {
self.0.remove(name);
}
pub fn is_defined(&self, name: &str) -> bool {
self.0.contains_key(name)
}
pub fn get(&self, name: &str) -> Option<&str> {
self.0.get(name).map(String::as_str)
}
/// `text` with every identifier that names a macro replaced by its value, repeatedly; a macro
/// is not expanded again inside its own expansion, so `A` defined as `A + 1` stops.
pub fn expand(&self, text: &str) -> String {
self.expand_hiding(text, &mut Vec::new())
}
fn expand_hiding<'a>(&'a self, text: &str, hidden: &mut Vec<&'a str>) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(start) = rest.find(is_ident_start) {
out.push_str(&rest[..start]);
// A digit run glued to letters (`1e5`, `0x1F`) is a number, not a name.
let glued = out
.chars()
.next_back()
.is_some_and(|c| c.is_ascii_alphanumeric() || c == '.');
let len = rest[start..]
.find(|c: char| !is_ident(c))
.unwrap_or(rest.len() - start);
let word = &rest[start..start + len];
match self.0.get_key_value(word) {
Some((name, value)) if !glued && !hidden.contains(&name.as_str()) => {
hidden.push(name);
out.push_str(&self.expand_hiding(value, hidden));
hidden.pop();
}
_ => out.push_str(word),
}
rest = &rest[start + len..];
}
out.push_str(rest);
out
}
}
pub(crate) fn is_ident_start(c: char) -> bool {
c.is_ascii_alphabetic() || c == '_'
}
pub(crate) fn is_ident(c: char) -> bool {
c.is_ascii_alphanumeric() || c == '_'
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn versions_follow_the_documented_rule() {
assert_eq!(mc_version("1.21"), 12100);
assert_eq!(mc_version("1.21.0"), 12100);
assert_eq!(mc_version("1.7.10"), 10710);
assert_eq!(mc_version("26.3"), 260300);
assert_eq!(MC_VERSION, 260300);
assert_eq!(Macros::standard().get("MC_VERSION"), Some("260300"));
}
#[test]
fn expansion_replaces_whole_words_and_stops_on_recursion() {
let mut m = Macros::default();
m.define("RES", "SIZE");
m.define("SIZE", "512");
m.define("LOOP", "LOOP + 1");
assert_eq!(m.expand("RES RES 0.5"), "512 512 0.5");
assert_eq!(
m.expand("RESOLUTION colortex4 LOOP"),
"RESOLUTION colortex4 LOOP + 1"
);
m.define("e5", "x");
assert_eq!(m.expand("1e5"), "1e5");
}
}