Skip to content

Truly independent web browser

AK: Add a Rust math module backed by LLVM libc

Shannon Boothc736841465b8
diff --git a/AK/Rust/Cargo.toml b/AK/Rust/Cargo.toml
index bdd2b9b909a..af2e67019ad 100644
--- a/AK/Rust/Cargo.toml
+++ b/AK/Rust/Cargo.toml
@@ -6,5 +6,8 @@ edition = "2024"
[lib]
crate-type = ["rlib"]
+[build-dependencies]
+cc = "1"
+
[lints]
workspace = true
diff --git a/AK/Rust/build.rs b/AK/Rust/build.rs
new file mode 100644
index 00000000000..617e7f84425
--- /dev/null
+++ b/AK/Rust/build.rs
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Compiles AK/MathFunctions.cpp so that unit tests link without AK. A CMake build links AK and skips this, as does a
+//! build without the LLVM libc headers, which only cargo check and clippy can use.
+
+use std::env;
+use std::fs;
+use std::path::{Path, PathBuf};
+
+fn main() {
+ println!("cargo:rerun-if-changed=build.rs");
+ println!("cargo:rerun-if-env-changed=LADYBIRD_LINKS_AK");
+ println!("cargo:rerun-if-env-changed=LLVM_LIBC_INCLUDE_DIR");
+ if env::var_os("LADYBIRD_LINKS_AK").is_some() {
+ return;
+ }
+
+ let manifest_directory = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"));
+ let source_root = manifest_directory.join("../..");
+ let source = source_root.join("AK/MathFunctions.cpp");
+ let Some(llvm_libc) = llvm_libc_include_directory(&source_root) else {
+ println!(
+ "cargo:warning=LLVM libc is installed by vcpkg: configure a CMake build, or set LLVM_LIBC_INCLUDE_DIR"
+ );
+ return;
+ };
+
+ println!("cargo:rerun-if-changed={}", source.display());
+ println!(
+ "cargo:rerun-if-changed={}",
+ source_root.join("AK/MathFunctions.h").display()
+ );
+ println!("cargo:rerun-if-changed={}", llvm_libc.display());
+ println!("cargo:rerun-if-env-changed=MACOSX_DEPLOYMENT_TARGET");
+
+ let mut build = cc::Build::new();
+ build
+ .cpp(true)
+ .std("c++20")
+ .file(&source)
+ .include(&source_root)
+ .include(&llvm_libc)
+ .warnings(false)
+ .flag_if_supported("-fvisibility=hidden")
+ .flag_if_supported("-fno-exceptions")
+ .flag_if_supported("-fno-rtti");
+ if env::var("CARGO_CFG_TARGET_OS").is_ok_and(|os| os == "macos")
+ && let Some(deployment_target) = rust_macos_deployment_target()
+ {
+ build.flag(format!("-mmacosx-version-min={deployment_target}"));
+ }
+ build.compile("ladybird_math");
+}
+
+/// The headers of LLVM libc that vcpkg installs. A CMake build passes their directory, and a build on its own takes them
+/// from the vcpkg tree of a build under Build/.
+fn llvm_libc_include_directory(source_root: &Path) -> Option<PathBuf> {
+ if let Some(directory) = env::var_os("LLVM_LIBC_INCLUDE_DIR") {
+ return Some(PathBuf::from(directory));
+ }
+ let builds = fs::read_dir(source_root.join("Build")).into_iter().flatten().flatten();
+ builds
+ .flat_map(|build| {
+ fs::read_dir(build.path().join("vcpkg_installed"))
+ .into_iter()
+ .flatten()
+ .flatten()
+ })
+ .map(|triplet| triplet.path().join("include/llvm-libc"))
+ .find(|directory| directory.join("shared/math.h").is_file())
+}
+
+/// The minimum macOS version rustc builds the crate's own code for, which the compiled C++ has to match.
+fn rust_macos_deployment_target() -> Option<String> {
+ if let Ok(target) = env::var("MACOSX_DEPLOYMENT_TARGET") {
+ return Some(target);
+ }
+ let rustc = env::var("RUSTC").unwrap_or_else(|_| "rustc".to_string());
+ let target = env::var("TARGET").ok()?;
+ let output = std::process::Command::new(rustc)
+ .args(["--print", "deployment-target", "--target", &target])
+ .output()
+ .ok()?;
+ String::from_utf8(output.stdout)
+ .ok()?
+ .trim()
+ .strip_prefix("MACOSX_DEPLOYMENT_TARGET=")
+ .map(str::to_string)
+}
diff --git a/AK/Rust/src/lib.rs b/AK/Rust/src/lib.rs
index 0850a280c9d..ab75e47c9d7 100644
--- a/AK/Rust/src/lib.rs
+++ b/AK/Rust/src/lib.rs
@@ -6,6 +6,7 @@
//! Rust views of shared AK data structures.
+pub mod math;
pub mod perf_map;
mod scope_guard;
mod slice;
diff --git a/AK/Rust/src/math.rs b/AK/Rust/src/math.rs
new file mode 100644
index 00000000000..2e556f59cbd
--- /dev/null
+++ b/AK/Rust/src/math.rs
@@ -0,0 +1,205 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The math functions of AK/Math.h, which unlike the f32 and f64 methods give the same results on every platform.
+
+mod fdlibm;
+
+pub use fdlibm::{acosh, asinh, atanh};
+
+// SAFETY: These are pure functions defined by AK/MathFunctions.cpp.
+unsafe extern "C" {
+ safe fn ladybird_math_acos(x: f64) -> f64;
+ safe fn ladybird_math_acosf(x: f32) -> f32;
+ safe fn ladybird_math_asin(x: f64) -> f64;
+ safe fn ladybird_math_asinf(x: f32) -> f32;
+ safe fn ladybird_math_atan(x: f64) -> f64;
+ safe fn ladybird_math_atanf(x: f32) -> f32;
+ safe fn ladybird_math_cbrt(x: f64) -> f64;
+ safe fn ladybird_math_cbrtf(x: f32) -> f32;
+ safe fn ladybird_math_cos(x: f64) -> f64;
+ safe fn ladybird_math_cosf(x: f32) -> f32;
+ safe fn ladybird_math_cosh(x: f64) -> f64;
+ safe fn ladybird_math_coshf(x: f32) -> f32;
+ safe fn ladybird_math_exp(x: f64) -> f64;
+ safe fn ladybird_math_expf(x: f32) -> f32;
+ safe fn ladybird_math_exp2(x: f64) -> f64;
+ safe fn ladybird_math_exp2f(x: f32) -> f32;
+ safe fn ladybird_math_expm1(x: f64) -> f64;
+ safe fn ladybird_math_expm1f(x: f32) -> f32;
+ safe fn ladybird_math_log(x: f64) -> f64;
+ safe fn ladybird_math_logf(x: f32) -> f32;
+ safe fn ladybird_math_log10(x: f64) -> f64;
+ safe fn ladybird_math_log10f(x: f32) -> f32;
+ safe fn ladybird_math_log1p(x: f64) -> f64;
+ safe fn ladybird_math_log1pf(x: f32) -> f32;
+ safe fn ladybird_math_log2(x: f64) -> f64;
+ safe fn ladybird_math_log2f(x: f32) -> f32;
+ safe fn ladybird_math_sin(x: f64) -> f64;
+ safe fn ladybird_math_sinf(x: f32) -> f32;
+ safe fn ladybird_math_sinh(x: f64) -> f64;
+ safe fn ladybird_math_sinhf(x: f32) -> f32;
+ safe fn ladybird_math_tan(x: f64) -> f64;
+ safe fn ladybird_math_tanf(x: f32) -> f32;
+ safe fn ladybird_math_tanh(x: f64) -> f64;
+ safe fn ladybird_math_tanhf(x: f32) -> f32;
+ safe fn ladybird_math_atan2(y: f64, x: f64) -> f64;
+ safe fn ladybird_math_atan2f(y: f32, x: f32) -> f32;
+ safe fn ladybird_math_hypot(x: f64, y: f64) -> f64;
+ safe fn ladybird_math_hypotf(x: f32, y: f32) -> f32;
+ safe fn ladybird_math_pow(x: f64, y: f64) -> f64;
+ safe fn ladybird_math_powf(x: f32, y: f32) -> f32;
+}
+
+// SAFETY: These write the sine and cosine through the two pointers, and have no other effects.
+unsafe extern "C" {
+ fn ladybird_math_sincos(x: f64, sin_value: *mut f64, cos_value: *mut f64);
+ fn ladybird_math_sincosf(x: f32, sin_value: *mut f32, cos_value: *mut f32);
+}
+
+macro_rules! define_math_functions {
+ (
+ unary: [$($unary:ident => $unary_f64:ident, $unary_f32:ident;)*]
+ binary: [$($binary:ident => $binary_f64:ident, $binary_f32:ident;)*]
+ ) => {
+ pub trait Float: Copy {
+ $(
+ #[doc(hidden)]
+ fn $unary(x: Self) -> Self;
+ )*
+ $(
+ #[doc(hidden)]
+ fn $binary(x: Self, y: Self) -> Self;
+ )*
+ #[doc(hidden)]
+ fn sincos(x: Self) -> (Self, Self);
+ }
+
+ impl Float for f64 {
+ $(
+ #[inline]
+ fn $unary(x: f64) -> f64 {
+ $unary_f64(x)
+ }
+ )*
+ $(
+ #[inline]
+ fn $binary(x: f64, y: f64) -> f64 {
+ $binary_f64(x, y)
+ }
+ )*
+ #[inline]
+ fn sincos(x: f64) -> (f64, f64) {
+ let (mut sin_value, mut cos_value) = (0.0, 0.0);
+ // SAFETY: Both pointers are to locals that outlive the call.
+ unsafe { ladybird_math_sincos(x, &raw mut sin_value, &raw mut cos_value) };
+ (sin_value, cos_value)
+ }
+ }
+
+ impl Float for f32 {
+ $(
+ #[inline]
+ fn $unary(x: f32) -> f32 {
+ $unary_f32(x)
+ }
+ )*
+ $(
+ #[inline]
+ fn $binary(x: f32, y: f32) -> f32 {
+ $binary_f32(x, y)
+ }
+ )*
+ #[inline]
+ fn sincos(x: f32) -> (f32, f32) {
+ let (mut sin_value, mut cos_value) = (0.0, 0.0);
+ // SAFETY: Both pointers are to locals that outlive the call.
+ unsafe { ladybird_math_sincosf(x, &raw mut sin_value, &raw mut cos_value) };
+ (sin_value, cos_value)
+ }
+ }
+
+ $(
+ #[inline]
+ pub fn $unary<T: Float>(x: T) -> T {
+ T::$unary(x)
+ }
+ )*
+ $(
+ #[inline]
+ pub fn $binary<T: Float>(x: T, y: T) -> T {
+ T::$binary(x, y)
+ }
+ )*
+ };
+}
+
+define_math_functions! {
+ unary: [
+ acos => ladybird_math_acos, ladybird_math_acosf;
+ asin => ladybird_math_asin, ladybird_math_asinf;
+ atan => ladybird_math_atan, ladybird_math_atanf;
+ cbrt => ladybird_math_cbrt, ladybird_math_cbrtf;
+ cos => ladybird_math_cos, ladybird_math_cosf;
+ cosh => ladybird_math_cosh, ladybird_math_coshf;
+ exp => ladybird_math_exp, ladybird_math_expf;
+ exp2 => ladybird_math_exp2, ladybird_math_exp2f;
+ expm1 => ladybird_math_expm1, ladybird_math_expm1f;
+ log => ladybird_math_log, ladybird_math_logf;
+ log10 => ladybird_math_log10, ladybird_math_log10f;
+ log1p => ladybird_math_log1p, ladybird_math_log1pf;
+ log2 => ladybird_math_log2, ladybird_math_log2f;
+ sin => ladybird_math_sin, ladybird_math_sinf;
+ sinh => ladybird_math_sinh, ladybird_math_sinhf;
+ tan => ladybird_math_tan, ladybird_math_tanf;
+ tanh => ladybird_math_tanh, ladybird_math_tanhf;
+ ]
+ binary: [
+ atan2 => ladybird_math_atan2, ladybird_math_atan2f;
+ hypot => ladybird_math_hypot, ladybird_math_hypotf;
+ pow => ladybird_math_pow, ladybird_math_powf;
+ ]
+}
+
+#[inline]
+pub fn sincos<T: Float>(x: T) -> (T, T) {
+ T::sincos(x)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn hypot_does_not_overflow_for_large_finite_arguments() {
+ assert_eq!(
+ hypot(
+ f64::from_bits(0x765f_ffff_ffff_fffe),
+ f64::from_bits(0x74bf_ffff_ffff_ffff)
+ ),
+ 1.5744403932561433e262
+ );
+ }
+
+ #[test]
+ fn sincos_matches_sin_and_cos() {
+ for x in [0.5f64, 1.0, 3.0, 1.0e10] {
+ assert_eq!(sincos(x), (sin(x), cos(x)));
+ }
+ assert_eq!(sincos(0.5f32), (sin(0.5f32), cos(0.5f32)));
+ }
+
+ #[test]
+ fn inverse_hyperbolic_functions() {
+ assert_eq!(acosh(1.0), 0.0);
+ assert!(acosh(0.5).is_nan());
+ assert_eq!(asinh(-0.0).to_bits(), (-0.0f64).to_bits());
+ assert_eq!(atanh(1.0), f64::INFINITY);
+ assert!((asinh(1.0) - 0.881_373_587_019_543).abs() < 1e-15);
+ assert!((acosh(2.0) - 1.316_957_896_924_816_6).abs() < 1e-15);
+ assert!((atanh(0.5) - 0.549_306_144_334_054_9).abs() < 1e-15);
+ }
+}
diff --git a/AK/Rust/src/math/fdlibm.rs b/AK/Rust/src/math/fdlibm.rs
new file mode 100644
index 00000000000..0d13debf771
--- /dev/null
+++ b/AK/Rust/src/math/fdlibm.rs
@@ -0,0 +1,112 @@
+/*
+ * Copyright 2016 the V8 project authors. All rights reserved.
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: SunPro
+ */
+// Source: v8/src/base/ieee754.cc, which is adapted from fdlibm (http://www.netlib.org/fdlibm).
+//
+// ====================================================
+// Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
+//
+// Developed at SunSoft, a Sun Microsystems, Inc. business.
+// Permission to use, copy, modify, and distribute this
+// software is freely granted, provided that this notice
+// is preserved.
+// ====================================================
+
+//! The inverse hyperbolic functions for f64, which LLVM libc does not have yet. These are built on its log and log1p.
+
+use super::{log, log1p};
+use core::f64::consts::LN_2;
+
+fn high_word(x: f64) -> i32 {
+ (x.to_bits() >> 32) as i32
+}
+
+/// acosh(x) = log(x + sqrt(x * x - 1)), computed as:
+/// - log(x) + ln2, if x is large;
+/// - log(2x - 1 / (sqrt(x * x - 1) + x)), if x > 2;
+/// - log1p(t + sqrt(2t + t * t)) with t = x - 1, otherwise.
+pub fn acosh(x: f64) -> f64 {
+ let high = high_word(x);
+ // x < 1
+ if high < 0x3ff0_0000 {
+ return f64::NAN;
+ }
+ // x > 2^28
+ if high >= 0x41b0_0000 {
+ // x is Infinity or NaN
+ if high >= 0x7ff0_0000 {
+ return x + x;
+ }
+ return log(x) + LN_2;
+ }
+ if x == 1.0 {
+ return 0.0;
+ }
+ // 2^28 > x > 2
+ if high > 0x4000_0000 {
+ let t = x * x;
+ return log(2.0 * x - 1.0 / (x + (t - 1.0).sqrt()));
+ }
+ // 1 < x <= 2
+ let t = x - 1.0;
+ log1p(t + (2.0 * t + t * t).sqrt())
+}
+
+/// asinh(x) = sign(x) * log(|x| + sqrt(x * x + 1)), computed as:
+/// - x, if 1 + x * x = 1;
+/// - sign(x) * (log(|x|) + ln2), if |x| is large;
+/// - sign(x) * log(2|x| + 1 / (|x| + sqrt(x * x + 1))), if |x| > 2;
+/// - sign(x) * log1p(|x| + x^2 / (1 + sqrt(1 + x^2))), otherwise.
+pub fn asinh(x: f64) -> f64 {
+ let high = high_word(x);
+ let magnitude_high = high & 0x7fff_ffff;
+ // x is Infinity or NaN
+ if magnitude_high >= 0x7ff0_0000 {
+ return x + x;
+ }
+ // |x| < 2^-28
+ if magnitude_high < 0x3e30_0000 {
+ return x;
+ }
+ let magnitude = x.abs();
+ let w = if magnitude_high > 0x41b0_0000 {
+ // |x| > 2^28
+ log(magnitude) + LN_2
+ } else if magnitude_high > 0x4000_0000 {
+ // 2^28 >= |x| > 2
+ log(2.0 * magnitude + 1.0 / ((x * x + 1.0).sqrt() + magnitude))
+ } else {
+ // 2 >= |x| >= 2^-28
+ let t = x * x;
+ log1p(magnitude + t / (1.0 + (1.0 + t).sqrt()))
+ };
+ if high > 0 { w } else { -w }
+}
+
+/// atanh(x) = 0.5 * log((1 + x) / (1 - x)), computed for |x| as:
+/// - 0.5 * log1p(2|x| / (1 - |x|)), if |x| >= 0.5;
+/// - 0.5 * log1p(2|x| + 2|x| * |x| / (1 - |x|)), otherwise.
+pub fn atanh(x: f64) -> f64 {
+ let magnitude = x.abs();
+ // |x| > 1, or x is NaN
+ if magnitude.is_nan() || magnitude > 1.0 {
+ return f64::NAN;
+ }
+ if magnitude == 1.0 {
+ return if x > 0.0 { f64::INFINITY } else { f64::NEG_INFINITY };
+ }
+ // |x| < 2^-28
+ if high_word(magnitude) < 0x3e30_0000 {
+ return x;
+ }
+ let t = if magnitude < 0.5 {
+ let twice = magnitude + magnitude;
+ 0.5 * log1p(twice + twice * magnitude / (1.0 - magnitude))
+ } else {
+ 0.5 * log1p((magnitude + magnitude) / (1.0 - magnitude))
+ };
+ if x >= 0.0 { t } else { -t }
+}
diff --git a/Cargo.lock b/Cargo.lock
index aad812c76ed..ebe53d599a5 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -84,6 +84,9 @@ dependencies = [
[[package]]
name = "ak"
version = "0.1.0"
+dependencies = [
+ "cc",
+]
[[package]]
name = "alloc-no-stdlib"
diff --git a/Meta/CMake/rust_crate.cmake b/Meta/CMake/rust_crate.cmake
index baf99d46a1d..ad2d0e3b20e 100644
--- a/Meta/CMake/rust_crate.cmake
+++ b/Meta/CMake/rust_crate.cmake
@@ -410,6 +410,13 @@ function(_rust_crate_common_setup)
list(APPEND cargo_env "FFI_OUTPUT_DIR=${ARG_FFI_OUTPUT_DIR}")
endif()
+ # The crates of the shared target directory link into libraries that link AK, so the ak crate leaves the math
+ # functions to AK rather than compiling a copy of its own.
+ if (NOT ARG_TARGET_DIR)
+ list(APPEND cargo_env "LADYBIRD_LINKS_AK=1")
+ endif()
+ list(APPEND cargo_env "LLVM_LIBC_INCLUDE_DIR=${LLVM_LIBC_INCLUDE_DIR}/llvm-libc")
+
# On Windows, rustc invokes the linker directly with MSVC-style flags, so we must not override it with a
# compiler driver like clang-cl.
if (NOT WIN32)
diff --git a/Meta/Linters/check_style.py b/Meta/Linters/check_style.py
index a5d0986edf3..f024302c2fa 100755
--- a/Meta/Linters/check_style.py
+++ b/Meta/Linters/check_style.py
@@ -26,6 +26,7 @@ GOOD_LADYBIRD_COPYRIGHT_PATTERN = re.compile("^ \\* Copyright \\(c\\) [0-9]{4}-p
LICENSE_HEADER_CHECK_EXCLUDES = {
"AK/Checked.h",
"AK/Function.h",
+ "AK/Rust/src/math/fdlibm.rs",
"Libraries/LibCore/SocketpairWindows.cpp",
"Libraries/LibMedia/Audio/WSOLAAlgorithm.cpp",
"Libraries/LibMedia/Audio/WSOLAAlgorithm.h",
diff --git a/Tests/CMakeLists.txt b/Tests/CMakeLists.txt
index dacc1cc890b..ca8c199cc82 100644
--- a/Tests/CMakeLists.txt
+++ b/Tests/CMakeLists.txt
@@ -37,7 +37,10 @@ add_subdirectory(Meta)
if (NOT WIN32)
string(TOUPPER "${RUST_TARGET_TRIPLE}" rust_target_upper)
string(REPLACE "-" "_" rust_target_upper "${rust_target_upper}")
- set(rust_test_env "CARGO_TARGET_${rust_target_upper}_RUSTFLAGS=${RUSTC_TARGET_FLAGS}")
+ set(rust_test_env
+ "CARGO_TARGET_${rust_target_upper}_RUSTFLAGS=${RUSTC_TARGET_FLAGS}"
+ "LLVM_LIBC_INCLUDE_DIR=${LLVM_LIBC_INCLUDE_DIR}/llvm-libc"
+ )
set(rust_workspace_test_command
"${CMAKE_COMMAND}" -E env