diff --git a/Cargo.lock b/Cargo.lock index 16e9262aa2e..ac43e38d4e1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -510,22 +510,6 @@ dependencies = [ "syn", ] -[[package]] -name = "bun_codegen" -version = "0.0.0" -dependencies = [ - "bitflags", - "bstr", - "bun_core", - "const_format", - "enum-map", - "enumset", - "libc", - "phf 0.11.3", - "scopeguard", - "strum", -] - [[package]] name = "bun_collections" version = "0.0.0" @@ -1305,24 +1289,6 @@ dependencies = [ "strum", ] -[[package]] -name = "bun_libarchive_sys" -version = "0.0.0" -dependencies = [ - "bitflags", - "bstr", - "bun_alloc", - "bun_core", - "bun_opaque", - "const_format", - "enum-map", - "enumset", - "libc", - "phf 0.11.3", - "scopeguard", - "strum", -] - [[package]] name = "bun_libdeflate_sys" version = "0.0.0" @@ -1398,21 +1364,6 @@ dependencies = [ "strum", ] -[[package]] -name = "bun_meta" -version = "0.0.0" -dependencies = [ - "bitflags", - "bstr", - "const_format", - "enum-map", - "enumset", - "libc", - "phf 0.11.3", - "scopeguard", - "strum", -] - [[package]] name = "bun_mimalloc_sys" version = "0.0.0" @@ -1429,21 +1380,6 @@ dependencies = [ "strum", ] -[[package]] -name = "bun_node-fallbacks" -version = "0.0.0" -dependencies = [ - "bitflags", - "bstr", - "const_format", - "enum-map", - "enumset", - "libc", - "phf 0.11.3", - "scopeguard", - "strum", -] - [[package]] name = "bun_opaque" version = "0.0.0" @@ -1607,21 +1543,6 @@ dependencies = [ "strum", ] -[[package]] -name = "bun_picohttp_sys" -version = "0.0.0" -dependencies = [ - "bitflags", - "bstr", - "const_format", - "enum-map", - "enumset", - "libc", - "phf 0.11.3", - "scopeguard", - "strum", -] - [[package]] name = "bun_platform" version = "0.0.0" @@ -2272,24 +2193,6 @@ dependencies = [ "strum", ] -[[package]] -name = "bun_unicode" -version = "0.0.0" -dependencies = [ - "bitflags", - "bstr", - "bun_collections", - "bun_core", - "const_format", - "enum-map", - "enumset", - "libc", - "phf 0.11.3", - "scopeguard", - "strum", - "thiserror", -] - [[package]] name = "bun_url" version = "0.0.0" @@ -2310,24 +2213,6 @@ dependencies = [ "strum", ] -[[package]] -name = "bun_url_jsc" -version = "0.0.0" -dependencies = [ - "bitflags", - "bstr", - "bun_core", - "bun_jsc", - "bun_url", - "const_format", - "enum-map", - "enumset", - "libc", - "phf 0.11.3", - "scopeguard", - "strum", -] - [[package]] name = "bun_uws" version = "0.0.0" diff --git a/Cargo.toml b/Cargo.toml index fd21868402e..99eac8bedf3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,6 @@ members = [ "src/api", "src/base64", "src/bundler", - "src/codegen", "src/collections", "src/css", "src/errno", @@ -19,8 +18,6 @@ members = [ "src/js", "src/libarchive", "src/md", - "src/meta", - "src/node-fallbacks", "src/paths", "src/resolver", "src/safety", @@ -29,7 +26,6 @@ members = [ "src/sql", "src/sys", "src/threading", - "src/unicode", "src/valkey", "src/watcher", "src/cares_sys", @@ -51,7 +47,6 @@ members = [ "src/js_parser", "src/js_parser_jsc", "src/js_printer", - "src/libarchive_sys", "src/libdeflate_sys", "src/libuv_sys", "src/ast", @@ -65,7 +60,6 @@ members = [ "src/platform", "src/sha_hmac", "src/sys_jsc", - "src/url_jsc", "src/zlib_sys", "src/dispatch", "src/brotli", @@ -82,7 +76,6 @@ members = [ "src/brotli_sys", "src/bun_alloc", "src/mimalloc_sys", - "src/picohttp_sys", "src/semver_jsc", "src/standalone_graph", "src/uws", @@ -188,11 +181,26 @@ codegen-units = 1 strip = "symbols" [workspace.lints.rust] +# Every rustc warning is an error. Individual lints below can override this +# back to "warn" (their priority 0 beats the group's -1) where a warning level +# is intentional. +warnings = { level = "deny", priority = -1 } # `bun_asan` is set via RUSTFLAGS (`--cfg=bun_asan` + `--check-cfg=cfg(bun_asan)`) # by scripts/build/rust.ts for asan builds; register it here so a plain # `cargo build` / `cargo check` (without those flags) doesn't warn. unexpected_cfgs = { level = "warn", check-cfg = ['cfg(bun_asan)'] } +# link.exe unconditionally prints "Creating library X.dll.lib and object +# X.dll.exp" to stdout when linking each proc-macro DLL on Windows hosts; +# there is no linker flag to suppress it. The lint already exempts itself +# from `-D warnings`, so this only silences the noise. +linker_messages = "allow" dead_code = "deny" +# Every crate in this workspace is an internal implementation detail of one +# binary, so `pub` is a claim that *another crate* imports the item. If it +# doesn't, write `pub(crate)` — that keeps the item under `dead_code` analysis +# instead of being exempted as an external API root. Macro-generated items that +# must stay `pub` carry `#[allow(unreachable_pub)]` at the expansion site. +unreachable_pub = "deny" unused_imports = "deny" unused_variables = "deny" unused_mut = "deny" @@ -339,7 +347,6 @@ memchr = "2" rustix = { version = "0.38", default-features = false, features = ["std", "fs", "event", "process", "net"] } bitflags = "2" thiserror = "2" -crossbeam = "0.8" smallvec = "1" bumpalo = { version = "3", features = ["collections", "boxed"] } typed-arena = "2" @@ -349,7 +356,6 @@ bun_analytics = { path = "src/analytics" } bun_api = { path = "src/api" } bun_base64 = { path = "src/base64" } bun_bundler = { path = "src/bundler" } -bun_codegen = { path = "src/codegen" } bun_collections = { path = "src/collections" } bun_css = { path = "src/css" } bun_errno = { path = "src/errno" } @@ -361,8 +367,6 @@ bun_io = { path = "src/io" } bun_js = { path = "src/js" } bun_libarchive = { path = "src/libarchive" } bun_md = { path = "src/md" } -bun_meta = { path = "src/meta" } -bun_node-fallbacks = { path = "src/node-fallbacks" } bun_paths = { path = "src/paths" } bun_resolver = { path = "src/resolver" } bun_safety = { path = "src/safety" } @@ -371,7 +375,6 @@ bun_sourcemap = { path = "src/sourcemap" } bun_sql = { path = "src/sql" } bun_sys = { path = "src/sys" } bun_threading = { path = "src/threading" } -bun_unicode = { path = "src/unicode" } bun_valkey = { path = "src/valkey" } bun_watcher = { path = "src/watcher" } bun_cares_sys = { path = "src/cares_sys" } @@ -393,7 +396,6 @@ bun_install_types = { path = "src/install_types" } bun_js_parser = { path = "src/js_parser" } bun_js_parser_jsc = { path = "src/js_parser_jsc" } bun_js_printer = { path = "src/js_printer" } -bun_libarchive_sys = { path = "src/libarchive_sys" } bun_libdeflate_sys = { path = "src/libdeflate_sys" } bun_libuv_sys = { path = "src/libuv_sys" } bun_ast = { path = "src/ast" } @@ -407,7 +409,6 @@ bun_patch = { path = "src/patch" } bun_platform = { path = "src/platform" } bun_sha_hmac = { path = "src/sha_hmac" } bun_sys_jsc = { path = "src/sys_jsc" } -bun_url_jsc = { path = "src/url_jsc" } bun_zlib_sys = { path = "src/zlib_sys" } bun_dispatch = { path = "src/dispatch" } bun_brotli = { path = "src/brotli" } @@ -424,7 +425,6 @@ bun_boringssl = { path = "src/boringssl" } bun_brotli_sys = { path = "src/brotli_sys" } bun_alloc = { path = "src/bun_alloc" } bun_mimalloc_sys = { path = "src/mimalloc_sys" } -bun_picohttp_sys = { path = "src/picohttp_sys" } bun_semver_jsc = { path = "src/semver_jsc" } bun_standalone_graph = { path = "src/standalone_graph" } bun_uws = { path = "src/uws" } diff --git a/scripts/find-dead-exports.ts b/scripts/find-dead-exports.ts new file mode 100644 index 00000000000..39512f5ed92 --- /dev/null +++ b/scripts/find-dead-exports.ts @@ -0,0 +1,303 @@ +#!/usr/bin/env bun +/** + * Find `pub` items that no other workspace crate references. + * + * `dead_code` treats every externally-reachable `pub` item as an API root and + * never analyzes it; `unreachable_pub` only fires when the *module path* blocks + * external access. Neither asks "does another crate actually import this?" — + * in a workspace where every crate is an internal implementation detail of one + * binary, that is the question that matters. This script answers it by diffing + * each crate's exported names against the union of names every other crate + * references through that crate's paths. + * + * The output is a *candidate* list, not a verdict: name matching is textual + * (an identifier appearing anywhere in a `bun_x::…` path or `use bun_x::…` + * statement counts as a use), so macro-expanded references that never appear + * in the consuming crate's source are missed. Verify by demoting a candidate + * to `pub(crate)` and compiling the workspace — a miss shows up as E0603. + * + * bun scripts/find-dead-exports.ts # full report + * bun scripts/find-dead-exports.ts bun_ast # one crate + * bun scripts/find-dead-exports.ts --json # machine-readable + */ + +import { readdirSync, readFileSync, statSync } from "node:fs"; +import { join, relative, resolve } from "node:path"; + +const ROOT = resolve(import.meta.dir, ".."); +const args = process.argv.slice(2); +const asJson = args.includes("--json"); +const onlyCrate = args.find(a => !a.startsWith("--")); + +// ── workspace layout ──────────────────────────────────────────────────────── + +interface Crate { + name: string; + dir: string; // relative to ROOT + files: string[]; // .rs files, relative to ROOT +} + +function rustFiles(dir: string): string[] { + const out: string[] = []; + for (const e of readdirSync(dir)) { + const p = join(dir, e); + const st = statSync(p); + if (st.isDirectory()) { + if (e === "target" || e === "node_modules") continue; + out.push(...rustFiles(p)); + } else if (e.endsWith(".rs")) { + out.push(p); + } + } + return out; +} + +function loadWorkspace(): Crate[] { + const rootToml = readFileSync(join(ROOT, "Cargo.toml"), "utf8"); + const membersBlock = rootToml.match(/members\s*=\s*\[([\s\S]*?)\]/)?.[1] ?? ""; + const dirs = [...membersBlock.matchAll(/"([^"]+)"/g)].map(m => m[1]); + const crates: Crate[] = []; + for (const dir of dirs) { + const tomlPath = join(ROOT, dir, "Cargo.toml"); + let name: string; + try { + name = readFileSync(tomlPath, "utf8").match(/^name\s*=\s*"([^"]+)"/m)![1]; + } catch { + continue; + } + // Crate names with `-` are referenced in Rust paths with `_`. + crates.push({ name: name.replace(/-/g, "_"), dir, files: rustFiles(join(ROOT, dir)).map(f => relative(ROOT, f)) }); + } + return crates; +} + +// ── export side: every `pub `-declared item ───────────────────────────────── +// After `unreachable_pub = deny`, a surviving bare-`pub` item is necessarily in +// a fully-public module chain, i.e. externally reachable. So "all pub items" +// IS the export set — no module-tree walk needed. + +interface Export { + name: string; + kind: string; + file: string; + line: number; +} + +const ITEM_RE = + /^\s*pub\s+(?:(?:unsafe|async|extern\s+"[^"]*"|const|safe)\s+)*(fn|struct|enum|trait|union|type|static|const|mod)\s+([A-Za-z_][A-Za-z0-9_]*)/; +// `pub use path::{A, B as C, D}` / `pub use path::Name` / `pub use path as Alias` +const USE_RE = /^\s*pub\s+use\s+(.+);\s*$/; + +function collectExports(crate: Crate): Export[] { + const out: Export[] = []; + for (const file of crate.files) { + const lines = readFileSync(join(ROOT, file), "utf8").split("\n"); + let inTestMod = false; + let testModDepth = 0; + let depth = 0; + // Methods and associated items are referenced through their *type* + // (`val.method()`, `Type::CONST`), never through a crate-qualified path, + // so grep cannot see their uses. Exclude everything inside impl/trait + // blocks — only path-addressable free items are auditable here. + const implStack: number[] = []; + // Set when an impl/trait header has no `{` on its own line (rustfmt wraps + // the brace onto a later line for long headers and where-clauses); the + // push happens on the first subsequent line that opens the block. + let pendingImpl = false; + for (let i = 0; i < lines.length; i++) { + const l = lines[i]; + // crude #[cfg(test)] mod skip — items only compiled for tests are not API + if (/^\s*#\[cfg\(test\)\]/.test(l) && /^\s*(pub\s+)?mod\s/.test(lines[i + 1] ?? "")) { + inTestMod = true; + testModDepth = depth; + continue; + } + const isImplOrTrait = /^\s*(unsafe\s+)?impl[\s<]/.test(l) || /^\s*(pub\s+)?(unsafe\s+)?trait\s/.test(l); + if (isImplOrTrait && l.includes("{")) implStack.push(depth); + else if (isImplOrTrait && !l.includes(";")) pendingImpl = true; + else if (pendingImpl && l.includes("{")) { + implStack.push(depth); + pendingImpl = false; + } + const opens = (l.match(/\{/g) ?? []).length; + const closes = (l.match(/\}/g) ?? []).length; + const inImpl = implStack.length > 0; + depth += opens - closes; + while (implStack.length && depth <= implStack[implStack.length - 1]) implStack.pop(); + if (inTestMod && depth <= testModDepth) inTestMod = false; + if (inTestMod) continue; + if (inImpl && !isImplOrTrait) continue; + + const m = ITEM_RE.exec(l); + if (m) { + out.push({ name: m[2], kind: m[1], file, line: i + 1 }); + continue; + } + const u = USE_RE.exec(l) ?? (l.trimStart().startsWith("pub use") ? collectMultilineUse(lines, i) : null); + if (u) { + for (const name of namesFromUseTail(u[1])) { + out.push({ name, kind: "use", file, line: i + 1 }); + } + } + } + } + return out; +} + +/** `pub use a::b::{C, D as E, f::G};` → the names this re-export *introduces*. */ +function namesFromUseTail(tail: string): string[] { + tail = tail.replace(/\s+/g, " ").trim(); + const names: string[] = []; + const brace = tail.match(/\{([\s\S]*)\}/); + if (brace) { + for (const part of brace[1].split(",")) { + const p = part.trim(); + if (!p || p === "self") continue; + const as = p.match(/\bas\s+([A-Za-z_][A-Za-z0-9_]*)$/); + if (as) names.push(as[1]); + else { + const last = p.split("::").pop()!.trim(); + if (last !== "*" && /^[A-Za-z_]/.test(last)) names.push(last); + } + } + } else { + const as = tail.match(/\bas\s+([A-Za-z_][A-Za-z0-9_]*)$/); + if (as) names.push(as[1]); + else { + const last = tail.split("::").pop()!.trim(); + if (last !== "*" && /^[A-Za-z_]/.test(last)) names.push(last); + } + } + return names; +} + +function collectMultilineUse(lines: string[], i: number): RegExpExecArray | null { + // `pub use foo::{\n A,\n B,\n};` spans lines — join until the `;` + let buf = ""; + for (let j = i; j < Math.min(i + 40, lines.length); j++) { + buf += lines[j] + " "; + if (lines[j].includes(";")) break; + } + return USE_RE.exec(buf.trim()); +} + +// ── import side: identifiers referenced through `crate_name::…` paths ─────── + +function collectReferences(crates: Crate[]): Map> { + // crate name → set of identifiers seen in any path rooted at that crate, + // from any *other* crate's source (plus generated code). + const refs = new Map>(crates.map(c => [c.name, new Set()])); + const crateNames = new Set(crates.map(c => c.name)); + + // `extern crate X as Y;` → references to `Y::…` are references to `X`. + const aliases = new Map(); + for (const c of crates) { + for (const f of c.files) { + for (const m of readFileSync(join(ROOT, f), "utf8").matchAll( + /extern crate ([A-Za-z_][A-Za-z0-9_]*) as ([A-Za-z_][A-Za-z0-9_]*)/g, + )) { + if (crateNames.has(m[1]) && m[2] !== m[1]) aliases.set(m[2], m[1]); + } + } + } + + const sources: { file: string; ownerCrate: string | null }[] = []; + for (const c of crates) for (const f of c.files) sources.push({ file: f, ownerCrate: c.name }); + // Generated code references workspace items but belongs to whichever crate + // include!()s it — attribute it to no crate so all its references count. + for (const genDir of ["build/debug/codegen", "build/release/codegen"]) { + try { + for (const f of rustFiles(join(ROOT, genDir))) sources.push({ file: relative(ROOT, f), ownerCrate: null }); + } catch {} + } + + // Two reference forms: + // (a) qualified paths in code: `bun_core::strings::index_of(...)` + // (b) use statements, possibly brace-grouped over multiple lines: + // `use bun_core::{String, output::{self, Output}};` + // (b) is the dominant style (rustfmt groups imports) and its leaf names are + // bare identifiers inside braces, not `::`-joined paths — handle separately. + const PATH_RE = /\b([A-Za-z_][A-Za-z0-9_]*)((?:::[A-Za-z_*][A-Za-z0-9_]*)+)/g; + const USE_STMT_RE = /^[ \t]*(?:pub(?:\([^)]*\))?[ \t]+)?use[ \t]+(?:::)?([A-Za-z_][A-Za-z0-9_]*)([^;]*);/gms; + for (const { file, ownerCrate } of sources) { + let text: string; + try { + text = readFileSync(join(ROOT, file), "utf8"); + } catch { + continue; + } + for (const m of text.matchAll(PATH_RE)) { + const root = aliases.get(m[1]) ?? m[1]; + if (!crateNames.has(root)) continue; + if (root === ownerCrate) continue; // self-references don't count + const set = refs.get(root)!; + for (const seg of m[2].split("::")) { + if (seg && seg !== "*") set.add(seg); + } + } + for (const m of text.matchAll(USE_STMT_RE)) { + const root = aliases.get(m[1]) ?? m[1]; + if (!crateNames.has(root)) continue; + if (root === ownerCrate) continue; + const set = refs.get(root)!; + for (const ident of m[2].matchAll(/[A-Za-z_][A-Za-z0-9_]*/g)) { + if (ident[0] !== "self" && ident[0] !== "as") set.add(ident[0]); + } + } + } + return refs; +} + +// ── diff ──────────────────────────────────────────────────────────────────── + +const crates = loadWorkspace(); +const refs = collectReferences(crates); + +// Crates consumed via `use crate::module::*` cross-crate glob imports: every +// name in them must be considered used. (Currently: bun_bundler::mal_prelude, +// bun_sql::…::FieldType.) Detect them so the report can flag the blind spot. +const globImportTargets = new Set(); +for (const c of crates) { + for (const f of c.files) { + for (const m of readFileSync(join(ROOT, f), "utf8").matchAll(/^\s*use ((?:::)?[A-Za-z_][A-Za-z0-9_:]*)::\*;/gm)) { + const root = m[1].replace(/^::/, "").split("::")[0]; + if (crates.some(x => x.name === root) && root !== c.name) globImportTargets.add(m[1]); + } + } +} + +interface Finding extends Export { + crate: string; +} +const findings: Finding[] = []; +let totalExports = 0; +for (const crate of crates) { + if (onlyCrate && crate.name !== onlyCrate) continue; + if (crate.name === "bun_bin") continue; // the staticlib root exports the C ABI, not Rust items + const exports = collectExports(crate); + totalExports += exports.length; + const used = refs.get(crate.name)!; + for (const e of exports) { + if (e.kind === "mod") continue; // a dead pub mod falls out once its contents are dead + if (!used.has(e.name)) findings.push({ ...e, crate: crate.name }); + } +} + +if (asJson) { + console.log(JSON.stringify(findings, null, 1)); +} else { + const byCrate = new Map(); + for (const f of findings) (byCrate.get(f.crate) ?? byCrate.set(f.crate, []).get(f.crate)!).push(f); + for (const [crate, list] of [...byCrate].sort((a, b) => b[1].length - a[1].length)) { + console.log(`\n${crate} — ${list.length} exported item(s) no other crate references`); + for (const f of list.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line)) { + console.log(` ${f.file}:${f.line} ${f.kind} ${f.name}`); + } + } + console.log(`\n────────────────────────────────────────`); + console.log(`${findings.length} candidate dead exports out of ${totalExports} exported items`); + if (globImportTargets.size) { + console.log(`note: cross-crate glob imports blind this analysis for: ${[...globImportTargets].join(", ")}`); + } + console.log(`verify a candidate by demoting it to pub(crate) and running cargo check --workspace`); +} diff --git a/scripts/update-uucode.sh b/scripts/update-uucode.sh deleted file mode 100755 index 0f9e8a8f560..00000000000 --- a/scripts/update-uucode.sh +++ /dev/null @@ -1,82 +0,0 @@ -#!/bin/bash -# Updates the vendored uucode library and regenerates grapheme tables. -# -# Usage: -# ./scripts/update-uucode.sh # update from default URL -# ./scripts/update-uucode.sh /path/to/uucode # update from local directory -# ./scripts/update-uucode.sh https://url.tar.gz # update from URL -# -# After running, verify with: -# bun bd test test/js/bun/util/stringWidth.test.ts - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -BUN_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" -UUCODE_DIR="$BUN_ROOT/src/unicode/uucode_lib" -ZIG="$BUN_ROOT/vendor/zig/zig" - -if [ ! -x "$ZIG" ]; then - echo "error: zig not found at $ZIG" - echo " run scripts/bootstrap.sh first" - exit 1 -fi - -update_from_dir() { - local src="$1" - echo "Updating uucode from: $src" - rm -rf "$UUCODE_DIR" - mkdir -p "$UUCODE_DIR" - cp -r "$src"/* "$UUCODE_DIR/" -} - -update_from_url() { - local url="$1" - local tmp - tmp=$(mktemp -d) - trap "rm -rf $tmp" EXIT - - echo "Downloading uucode from: $url" - curl -fsSL "$url" | tar -xz -C "$tmp" --strip-components=1 - - update_from_dir "$tmp" -} - -# Handle source argument -if [ $# -ge 1 ]; then - SOURCE="$1" - if [ -d "$SOURCE" ]; then - update_from_dir "$SOURCE" - elif [[ "$SOURCE" == http* ]]; then - update_from_url "$SOURCE" - else - echo "error: argument must be a directory or URL" - exit 1 - fi -else - # Default: use the zig global cache if available - CACHED=$(find "$HOME/.cache/zig/p" -maxdepth 1 -name "uucode-*" -type d 2>/dev/null | sort -V | tail -1) - if [ -n "$CACHED" ]; then - update_from_dir "$CACHED" - else - echo "error: no uucode source specified and none found in zig cache" - echo "" - echo "usage: $0 " - exit 1 - fi -fi - -echo "" -echo "Regenerating grapheme tables..." -cd "$BUN_ROOT" -"$ZIG" build generate-grapheme-tables - -echo "" -echo "Done. Updated files:" -echo " src/unicode/uucode_lib/ (vendored library)" -echo " src/string/immutable/grapheme_tables.zig (regenerated)" -echo "" -echo "Next steps:" -echo " 1. bun bd test test/js/bun/util/stringWidth.test.ts" -echo " 2. git add src/unicode/uucode_lib src/string/immutable/grapheme_tables.zig" -echo " 3. git commit -m 'Update uucode to '" diff --git a/src/analytics/lib.rs b/src/analytics/lib.rs index 4a8373accf7..4af975b761d 100644 --- a/src/analytics/lib.rs +++ b/src/analytics/lib.rs @@ -1,4 +1,3 @@ -#![warn(unreachable_pub)] use core::fmt; use core::sync::atomic::{AtomicU8, AtomicUsize, Ordering}; use std::sync::OnceLock; @@ -39,21 +38,13 @@ impl TriState { // Zig: `pub var enabled: enum { yes, no, unknown } = .unknown;` static ENABLED: AtomicU8 = AtomicU8::new(TriState::Unknown as u8); -// Zig: `pub var is_ci: enum { yes, no, unknown } = .unknown;` -static IS_CI: AtomicU8 = AtomicU8::new(TriState::Unknown as u8); -pub fn enabled() -> TriState { +pub(crate) fn enabled() -> TriState { TriState::from_u8(ENABLED.load(Ordering::Relaxed)) } pub fn set_enabled(v: TriState) { ENABLED.store(v as u8, Ordering::Relaxed); } -pub fn is_ci() -> TriState { - TriState::from_u8(IS_CI.load(Ordering::Relaxed)) -} -pub fn set_is_ci(v: TriState) { - IS_CI.store(v as u8, Ordering::Relaxed); -} pub fn is_enabled() -> bool { match enabled() { @@ -106,7 +97,7 @@ pub mod features { // `BUILTIN_MODULES.lock().insert(<&'static str>::from(hardcoded))`. // PERF(port): Zig used a packed `EnumSet` (bitset); BTreeSet is O(log n) // insert — fine for ≤~80 entries written once each at module-load time. - pub static BUILTIN_MODULES: bun_core::Mutex> = + pub(crate) static BUILTIN_MODULES: bun_core::Mutex> = bun_core::Mutex::new(std::collections::BTreeSet::new()); // PORT NOTE: Zig used a plain mutable global; wrapped in a Mutex here // because the set is not a single atomic word. @@ -317,7 +308,7 @@ pub use features::{ /// Zig: `pub fn validateFeatureName(name: []const u8) void` (comptime-only). /// In Rust this is enforced at the macro definition site; kept as a `const fn` /// for documentation / debug assertions. -pub const fn validate_feature_name(name: &[u8]) -> bool { +pub(crate) const fn validate_feature_name(name: &[u8]) -> bool { if name.len() > 64 { return false; } @@ -399,7 +390,7 @@ pub mod generate_header { libc::sysctlbyname( c"kern.osproductversion".as_ptr(), name.as_mut_ptr().cast(), - &mut len, + &raw mut len, core::ptr::null_mut(), 0, ) @@ -486,7 +477,7 @@ pub mod generate_header { } #[unsafe(no_mangle)] - pub extern "C" fn Bun__doesMacOSVersionSupportSendRecvMsgX() -> i32 { + pub(crate) extern "C" fn Bun__doesMacOSVersionSupportSendRecvMsgX() -> i32 { #[cfg(not(target_os = "macos"))] { // this should not be used on non-mac platforms. @@ -526,7 +517,7 @@ pub mod generate_header { } #[unsafe(no_mangle)] - pub extern "C" fn Bun__isEpollPwait2SupportedOnLinuxKernel() -> i32 { + pub(crate) extern "C" fn Bun__isEpollPwait2SupportedOnLinuxKernel() -> i32 { #[cfg(not(any(target_os = "linux", target_os = "android")))] { 0 diff --git a/src/analytics/schema.rs b/src/analytics/schema.rs index 72f09e28219..aa521e7e7d3 100644 --- a/src/analytics/schema.rs +++ b/src/analytics/schema.rs @@ -26,7 +26,7 @@ use bun_core::Error; // PORT NOTE: peechy's two error cases (`EOF`, `InvalidValue`) are folded into // the crate-wide `bun_core::Error` so downstream `decode` signatures stay // `Result<_, bun_core::Error>` without an extra `From` hop. -pub const EOF: Error = Error::TODO; // TODO(port): Error::from_name("EOF") once name→code table lands +pub(crate) const EOF: Error = Error::TODO; // TODO(port): Error::from_name("EOF") once name→code table lands /// Primitive integers encodable in the peechy wire format (native-endian raw /// bytes). Zig handled this via `comptime T` + `std.mem.readIntSliceNative` / diff --git a/src/api/lib.rs b/src/api/lib.rs index cab704f0ee3..de79a80e96c 100644 --- a/src/api/lib.rs +++ b/src/api/lib.rs @@ -26,7 +26,6 @@ // Re-exports — canonical definitions live in `bun_options_types::schema::api`. // ────────────────────────────────────────────────────────────────────────── -#![warn(unreachable_pub)] pub use bun_options_types::schema::api::{ BunInstall, Ca, NodeLinker, NpmRegistry, NpmRegistryMap, PnpmMatcher, }; diff --git a/src/ast/ast_result.rs b/src/ast/ast_result.rs index b9fd0332af5..644b5fd49d6 100644 --- a/src/ast/ast_result.rs +++ b/src/ast/ast_result.rs @@ -186,20 +186,6 @@ impl<'a> Ast<'a> { } } - // Zig: `std.json.stringify(self.parts, opts, stream)` where - // `opts = .{ .whitespace = .{ .separator = true } }`. In the Rust port the - // `crate::JsonWriter` trait stands in for the configured - // `std.json.WriteStream` (separator/whitespace are properties of the - // writer impl, not passed per-call), so the body collapses to a single - // `write` of the parts slice — the writer emits the JSON array, - // dispatching to `Part::json_stringify` per element (same shape as - // `Part::json_stringify` writing `self.stmts`). No live callers. - pub fn to_json(&self, stream: &mut W) -> Result<(), bun_core::Error> { - // PORT NOTE: `whitespace.separator = true` is the caller's - // responsibility when constructing the `JsonWriter` impl. - stream.write(self.parts.as_slice()) - } - // Zig `deinit` only freed `parts`, `symbols`, `import_records` via `bun.default_allocator`, // and was guarded by "Do not call this if it wasn't globally allocated!". // In Rust those fields own their storage and free on Drop; no explicit body needed. diff --git a/src/ast/base.rs b/src/ast/base.rs index a8caddd15bb..13131b32e25 100644 --- a/src/ast/base.rs +++ b/src/ast/base.rs @@ -181,12 +181,6 @@ impl Ref { symbol: symbol_table.get_symbol(self), } } - pub fn json_stringify( - self, - writer: &mut W, - ) -> Result<(), bun_core::Error> { - writer.write(&[self.source_index(), self.inner_index()]) - } } // Zig: `DumpImplData` + `dumpImpl` — formatter wrapper returned by `Ref.dump`. diff --git a/src/ast/binding.rs b/src/ast/binding.rs index 0377ef7ed8c..889d8bf546e 100644 --- a/src/ast/binding.rs +++ b/src/ast/binding.rs @@ -38,19 +38,10 @@ pub enum Tag { BMissing, } -impl Tag { - pub fn json_stringify( - self, - writer: &mut W, - ) -> Result<(), bun_core::Error> { - writer.write(<&'static str>::from(self)) - } -} - // Zig: `pub var icount: usize = 0;` — mutable global counter, never read. // Debug-only so release doesn't pay a contended `lock xadd` per Binding. #[cfg(debug_assertions)] -pub static ICOUNT: AtomicUsize = AtomicUsize::new(0); +pub(crate) static ICOUNT: AtomicUsize = AtomicUsize::new(0); // ────────────────────────────────────────────────────────────────────────── // `init` / `alloc` — Zig switched on `@TypeOf(t)` to pick the `B` variant. @@ -300,45 +291,4 @@ impl Binding { } } -// ────────────────────────────────────────────────────────────────────────── -// jsonStringify — Zig wrote a `Serializable` aggregate via the std.json -// protocol. The Rust JSON-writer trait is still shape-agnostic (`write`), -// so we mirror the Zig body 1:1 and let the writer impl decide how to emit -// the aggregate. `Serializable` is a private layout-only carrier. -// ────────────────────────────────────────────────────────────────────────── - -// Fields are the JSON-serialization payload (Zig std.json wrote each via -// `@typeInfo` reflection). No `BindingJsonWriter` implementor exists yet, so -// rustc correctly proves they are never *read*; they are the data contract for -// when the writer lands, not dead code. -#[expect(dead_code)] -pub struct Serializable { - r#type: Tag, - object: &'static [u8], - value: B, - loc: crate::Loc, -} - -impl Binding { - pub fn json_stringify(&self, writer: &mut W) -> Result<(), bun_core::Error> - where - W: BindingJsonWriter, - { - writer.write(Serializable { - r#type: self.data.tag(), - object: b"binding", - value: self.data, - loc: self.loc, - }) - } -} - -/// Stand-in for Zig's `anytype` json writer used by `Binding::json_stringify`. -/// Kept local (not `crate::JsonWriter`) because the crate-level trait is -/// currently `&str`-only; this preserves the Zig call-shape until the JSON -/// layer settles. -pub trait BindingJsonWriter { - fn write(&mut self, value: Serializable) -> Result<(), bun_core::Error>; -} - // ported from: src/js_parser/ast/Binding.zig diff --git a/src/ast/char_freq.rs b/src/ast/char_freq.rs index 39707cb8399..e329705ea8e 100644 --- a/src/ast/char_freq.rs +++ b/src/ast/char_freq.rs @@ -1,7 +1,7 @@ -pub const CHAR_FREQ_COUNT: usize = 64; +pub(crate) const CHAR_FREQ_COUNT: usize = 64; #[derive(Copy, Clone, Default)] -pub struct CharAndCount { +pub(crate) struct CharAndCount { pub char: u8, pub count: i32, pub index: usize, @@ -9,21 +9,7 @@ pub struct CharAndCount { // PORT NOTE: Zig `CharAndCount.Array` was an associated type alias; inherent // associated types are unstable in Rust, so it's a free alias here. -pub type CharAndCountArray = [CharAndCount; CHAR_FREQ_COUNT]; - -impl CharAndCount { - pub fn less_than(a: &CharAndCount, b: &CharAndCount) -> bool { - if a.count != b.count { - return a.count > b.count; - } - - if a.index != b.index { - return a.index < b.index; - } - - a.char < b.char - } -} +pub(crate) type CharAndCountArray = [CharAndCount; CHAR_FREQ_COUNT]; // PERF(port): Zig used `@Vector(CHAR_FREQ_COUNT, i32)` for SIMD adds — profile type Buffer = [i32; CHAR_FREQ_COUNT]; diff --git a/src/ast/e.rs b/src/ast/e.rs index 89e6043c321..d1d101d4fef 100644 --- a/src/ast/e.rs +++ b/src/ast/e.rs @@ -621,13 +621,15 @@ pub struct PrivateIdentifier { /// In development mode, the new JSX transform has a few special props /// - `React.jsxDEV(type, arguments, key, isStaticChildren, source, self)` /// - `arguments`: -/// ```{ ...props, children: children, }``` +/// `{ ...props, children: children, }` /// - `source`: https://github.com/babel/babel/blob/ef87648f3f05ccc393f89dea7d4c7c57abf398ce/packages/babel-plugin-transform-react-jsx-source/src/index.js#L24-L48 -/// ```{ -/// fileName: string | null, -/// columnNumber: number | null, -/// lineNumber: number | null, -/// }``` +/// ```text +/// { +/// fileName: string | null, +/// columnNumber: number | null, +/// lineNumber: number | null, +/// } +/// ``` /// - `children`: /// - static the function is React.jsxsDEV, "jsxs" instead of "jsx" /// - one child? the function is React.jsxDEV, @@ -707,11 +709,6 @@ impl JSXSpecialProp { } } -// `Missing` re-exported from `crate::E` above. -// TODO(port): `Missing::json_stringify` — Zig std.json protocol; orphan rules -// prevent an inherent impl here now that the type lives at T2. Pick a -// serde strategy (extension trait or move the method down). - #[derive(Clone, Copy)] pub struct Number { pub value: f64, @@ -824,13 +821,6 @@ impl Number { T::from_f64(clamped) } - pub fn json_stringify( - self, - writer: &mut W, - ) -> Result<(), bun_core::Error> { - writer.write(&self.value) - } - // `toJS` alias deleted — lives in `js_parser_jsc` extension trait. } @@ -859,13 +849,6 @@ pub struct BigInt { impl BigInt { pub const EMPTY: BigInt = BigInt { value: Str::EMPTY }; - pub fn json_stringify( - &self, - writer: &mut W, - ) -> Result<(), bun_core::Error> { - writer.write(&self.value) - } - // `toJS` alias deleted — lives in `js_parser_jsc` extension trait. } @@ -1826,23 +1809,6 @@ impl EString { ZigString::init_utf16(self.slice16()) } } - - // TODO(port): jsonStringify — Zig std.json protocol; pick a serde strategy. - pub fn json_stringify(&self, writer: &mut W) -> Result<(), bun_core::Error> { - let _ = writer; - let mut buf = [0u8; 4096]; - let mut i: usize = 0; - for &char in self.slice16() { - buf[i] = u8::try_from(char).expect("int cast"); - i += 1; - if i >= 4096 { - break; - } - } - let _ = &buf[..i]; - // writer.write(&buf[..i]) - Err(bun_core::err!(Unimplemented)) - } } impl fmt::Display for EString { @@ -2165,13 +2131,6 @@ impl RegExp { b"" } - - pub fn json_stringify( - &self, - writer: &mut W, - ) -> Result<(), bun_core::Error> { - writer.write(&self.value) - } } pub struct Await { diff --git a/src/ast/expr.rs b/src/ast/expr.rs index 5766dfeedf4..73b8f92140c 100644 --- a/src/ast/expr.rs +++ b/src/ast/expr.rs @@ -973,22 +973,6 @@ impl Expr { } } -// TODO(refactor): jsonStringify protocol — replace with serde or a custom trait. -// `Serializable` is its payload shape. - -impl Expr { - // PORT NOTE: Zig's `jsonStringify` fed `Serializable` to `std.json.stringify`. - // The Rust port emits the same shape directly (no serde dependency). - pub fn json_stringify(self_: &Expr, writer: &mut impl fmt::Write) -> fmt::Result { - let tag: &'static str = self_.data.tag().into(); - write!( - writer, - "{{\"type\":\"{}\",\"object\":\"expr\",\"loc\":{}}}", - tag, self_.loc.start - ) - } -} - // ─────────────────────────────────────────────────────────────────────────── // Static state // ─────────────────────────────────────────────────────────────────────────── @@ -1000,7 +984,7 @@ impl Expr { // (i.e. racy garbage under threads) so a debug-gated atomic is strictly more // faithful than the old unconditional one. #[cfg(debug_assertions)] -pub static ICOUNT: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0); +pub(crate) static ICOUNT: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0); // PORT NOTE: Zig `expr.zig` declares `true_bool`/`false_bool`/`bool_values` // statics but never references them — `E.Boolean` is stored by value in @@ -1320,11 +1304,6 @@ impl Tag { }) } - // TODO(port): jsonStringify — serde or custom JSON writer - pub fn json_stringify(self_: Tag, writer: &mut impl fmt::Write) -> fmt::Result { - writer.write_str(<&'static str>::from(self_)) - } - pub fn is_array(self) -> bool { matches!(self, Tag::EArray) } diff --git a/src/ast/g.rs b/src/ast/g.rs index 874c880e06b..9b557a9405e 100644 --- a/src/ast/g.rs +++ b/src/ast/g.rs @@ -256,16 +256,6 @@ pub enum PropertyKind { AutoAccessor, } -impl PropertyKind { - // TODO(port): Zig `jsonStringify(self, writer: anytype) !void` — maps to a serde-like - // protocol writing @tagName(self). Decide on a shared json writer trait. - pub fn json_stringify(self, writer: &mut impl core::fmt::Write) -> core::fmt::Result { - // Zig: `writer.write(@tagName(self))` on a std.json WriteStream — emits a - // *quoted* JSON string. Tag names are [a-z_] so no escaping needed. - write!(writer, "\"{}\"", <&'static str>::from(self)) - } -} - pub struct FnBody { pub loc: crate::Loc, pub stmts: StmtNodeList, diff --git a/src/ast/known_global.rs b/src/ast/known_global.rs index 4a3230f45a5..d50ac3bdd05 100644 --- a/src/ast/known_global.rs +++ b/src/ast/known_global.rs @@ -42,7 +42,7 @@ pub enum KnownGlobal { // no indirection. 21 keys, ≤3 per length bucket: well within the range where // open-coded dispatch beats `phf`. #[inline] -pub fn lookup(name: &[u8]) -> Option { +pub(crate) fn lookup(name: &[u8]) -> Option { match name.len() { 3 => match name { b"Set" => Some(KnownGlobal::Set), diff --git a/src/ast/lexer_tables.rs b/src/ast/lexer_tables.rs index e0dab17bcb1..a7a8487593a 100644 --- a/src/ast/lexer_tables.rs +++ b/src/ast/lexer_tables.rs @@ -977,10 +977,6 @@ mod tests { // Shared by `bun_ast::E::EString::is_identifier`, `bun_js_printer::renamer`, // and the parser's lexer. Data-only (codepoint tables live in `bun_core`). -#[inline] -pub fn is_identifier_start(codepoint: i32) -> bool { - bun_core::identifier::is_identifier_start(codepoint) -} #[inline] pub fn is_identifier_continue(codepoint: i32) -> bool { bun_core::identifier::is_identifier_part(codepoint) diff --git a/src/ast/lib.rs b/src/ast/lib.rs index 29fd3f64d06..e534c286817 100644 --- a/src/ast/lib.rs +++ b/src/ast/lib.rs @@ -17,7 +17,6 @@ //! a real ownership story (likely `bun_core::String` or a `'source` lifetime //! threaded through `Location`/`Data`/`Msg`) is still needed. -#![warn(unreachable_pub)] use core::fmt; use std::borrow::Cow; @@ -84,8 +83,6 @@ pub enum ImportKind { Internal = 11, } -pub type ImportKindLabel = enum_map::EnumMap; - // E0015: EnumMap indexing isn't const; Zig's `comptime brk: { ... }` initializer // is folded into match arms inside label()/error_label() below — same lookup // table, zero runtime init (PORTING.md §Concurrency: prefer no-lock over OnceLock @@ -137,16 +134,6 @@ impl ImportKind { matches!(self, Self::Require | Self::RequireResolve) } - // TODO(port): Zig `jsonStringify` uses the std.json writer protocol; replace - // with a `serde::Serialize` impl or the project's JSON writer trait. For now - // emit the quoted string directly — every tag name is a plain ASCII - // identifier with no chars that need JSON escaping. - pub fn json_stringify(self, writer: &mut W) -> core::fmt::Result { - writer.write_char('"')?; - writer.write_str(<&'static str>::from(self))?; - writer.write_char('"') - } - pub fn is_from_css(self) -> bool { self == Self::AtConditional || self == Self::At @@ -712,28 +699,6 @@ impl Loc { pub fn is_empty(self) -> bool { self.eql(Self::EMPTY) } - - pub fn json_stringify(self, writer: &mut impl JsonWriter) -> Result<(), bun_core::Error> { - // TODO(port): narrow error set - writer.write_i32(self.start) - } -} - -// TODO(port): `writer: anytype` for jsonStringify — the Zig calls -// `writer.write(value)` for arbitrary `value`. Model as a single generic -// `write` until the real serializer exists. -pub trait JsonWriter { - fn write(&mut self, value: &V) -> core::result::Result<(), bun_core::Error>; - - // Legacy specialised entry points (Loc/Range) — default to `write`. - #[inline] - fn write_i32(&mut self, v: i32) -> core::result::Result<(), bun_core::Error> { - self.write(&v) - } - #[inline] - fn write_i32_pair(&mut self, v: [i32; 2]) -> core::result::Result<(), bun_core::Error> { - self.write(&v) - } } // ─────────────────────────────────────────────────────────────────────────── @@ -1539,10 +1504,6 @@ impl Range { // std.math.lossyCast(usize, ...) — saturates negatives to 0. (self.loc.start + self.len).max(0) as usize } - - pub fn json_stringify(self, writer: &mut impl JsonWriter) -> Result<(), bun_core::Error> { - writer.write_i32_pair([self.loc.start, self.len + self.loc.start]) - } } // ─────────────────────────────────────────────────────────────────────────── @@ -3205,7 +3166,7 @@ pub fn source_from_file(path: &bun_core::ZStr, opts: ToSourceOptions) -> bun_sys /// /// MOVE_DOWN from `bun_sys::File::to_source_at`. Zig source: /// `src/sys/File.zig:toSourceAt`. -pub fn source_from_file_at( +pub(crate) fn source_from_file_at( dir_fd: bun_sys::Fd, path: &bun_core::ZStr, opts: ToSourceOptions, @@ -3222,16 +3183,7 @@ pub fn source_from_file_at( Ok(Source::init_path_string_owned(path.as_bytes(), bytes)) } -/// Read `path` (relative to `dir_fd`) into memory and wrap it in a `Source`. -pub fn to_source_at( - dir_fd: bun_sys::Fd, - path: &bun_core::ZStr, - opts: ToSourceOptions, -) -> bun_sys::Result { - source_from_file_at(dir_fd, path, opts) -} - -/// `to_source_at` rooted at the process CWD. +/// `source_from_file_at` rooted at the process CWD. pub fn to_source(path: &bun_core::ZStr, opts: ToSourceOptions) -> bun_sys::Result { source_from_file(path, opts) } @@ -3461,7 +3413,7 @@ pub mod store_ast_alloc_heap { core::ptr::eq(ast_alloc::active_state_id(), STATE_ID.get()) } - pub fn enter() { + pub(crate) fn enter() { if bun_core::getenv_z(bun_core::zstr!("BUN_DISABLE_STORE_AST_HEAP")).is_some() { return; } @@ -3490,7 +3442,7 @@ pub mod store_ast_alloc_heap { ast_alloc::reset_active_state(); } - pub fn exit() { + pub(crate) fn exit() { if STATE_ID.get().is_null() { return; } @@ -3521,11 +3473,11 @@ static DATA_STORE_OVERRIDE: core::cell::Cell<*const bun_alloc::Arena> = core::cell::Cell::new(core::ptr::null()); #[inline] -pub fn data_store_override() -> *const bun_alloc::Arena { +pub(crate) fn data_store_override() -> *const bun_alloc::Arena { DATA_STORE_OVERRIDE.get() } #[inline] -pub fn set_data_store_override(p: *const bun_alloc::Arena) { +pub(crate) fn set_data_store_override(p: *const bun_alloc::Arena) { DATA_STORE_OVERRIDE.set(p); } diff --git a/src/ast/new_store.rs b/src/ast/new_store.rs index 1a064b6d35b..a28ec01048a 100644 --- a/src/ast/new_store.rs +++ b/src/ast/new_store.rs @@ -89,7 +89,7 @@ macro_rules! new_store { // payload is ever introduced. const _: () = assert!(LARGEST_ALIGN <= 16, "NewStore payload type with align>16; bump Block repr(align)"); /// Zig: `pub const size = largest_size * count * 2;` - pub const BLOCK_SIZE: usize = LARGEST_SIZE * $count * 2; + pub(crate) const BLOCK_SIZE: usize = LARGEST_SIZE * $count * 2; #[repr(C, align(16))] pub struct Block { buffer: [MaybeUninit; BLOCK_SIZE], @@ -377,7 +377,7 @@ macro_rules! thread_local_ast_store { // next-lint profiles. All three are `Cell` (no destructor, // const init); matches Zig `threadlocal var`. #[thread_local] - pub static INSTANCE: Cell<*mut Backing> = Cell::new(::core::ptr::null_mut()); + pub(crate) static INSTANCE: Cell<*mut Backing> = Cell::new(::core::ptr::null_mut()); /// Back-reference to the `ASTMemoryAllocator` installed by the /// enclosing `ASTMemoryAllocatorScope` stack frame. Stored as /// `Option` (vs. raw `*mut`) so `append()` can read it via @@ -385,11 +385,11 @@ macro_rules! thread_local_ast_store { /// copy) is upheld by `ASTMemoryAllocatorScope::{enter,exit}`, which /// always restores the previous value before its frame returns. #[thread_local] - pub static MEMORY_ALLOCATOR: Cell< + pub(crate) static MEMORY_ALLOCATOR: Cell< Option<::bun_ptr::BackRef<$crate::ASTMemoryAllocator>>, > = Cell::new(None); #[thread_local] - pub static DISABLE_RESET: Cell = Cell::new(false); + pub(crate) static DISABLE_RESET: Cell = Cell::new(false); #[inline] fn instance() -> *mut Backing { @@ -413,7 +413,7 @@ macro_rules! thread_local_ast_store { .map_or(::core::ptr::null_mut(), ::bun_ptr::BackRef::as_ptr) } #[inline] - pub fn set_memory_allocator(p: *mut $crate::ASTMemoryAllocator) { + pub(crate) fn set_memory_allocator(p: *mut $crate::ASTMemoryAllocator) { MEMORY_ALLOCATOR.set(::core::ptr::NonNull::new(p).map(::bun_ptr::BackRef::from)); } @@ -425,7 +425,7 @@ macro_rules! thread_local_ast_store { } /// create || reset - pub fn begin() { + pub(crate) fn begin() { if !memory_allocator().is_null() { return; } @@ -453,7 +453,7 @@ macro_rules! thread_local_ast_store { /// callers (transpiler, bundler) that want the Store to persist /// across multiple parse calls. #[inline] - pub fn set_disable_reset(b: bool) { + pub(crate) fn set_disable_reset(b: bool) { DISABLE_RESET.set(b); } #[inline] @@ -472,7 +472,7 @@ macro_rules! thread_local_ast_store { } #[inline] - pub fn assert() { + pub(crate) fn assert() { if cfg!(debug_assertions) { if instance().is_null() && memory_allocator().is_null() { unreachable!("Store must be init'd"); diff --git a/src/ast/nodes.rs b/src/ast/nodes.rs index 537a36ffce1..5122c8b0c8e 100644 --- a/src/ast/nodes.rs +++ b/src/ast/nodes.rs @@ -9,7 +9,6 @@ pub use bun_collections::VecExt as _VecExtReexport; use bun_collections::{ArrayHashMap, AutoContext, MultiArrayList, StringHashMap}; use bun_core::Output; -use crate::JsonWriter; use crate::char_freq::CHAR_FREQ_COUNT; use crate::{Binding, E, Expr, Index, Ref, Scope, Stmt, symbol}; @@ -546,16 +545,6 @@ pub enum ImportItemStatus { Missing, } -impl ImportItemStatus { - // TODO(port): narrow error set - pub fn json_stringify( - self, - writer: &mut impl JsonWriter, - ) -> core::result::Result<(), bun_core::Error> { - writer.write(<&'static str>::from(self)) - } -} - #[repr(u8)] // Zig: enum(u2) #[derive(Copy, Clone, PartialEq, Eq, Debug, Default, strum::IntoStaticStr)] #[strum(serialize_all = "snake_case")] @@ -568,16 +557,6 @@ pub enum AssignTarget { Update = 2, } -impl AssignTarget { - // TODO(port): narrow error set - pub fn json_stringify( - self, - writer: &mut impl JsonWriter, - ) -> core::result::Result<(), bun_core::Error> { - writer.write(<&'static str>::from(self)) - } -} - #[derive(Copy, Clone)] pub struct LocRef { pub loc: crate::Loc, @@ -722,16 +701,6 @@ pub enum OptionalChain { Continuation, } -impl OptionalChain { - // TODO(port): narrow error set - pub fn json_stringify( - self, - writer: &mut impl JsonWriter, - ) -> core::result::Result<(), bun_core::Error> { - writer.write(<&'static str>::from(self)) - } -} - pub struct EnumValue { pub loc: crate::Loc, pub ref_: Ref, @@ -918,14 +887,6 @@ impl ExportsKind { ) } - // TODO(port): narrow error set - pub fn json_stringify( - self, - writer: &mut impl JsonWriter, - ) -> core::result::Result<(), bun_core::Error> { - writer.write(<&'static str>::from(self)) - } - // `to_module_type()` lives in `bun_options_types` as // `impl From for ModuleType` (would cycle here). } @@ -1180,16 +1141,6 @@ impl Default for Part { } } -impl Part { - // TODO(port): narrow error set - pub fn json_stringify( - &self, - writer: &mut impl JsonWriter, - ) -> core::result::Result<(), bun_core::Error> { - writer.write(self.stmts.slice()) - } -} - #[derive(Clone, Copy)] pub enum StmtOrExpr { Stmt(Stmt), @@ -1286,16 +1237,6 @@ pub enum StrictModeKind { ImplicitStrictModeClass, } -impl StrictModeKind { - // TODO(port): narrow error set - pub fn json_stringify( - self, - writer: &mut impl JsonWriter, - ) -> core::result::Result<(), bun_core::Error> { - writer.write(<&'static str>::from(self)) - } -} - pub fn printmem(args: fmt::Arguments<'_>) { // `defer Output.flush()` → executes after print; emulate ordering explicitly. Output::init_test(); diff --git a/src/ast/op.rs b/src/ast/op.rs index 650c5e50e82..d8f1cd522ff 100644 --- a/src/ast/op.rs +++ b/src/ast/op.rs @@ -114,14 +114,6 @@ pub enum Code { } impl Code { - // Zig std.json.Stringify hook → write the tag name as a JSON string. - pub fn json_stringify( - self, - writer: &mut W, - ) -> Result<(), bun_core::Error> { - writer.write(<&'static str>::from(self)) - } - pub fn unary_assign_target(code: Code) -> AssignTarget { if (code as u8) >= (Code::UnPreDec as u8) && (code as u8) <= (Code::UnPostInc as u8) { return AssignTarget::Update; @@ -280,15 +272,6 @@ impl Op { is_keyword, } } - - // Zig std.json.Stringify hook → emits `self.text` as a JSON-encoded string - // (quoted + escaped), e.g. `"+"` — not raw bytes. - pub fn json_stringify( - &self, - writer: &mut W, - ) -> Result<(), bun_core::Error> { - writer.write(self.text) - } } // Zig: `pub const TableType: std.EnumArray(Op.Code, Op) = undefined;` diff --git a/src/ast/s.rs b/src/ast/s.rs index 42adb498f14..a8ce4377c39 100644 --- a/src/ast/s.rs +++ b/src/ast/s.rs @@ -291,13 +291,6 @@ pub enum Kind { } impl Kind { - // TODO(port): Zig `jsonStringify` hooks into std.json; wire to whatever - // JSON-serialize trait the AST uses in Rust (serde::Serialize or custom). - pub fn json_stringify(self, writer: &mut impl core::fmt::Write) -> core::fmt::Result { - // TODO(port): narrow error set - writer.write_str(<&'static str>::from(self)) - } - pub fn is_using(self) -> bool { matches!(self, Kind::KUsing | Kind::KAwaitUsing) } diff --git a/src/ast/scope.rs b/src/ast/scope.rs index d904f487836..74672d9f992 100644 --- a/src/ast/scope.rs +++ b/src/ast/scope.rs @@ -1,5 +1,5 @@ use bun_alloc::{AstAlloc, AstVec}; -use bun_collections::{ArrayHashMap, StringHashMap, VecExt}; +use bun_collections::{StringHashMap, VecExt}; use crate::StrictModeKind; use crate::base::Ref; @@ -14,7 +14,7 @@ use crate::ts::TSNamespaceScope; /// lived in the parser arena; the original Rust port placed both on the /// global heap, and since `Scope` itself sits in an arena slot whose `Drop` /// never runs, every member map leaked. -pub type MemberHashMap = StringHashMap; +pub(crate) type MemberHashMap = StringHashMap; // PORT NOTE: Zig `Scope` is a value type — `Ast.module_scope` / `BundledAst.module_scope` // hold it by value and `toAST` / `init` bitwise-copy it (`this.module_scope`). Vec no @@ -90,8 +90,6 @@ impl Default for Scope { } } -pub type NestedScopeMap = ArrayHashMap>>; - impl Scope { // Must agree with `StringHashMap`'s `BuildHasher` (`bun_wyhash::BuildHasher`, // i.e. `BuildHasherDefault`) so the precomputed hash can be @@ -303,12 +301,4 @@ pub enum Kind { ClassStaticInit, } -impl Kind { - // TODO(port): std.json.Stringify protocol — confirm Rust-side json writer trait. - pub fn json_stringify(self, writer: &mut impl core::fmt::Write) -> core::fmt::Result { - // Zig: writer.write(@tagName(self)) — std.json writer wraps strings in quotes. - write!(writer, "\"{}\"", <&'static str>::from(self)) - } -} - // ported from: src/js_parser/ast/Scope.zig diff --git a/src/ast/server_component_boundary.rs b/src/ast/server_component_boundary.rs index 683455c758b..9528108ff2e 100644 --- a/src/ast/server_component_boundary.rs +++ b/src/ast/server_component_boundary.rs @@ -151,7 +151,7 @@ impl<'a> Slice<'a> { // PORT NOTE: Zig stored the full `MultiArrayList.Slice` and called // `.items(.source_index)` on each compare. The Rust `Slice` is not `Copy`, // so we cache just the `source_index` column the adapter actually needs. -pub struct Adapter<'a> { +pub(crate) struct Adapter<'a> { pub source_indices: &'a [IndexInt], } diff --git a/src/ast/stmt.rs b/src/ast/stmt.rs index f0782ebec90..bb1b4aaae0b 100644 --- a/src/ast/stmt.rs +++ b/src/ast/stmt.rs @@ -45,30 +45,7 @@ impl Stmt { } } -// See `binding.rs::Serializable` — JSON-payload carrier passed to the -// shape-agnostic `JsonWriter::write`; fields are the serialization -// contract, not dead, but no reflective writer exists yet to read them. -#[expect(dead_code)] -struct Serializable { - r#type: Tag, - object: &'static [u8], - value: Data, - loc: crate::Loc, -} - impl Stmt { - pub fn json_stringify(&self, writer: &mut W) -> Result<(), bun_core::Error> - where - W: crate::JsonWriter, - { - writer.write(&Serializable { - r#type: self.data.tag(), - object: b"stmt", - value: self.data, - loc: self.loc, - }) - } - pub fn is_type_script(&self) -> bool { matches!(self.data, Data::STypeScript(_)) } @@ -329,14 +306,6 @@ pub enum Tag { } impl Tag { - pub fn json_stringify(self, writer: &mut W) -> Result<(), bun_core::Error> - where - // TODO(port): narrow error set - W: crate::JsonWriter, - { - writer.write(<&'static str>::from(self)) - } - pub fn is_export_like(self) -> bool { matches!( self, diff --git a/src/ast/symbol.rs b/src/ast/symbol.rs index 8218b8f0900..aef56f39de7 100644 --- a/src/ast/symbol.rs +++ b/src/ast/symbol.rs @@ -207,7 +207,7 @@ pub enum SlotNamespace { // Zig: `pub const CountsArray = std.EnumArray(SlotNamespace, u32);` (nested decl). // Inherent associated types are nightly-only; expose as a free alias. -pub type SlotNamespaceCountsArray = enum_map::EnumMap; +pub(crate) type SlotNamespaceCountsArray = enum_map::EnumMap; impl Symbol { /// This is for generating cross-chunk imports and exports for code splitting. @@ -345,17 +345,6 @@ pub enum Kind { } impl Kind { - // TODO(port): Zig std.json.stringify protocol — `writer.write(@tagName(self))` writes a - // JSON string value (with quotes). Verify the Rust JSON writer trait used. - pub fn json_stringify( - self, - writer: &mut W, - ) -> Result<(), bun_core::Error> { - // TODO(port): narrow error set - writer.write_str(<&'static str>::from(self))?; - Ok(()) - } - #[inline] pub fn is_private(self) -> bool { (self as u8) >= (Kind::PrivateField as u8) diff --git a/src/ast_jsc/lib.rs b/src/ast_jsc/lib.rs index b850ca88d75..57b5f9fb7ee 100644 --- a/src/ast_jsc/lib.rs +++ b/src/ast_jsc/lib.rs @@ -4,13 +4,10 @@ use std::borrow::Cow; -use bun_ast::{Data, Level, Location, Log, Metadata, Msg}; +use bun_ast::{Data, Location, Log, Metadata, Msg}; use bun_core::ZigString; -use bun_jsc::{ - self as jsc, BuildMessage, JSGlobalObject, JSValue, JsResult, ResolveMessage, - comptime_string_map_jsc, -}; +use bun_jsc::{self as jsc, BuildMessage, JSGlobalObject, JSValue, JsResult, ResolveMessage}; pub fn msg_from_js(global_object: &JSGlobalObject, file: Vec, err: JSValue) -> JsResult { let mut zig_exception_holder = jsc::zig_exception::Holder::init(); @@ -40,30 +37,13 @@ pub fn msg_from_js(global_object: &JSGlobalObject, file: Vec, err: JSValue) }) } -pub fn msg_to_js(this: Msg, global_object: &JSGlobalObject) -> JsResult { +pub(crate) fn msg_to_js(this: Msg, global_object: &JSGlobalObject) -> JsResult { match this.metadata { Metadata::Build => BuildMessage::create(global_object, this), Metadata::Resolve(_) => ResolveMessage::create(global_object, &this, b""), } } -pub fn level_from_js(global_this: &JSGlobalObject, value: JSValue) -> JsResult> { - if value.is_empty() || value.is_undefined() { - return Ok(None); - } - - if !value.is_string() { - return Err( - global_this.throw_invalid_arguments(format_args!("Expected logLevel to be a string")) - ); - } - - // Zig: `Log.Level.Map.fromJS` — ComptimeStringMap JSC-aware lookup. - // Rust: `Level::MAP` is the `phf::Map`; the `.fromJS` helper lives in - // `bun_jsc::comptime_string_map_jsc`. - comptime_string_map_jsc::from_js(&Level::MAP, global_this, value) -} - pub fn log_to_js(this: &Log, global: &JSGlobalObject, message: &[u8]) -> JsResult { let msgs: &[Msg] = this.msgs.as_slice(); // On-stack array: conservative GC stack scan keeps these JSValues alive (see PORTING.md §JSC). diff --git a/src/base64/lib.rs b/src/base64/lib.rs index d3ba74852f5..a70d815e15d 100644 --- a/src/base64/lib.rs +++ b/src/base64/lib.rs @@ -1,4 +1,3 @@ -#![warn(unreachable_pub)] use bun_simdutf_sys::simdutf::{self, SIMDUTFResult}; pub use zig_base64::STANDARD_ALPHABET_CHARS; @@ -79,7 +78,7 @@ pub fn encode_alloc(source: &[u8]) -> Vec { destination } -pub fn simdutf_encode_len_url_safe(source_len: usize) -> usize { +pub(crate) fn simdutf_encode_len_url_safe(source_len: usize) -> usize { simdutf::base64::encode_len(source_len, true) } @@ -89,7 +88,7 @@ pub fn simdutf_encode_len_url_safe(source_len: usize) -> usize { /// * `-` and `_` are used instead of `+` and `/` /// /// See the documentation for simdutf's `binary_to_base64` function for more details (simdutf_impl.h). -pub fn simdutf_encode_url_safe(destination: &mut [u8], source: &[u8]) -> usize { +pub(crate) fn simdutf_encode_url_safe(destination: &mut [u8], source: &[u8]) -> usize { simdutf::base64::encode(source, destination, true) } @@ -135,7 +134,7 @@ pub const fn encode_len_from_size(source: usize) -> usize { } #[inline] -pub const fn url_safe_encode_len_from_size(n: usize) -> usize { +pub(crate) const fn url_safe_encode_len_from_size(n: usize) -> usize { // Equivalent to WebKit's `ceil(n * 4 / 3)`, but split so the intermediate // product can't overflow before the divide for large `n`. let full_chunks = n / 3; @@ -195,7 +194,7 @@ pub mod vlq { } } - pub const VLQ_MAX_IN_BYTES: usize = 7; + pub(crate) const VLQ_MAX_IN_BYTES: usize = 7; impl VLQ { #[inline] @@ -383,7 +382,7 @@ pub mod zig_base64 { } bun_core::named_error_set!(Error); - pub type DecoderWithIgnoreProto = fn(ignore: &[u8]) -> Base64DecoderWithIgnore; + pub(crate) type DecoderWithIgnoreProto = fn(ignore: &[u8]) -> Base64DecoderWithIgnore; /// Base64 codecs pub struct Codecs { @@ -397,7 +396,9 @@ pub mod zig_base64 { pub const STANDARD_ALPHABET_CHARS: [u8; 64] = *b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - pub const fn standard_base64_decoder_with_ignore(ignore: &[u8]) -> Base64DecoderWithIgnore { + pub(crate) const fn standard_base64_decoder_with_ignore( + ignore: &[u8], + ) -> Base64DecoderWithIgnore { Base64DecoderWithIgnore::init(STANDARD_ALPHABET_CHARS, Some(b'='), ignore) } @@ -420,38 +421,9 @@ pub mod zig_base64 { decoder: Base64Decoder::init(STANDARD_ALPHABET_CHARS, None), }; - pub const URL_SAFE_ALPHABET_CHARS: [u8; 64] = + pub(crate) const URL_SAFE_ALPHABET_CHARS: [u8; 64] = *b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; - /// Shared by both [`URL_SAFE`] and [`URL_SAFE_NO_PAD`] (mirrors the `.zig` - /// sibling). It always builds a *padded* decoder, so for `URL_SAFE_NO_PAD` - /// it does NOT match the codec's `pad_char` — feed it padded input. - pub const fn url_safe_base64_decoder_with_ignore(ignore: &[u8]) -> Base64DecoderWithIgnore { - Base64DecoderWithIgnore::init(URL_SAFE_ALPHABET_CHARS, Some(b'='), ignore) - } - - /// URL-safe Base64 codecs, with padding - pub static URL_SAFE: Codecs = Codecs { - alphabet_chars: URL_SAFE_ALPHABET_CHARS, - pad_char: Some(b'='), - decoder_with_ignore: url_safe_base64_decoder_with_ignore, - encoder: Base64Encoder::init(URL_SAFE_ALPHABET_CHARS, Some(b'=')), - decoder: Base64Decoder::init(URL_SAFE_ALPHABET_CHARS, Some(b'=')), - }; - - /// URL-safe Base64 codecs, without padding. - /// - /// Note: `decoder_with_ignore` here is the *padded* decoder (see comment on - /// [`url_safe_base64_decoder_with_ignore`]) — it does not match this codec's - /// `pad_char`. Use `decoder` for unpadded input. - pub static URL_SAFE_NO_PAD: Codecs = Codecs { - alphabet_chars: URL_SAFE_ALPHABET_CHARS, - pad_char: None, - decoder_with_ignore: url_safe_base64_decoder_with_ignore, - encoder: Base64Encoder::init(URL_SAFE_ALPHABET_CHARS, None), - decoder: Base64Decoder::init(URL_SAFE_ALPHABET_CHARS, None), - }; - // PORT NOTE: dropped `standard_pad_char`/`standard_encoder`/`standard_decoder` // @compileError deprecation stubs — no Rust equivalent for use-site compile errors. @@ -667,7 +639,7 @@ pub mod zig_base64 { } impl Base64DecoderWithIgnore { - pub const fn init( + pub(crate) const fn init( alphabet_chars: [u8; 64], pad_char: Option, ignore_chars: &[u8], @@ -693,22 +665,11 @@ pub mod zig_base64 { result } - /// Return the maximum possible decoded size for a given input length - The actual length may be less if the input includes padding - /// `InvalidPadding` is returned if the input length is not valid. - pub fn calc_size_upper_bound(&self, source_len: usize) -> usize { - let mut result = source_len / 4 * 3; - if self.decoder.pad_char.is_none() { - let leftover = source_len % 4; - result += leftover * 3 / 4; - } - result - } - /// Invalid characters that are not ignored result in Error::InvalidCharacter. /// Invalid padding results in Error::InvalidPadding. /// Decoding more data than can fit in dest results in Error::NoSpaceLeft. See also ::calc_size_upper_bound. /// Returns the number of bytes written to dest. - pub fn decode( + pub(crate) fn decode( &self, dest: &mut [u8], source: &[u8], @@ -873,90 +834,6 @@ pub mod zig_base64 { test_no_space_left_error(codecs, b"AAAAAA=="); } - #[test] - fn test_base64_url_safe_no_pad() { - let codecs = &URL_SAFE_NO_PAD; - - // `URL_SAFE_NO_PAD.decoder_with_ignore` is the *padded* decoder - // (the field is shared with `URL_SAFE` — see the comment on - // `url_safe_base64_decoder_with_ignore`), so the third parameter - // is what *that* decoder accepts, not what `encoder` produces. - test_all_apis(codecs, b"", b"", b""); - test_all_apis(codecs, b"f", b"Zg", b"Zg=="); - test_all_apis(codecs, b"fo", b"Zm8", b"Zm8="); - test_all_apis(codecs, b"foo", b"Zm9v", b"Zm9v"); - test_all_apis(codecs, b"foob", b"Zm9vYg", b"Zm9vYg=="); - test_all_apis(codecs, b"fooba", b"Zm9vYmE", b"Zm9vYmE="); - test_all_apis(codecs, b"foobar", b"Zm9vYmFy", b"Zm9vYmFy"); - - test_decode_ignore_space(codecs, b"", b" "); - test_decode_ignore_space(codecs, b"f", b"Z g= ="); - test_decode_ignore_space(codecs, b"fo", b" Zm8="); - test_decode_ignore_space(codecs, b"foo", b"Zm9v "); - test_decode_ignore_space(codecs, b"foob", b"Zm9vYg = = "); - test_decode_ignore_space(codecs, b"fooba", b"Zm9v YmE="); - test_decode_ignore_space(codecs, b"foobar", b" Z m 9 v Y m F y "); - - // `codecs.decoder` (pad_char: None) and the padded - // `decoder_with_ignore` classify `=`-containing inputs differently: - // - // - `decoder` treats `=` as `InvalidCharacter` (not in the - // unpadded alphabet at all). - // - `decoder_with_ignore` treats `=` as padding; mismatched - // padding is `InvalidPadding`, and well-formed padding (e.g. - // `b"AAA="`) decodes successfully. - // - // Inputs without `=` produce the same error for both. - test_error( - codecs, - b"A", - Error::InvalidPadding, - Some(Error::InvalidPadding), - ); - test_error(codecs, b"AAA=", Error::InvalidCharacter, None); - test_error( - codecs, - b"A..A", - Error::InvalidCharacter, - Some(Error::InvalidCharacter), - ); - test_error( - codecs, - b"AA=A", - Error::InvalidCharacter, - Some(Error::InvalidPadding), - ); - test_error( - codecs, - b"AA/=", - Error::InvalidCharacter, - Some(Error::InvalidCharacter), - ); - test_error( - codecs, - b"A/==", - Error::InvalidCharacter, - Some(Error::InvalidCharacter), - ); - test_error( - codecs, - b"A===", - Error::InvalidCharacter, - Some(Error::InvalidPadding), - ); - test_error( - codecs, - b"====", - Error::InvalidCharacter, - Some(Error::InvalidPadding), - ); - - test_no_space_left_error(codecs, b"AA"); - test_no_space_left_error(codecs, b"AAA"); - test_no_space_left_error(codecs, b"AAAA"); - test_no_space_left_error(codecs, b"AAAAAA"); - } - /// `expected_with_ignore` is the input for `Base64DecoderWithIgnore`, /// which may differ from `expected_encoded` when the codec's /// `decoder_with_ignore` doesn't share its `pad_char` (URL-safe family). @@ -989,9 +866,7 @@ pub mod zig_base64 { { let decoder_ignore_nothing = (codecs.decoder_with_ignore)(b""); let mut buffer = [0u8; 0x100]; - let upper = - decoder_ignore_nothing.calc_size_upper_bound(expected_with_ignore.len()); - let decoded = &mut buffer[0..upper]; + let decoded = &mut buffer[..]; let mut written: usize = 0; decoder_ignore_nothing .decode(decoded, expected_with_ignore, &mut written) @@ -1004,8 +879,7 @@ pub mod zig_base64 { fn test_decode_ignore_space(codecs: &Codecs, expected_decoded: &[u8], encoded: &[u8]) { let decoder_ignore_space = (codecs.decoder_with_ignore)(b" "); let mut buffer = [0u8; 0x100]; - let upper = decoder_ignore_space.calc_size_upper_bound(encoded.len()); - let decoded = &mut buffer[0..upper]; + let decoded = &mut buffer[..]; let mut written: usize = 0; decoder_ignore_space .decode(decoded, encoded, &mut written) diff --git a/src/boringssl/lib.rs b/src/boringssl/lib.rs index e999978f4f5..60c17a526ce 100644 --- a/src/boringssl/lib.rs +++ b/src/boringssl/lib.rs @@ -2,7 +2,6 @@ // the translated file can be provided by `zig translate-c` #![warn(unused_must_use)] -#![warn(unreachable_pub)] use core::ffi::{c_int, c_void}; use core::ptr; use std::cell::Cell; diff --git a/src/boringssl_sys/boringssl.rs b/src/boringssl_sys/boringssl.rs index 8848d8630be..ffa1a3ef806 100644 --- a/src/boringssl_sys/boringssl.rs +++ b/src/boringssl_sys/boringssl.rs @@ -38,16 +38,9 @@ pub const NID_commonName: c_int = 13; /// `#define NID_subject_alt_name 85` pub const NID_subject_alt_name: c_int = 85; -// GENERAL_NAME.type discriminants (`openssl/x509v3.h`). -pub const GEN_OTHERNAME: c_int = 0; -pub const GEN_EMAIL: c_int = 1; pub const GEN_DNS: c_int = 2; -pub const GEN_X400: c_int = 3; -pub const GEN_DIRNAME: c_int = 4; -pub const GEN_EDIPARTY: c_int = 5; pub const GEN_URI: c_int = 6; pub const GEN_IPADD: c_int = 7; -pub const GEN_RID: c_int = 8; // ═══════════════════════════════════════════════════════════════════════════ // ASN.1 string types @@ -63,9 +56,9 @@ pub struct asn1_string_st { pub flags: c_long, } -pub type ASN1_STRING = asn1_string_st; +pub(crate) type ASN1_STRING = asn1_string_st; pub type ASN1_OCTET_STRING = asn1_string_st; -pub type ASN1_IA5STRING = asn1_string_st; +pub(crate) type ASN1_IA5STRING = asn1_string_st; // ═══════════════════════════════════════════════════════════════════════════ // Opaque handles @@ -274,15 +267,15 @@ pub struct GENERAL_NAME { // OPENSSL_STACK low-level ABI (used by the typed `sk_*` inline wrappers) // ═══════════════════════════════════════════════════════════════════════════ -pub type OPENSSL_sk_free_func = Option; -pub type OPENSSL_sk_call_free_func = +pub(crate) type OPENSSL_sk_free_func = Option; +pub(crate) type OPENSSL_sk_call_free_func = Option; -pub type OPENSSL_sk_cmp_func = +pub(crate) type OPENSSL_sk_cmp_func = Option c_int>; /// `struct stack_st` / `OPENSSL_STACK`. #[repr(C)] -pub struct OPENSSL_STACK { +pub(crate) struct OPENSSL_STACK { pub num: usize, pub data: *mut *mut c_void, pub sorted: c_int, @@ -309,7 +302,7 @@ unsafe extern "C" { // ── crypto / err ────────────────────────────────────────────────────── // No-arg init calls — no preconditions, idempotent. pub safe fn CRYPTO_library_init(); - pub fn CRYPTO_memcmp(a: *const c_void, b: *const c_void, len: usize) -> c_int; + pub(crate) fn CRYPTO_memcmp(a: *const c_void, b: *const c_void, len: usize) -> c_int; pub fn ERR_error_string_n(packed_error: u32, buf: *mut c_char, len: usize) -> *mut c_char; pub safe fn ERR_load_BIO_strings(); pub safe fn OpenSSL_add_all_algorithms(); @@ -452,7 +445,7 @@ unsafe extern "C" { /// Per-stack free callback type used by `sk_GENERAL_NAME_pop_free` /// (matches Zig's `stack_GENERAL_NAME_free_func`). -pub type sk_GENERAL_NAME_free_func = unsafe extern "C" fn(*mut struct_stack_st_GENERAL_NAME); +pub(crate) type sk_GENERAL_NAME_free_func = unsafe extern "C" fn(*mut struct_stack_st_GENERAL_NAME); #[inline] pub unsafe fn sk_X509_value(sk: *const struct_stack_st_X509, i: usize) -> *mut X509 { @@ -536,15 +529,11 @@ pub unsafe fn sk_GENERAL_NAME_pop_free( // (`vendor/boringssl/include/openssl/ssl.h`) // ═══════════════════════════════════════════════════════════════════════════ -pub const SSL_ERROR_NONE: c_int = 0; pub const SSL_ERROR_SSL: c_int = 1; pub const SSL_ERROR_WANT_READ: c_int = 2; pub const SSL_ERROR_WANT_WRITE: c_int = 3; -pub const SSL_ERROR_WANT_X509_LOOKUP: c_int = 4; pub const SSL_ERROR_SYSCALL: c_int = 5; pub const SSL_ERROR_ZERO_RETURN: c_int = 6; -pub const SSL_ERROR_WANT_CONNECT: c_int = 7; -pub const SSL_ERROR_WANT_ACCEPT: c_int = 8; pub const SSL_ERROR_WANT_RENEGOTIATE: c_int = 19; pub const SSL_VERIFY_NONE: c_int = 0x00; @@ -552,24 +541,17 @@ pub const SSL_VERIFY_PEER: c_int = 0x01; pub const SSL_VERIFY_FAIL_IF_NO_PEER_CERT: c_int = 0x02; pub const SSL_VERIFY_PEER_IF_NO_OBC: c_int = 0x04; -pub const SSL_SENT_SHUTDOWN: c_int = 1; pub const SSL_RECEIVED_SHUTDOWN: c_int = 2; pub const SSL_TLSEXT_ERR_OK: c_int = 0; -pub const SSL_TLSEXT_ERR_ALERT_WARNING: c_int = 1; pub const SSL_TLSEXT_ERR_ALERT_FATAL: c_int = 2; pub const SSL_TLSEXT_ERR_NOACK: c_int = 3; -pub const OPENSSL_NPN_UNSUPPORTED: c_int = 0; pub const OPENSSL_NPN_NEGOTIATED: c_int = 1; -pub const OPENSSL_NPN_NO_OVERLAP: c_int = 2; /// `enum ssl_renegotiate_mode_t` — passed to `SSL_set_renegotiate_mode`. pub type ssl_renegotiate_mode_t = c_uint; pub const ssl_renegotiate_never: ssl_renegotiate_mode_t = 0; -pub const ssl_renegotiate_once: ssl_renegotiate_mode_t = 1; -pub const ssl_renegotiate_freely: ssl_renegotiate_mode_t = 2; -pub const ssl_renegotiate_ignore: ssl_renegotiate_mode_t = 3; pub const ssl_renegotiate_explicit: ssl_renegotiate_mode_t = 4; /// `SSL_OP_LEGACY_SERVER_CONNECT` — BoringSSL defines this as 0 (no-op flag); @@ -585,14 +567,14 @@ pub const RSA_PKCS1_OAEP_PADDING: c_int = 4; // ═══════════════════════════════════════════════════════════════════════════ /// `CRYPTO_refcount_t` (`openssl/thread.h`) — atomic-ish u32 in BoringSSL. -pub type CRYPTO_refcount_t = u32; +pub(crate) type CRYPTO_refcount_t = u32; /// `ossl_ssize_t` — signed counterpart of `size_t` for BoringSSL "length or -1" /// parameters. Mirrors the `isize` definition in `boringssl.zig`. -pub type ossl_ssize_t = isize; +pub(crate) type ossl_ssize_t = isize; /// `bio_info_cb` — callback type for `BIO_METHOD.callback_ctrl`. -pub type bio_info_cb = +pub(crate) type bio_info_cb = Option c_long>; /// `struct bio_method_st` — vtable for a BIO implementation. Laid out by-value @@ -656,7 +638,8 @@ opaque!( pub type SSL_verify_cb = Option c_int>; /// `int pem_password_cb(char *buf, int size, int rwflag, void *userdata)`. -pub type pem_password_cb = unsafe extern "C" fn(*mut c_char, c_int, c_int, *mut c_void) -> c_int; +pub(crate) type pem_password_cb = + unsafe extern "C" fn(*mut c_char, c_int, c_int, *mut c_void) -> c_int; // ═══════════════════════════════════════════════════════════════════════════ // Extern functions — SSL / BIO / ERR / HMAC / RSA / PBKDF2 diff --git a/src/brotli/lib.rs b/src/brotli/lib.rs index 249d90422f5..01c9b0c73f3 100644 --- a/src/brotli/lib.rs +++ b/src/brotli/lib.rs @@ -1,4 +1,3 @@ -#![warn(unreachable_pub)] use core::ptr; pub use bun_brotli_sys::brotli_c as c; diff --git a/src/brotli_sys/brotli_c.rs b/src/brotli_sys/brotli_c.rs index 81d09b61275..a8c78320334 100644 --- a/src/brotli_sys/brotli_c.rs +++ b/src/brotli_sys/brotli_c.rs @@ -79,15 +79,6 @@ impl BrotliDecoder { BrotliDecoderSetParameter(state, param as c_uint, value) > 0 } - pub fn attach_dictionary( - state: &mut BrotliDecoder, - type_: BrotliSharedDictionaryType, - data: &[u8], - ) -> c_int { - // SAFETY: state is a valid &mut BrotliDecoder; data.ptr/len are a valid slice - unsafe { BrotliDecoderAttachDictionary(state, type_, data.len(), data.as_ptr()) } - } - /// # Safety /// `opaque` is forwarded to brotli's allocator hooks; it must be valid for /// every `alloc_func`/`free_func` invocation for the lifetime of the @@ -421,10 +412,6 @@ impl BrotliEncoder { unsafe { BrotliEncoderDestroyInstance(state) } } - pub fn has_more_output(state: &mut BrotliEncoder) -> bool { - BrotliEncoderHasMoreOutput(state) > 0 - } - pub fn take_output(state: &mut BrotliEncoder) -> &[u8] { let mut size: usize = 0; let ptr = BrotliEncoderTakeOutput(state, &mut size); diff --git a/src/bun_alloc/MimallocArena.rs b/src/bun_alloc/MimallocArena.rs index ae0def01ca7..2b0b1795e1d 100644 --- a/src/bun_alloc/MimallocArena.rs +++ b/src/bun_alloc/MimallocArena.rs @@ -31,31 +31,14 @@ use crate::mimalloc; // // Tracks `mi_heap_new`/`mi_heap_destroy` calls so leak tests can assert the // live-heap count is bounded. Gated on `debug_assertions` (zero cost in -// release). The runtime exposes `bun_alloc::live_arena_heaps()` for ad-hoc -// probes; nothing reads these counters in production. +// release); nothing reads these counters in production. #[cfg(debug_assertions)] -pub static HEAP_NEW_COUNT: core::sync::atomic::AtomicUsize = +pub(crate) static HEAP_NEW_COUNT: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0); #[cfg(debug_assertions)] -pub static HEAP_DESTROY_COUNT: core::sync::atomic::AtomicUsize = +pub(crate) static HEAP_DESTROY_COUNT: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0); -/// Debug-only: number of live `MimallocArena` heaps (`mi_heap_new` minus -/// `mi_heap_destroy`). Returns 0 in release builds. -#[inline] -pub fn live_arena_heaps() -> usize { - #[cfg(debug_assertions)] - { - HEAP_NEW_COUNT - .load(core::sync::atomic::Ordering::Relaxed) - .saturating_sub(HEAP_DESTROY_COUNT.load(core::sync::atomic::Ordering::Relaxed)) - } - #[cfg(not(debug_assertions))] - { - 0 - } -} - // ── Debug-only thread-ownership guard (Zig: `bun.safety.ThreadLock`) ────── // // `bun_alloc` sits below `bun_core` in the crate graph, so we cannot reuse @@ -765,7 +748,7 @@ unsafe fn vtable_free(_ctx: *mut c_void, buf: &mut [u8], a: crate::Alignment, _r /// Zig: `heap_allocator_vtable` — per-arena thunks; `ctx` is the /// `*const MimallocArena` stashed by `std_allocator()`. -pub static HEAP_ALLOCATOR_VTABLE: crate::AllocatorVTable = crate::AllocatorVTable { +pub(crate) static HEAP_ALLOCATOR_VTABLE: crate::AllocatorVTable = crate::AllocatorVTable { alloc: vtable_alloc, resize: vtable_resize, remap: vtable_remap, @@ -786,7 +769,7 @@ unsafe fn global_vtable_alloc( } /// Zig: `global_mimalloc_vtable`. -pub static GLOBAL_MIMALLOC_VTABLE: crate::AllocatorVTable = crate::AllocatorVTable { +pub(crate) static GLOBAL_MIMALLOC_VTABLE: crate::AllocatorVTable = crate::AllocatorVTable { alloc: global_vtable_alloc, resize: crate::basic::MimallocAllocator::resize_with_default_allocator, remap: crate::basic::MimallocAllocator::remap_with_default_allocator, diff --git a/src/bun_alloc/basic.rs b/src/bun_alloc/basic.rs index b28c8a940ad..c1fe95e397d 100644 --- a/src/bun_alloc/basic.rs +++ b/src/bun_alloc/basic.rs @@ -181,10 +181,10 @@ pub(crate) mod memory_allocator_tags { use core::ffi::c_void; const DEFAULT_ALLOCATOR_TAG: usize = 0xBEEFA110C; // "BEEFA110C" beef a110c i guess - pub const DEFAULT_ALLOCATOR_TAG_PTR: *mut c_void = DEFAULT_ALLOCATOR_TAG as *mut c_void; + pub(crate) const DEFAULT_ALLOCATOR_TAG_PTR: *mut c_void = DEFAULT_ALLOCATOR_TAG as *mut c_void; const Z_ALLOCATOR_TAG: usize = 0x2a11043470123; // "z4110c4701" (Z ALLOCATOR in 1337 speak) - pub const Z_ALLOCATOR_TAG_PTR: *mut c_void = Z_ALLOCATOR_TAG as *mut c_void; + pub(crate) const Z_ALLOCATOR_TAG_PTR: *mut c_void = Z_ALLOCATOR_TAG as *mut c_void; } pub static Z_ALLOCATOR: StdAllocator = StdAllocator { diff --git a/src/bun_alloc/heap_breakdown.rs b/src/bun_alloc/heap_breakdown.rs index f93c4101428..36a0784559c 100644 --- a/src/bun_alloc/heap_breakdown.rs +++ b/src/bun_alloc/heap_breakdown.rs @@ -11,61 +11,6 @@ type vm_size_t = usize; // TODO(port): `enable_asan` mapped to a cargo feature; verify the build wires this the same way. pub const ENABLED: bool = cfg!(debug_assertions) && cfg!(target_os = "macos") && !cfg!(bun_asan); -/// Zig: `fn heapLabel(comptime T: type) [:0]const u8` -/// -/// Uses `@hasDecl(T, "heap_label")` to optionally pick a custom label, else -/// `bun.meta.typeBaseName(@typeName(T))`. In Rust this is a trait with a -/// blanket default; types override by implementing `HEAP_LABEL` explicitly. -pub trait HeapLabel { - const HEAP_LABEL: &'static str; -} - -// TODO(port): blanket impl wants `bun.meta.typeBaseName(@typeName(T))` at compile -// time. `core::any::type_name::()` is not `const fn` and includes the full -// module path. Either a proc-macro derive, or require every `T` used -// with heap_breakdown to impl `HeapLabel` explicitly. -fn heap_label() -> &'static str { - T::HEAP_LABEL -} - -/// Zig: `pub fn allocator(comptime T: type) std.mem.Allocator` -pub fn allocator() -> &'static dyn crate::Allocator { - named_allocator(heap_label::()) -} - -/// Zig: `pub fn namedAllocator(comptime name: [:0]const u8) std.mem.Allocator` -/// -/// In Zig the `"Bun__" ++ name` concatenation and the per-name `static` happen -/// at comptime via monomorphization. Rust cannot monomorphize on a `&'static str` -/// const generic on stable, so the per-name `OnceLock` must be minted at the -/// call site — see the `get_zone!` macro below. This function is a thin wrapper -/// that defers to that macro at call sites; here we expose the runtime half. -pub fn named_allocator(name: &'static str) -> &'static dyn crate::Allocator { - // TODO(port): callers should prefer `named_allocator!("Name")` / `get_zone!` directly - // so the OnceLock is per-name. This runtime path falls back to a process-global - // map and is not zero-cost like the Zig comptime version. - // PERF(port): was comptime monomorphization — profile if hot. - // - // Zig: `getZone("Bun__" ++ name)` — the "Bun__" prefix is applied HERE, not in - // `getZone`/`get_zone_runtime`. PORTING.md §Forbidden: no `Box::leak` for - // 'static — `get_zone_runtime` owns the prefixed string in its OnceLock map, - // so pass a borrowed `&str` and let the map intern it. - let mut prefixed = String::with_capacity(5 + name.len()); - prefixed.push_str("Bun__"); - prefixed.push_str(name); - get_zone(prefixed.as_bytes()).allocator() -} - -// Comptime-literal form of `named_allocator` lives at crate root as `get_zone!` -// (see lib.rs). A local `macro_rules! named_allocator` re-export would collide -// with the `pub fn named_allocator` above in the value namespace on macOS where -// this module is actually compiled, so it is omitted here. - -/// Zig: `pub fn getZoneT(comptime T: type) *Zone` -pub fn get_zone_t() -> &'static Zone { - get_zone(heap_label::().as_bytes()) -} - /// Zig: `pub fn getZone(comptime name: [:0]const u8) *Zone` /// /// Each comptime instantiation in Zig gets its own `static var zone` + `std.once`. @@ -73,13 +18,9 @@ pub fn get_zone_t() -> &'static Zone { /// that expands a fresh `OnceLock` per call site (per literal name). Not /// duplicated here to avoid path-export collisions on macOS. -/// Runtime `getZone(name)` — looks up (or creates) the per-name zone. -/// -/// Zig used a comptime-monomorphized `static` per literal; the crate-root +/// Runtime `getZone(name)` — looks up (or creates) the per-name zone. The /// `get_zone!` macro is the zero-cost form. This runtime path keys a -/// process-global map for callers that pass a non-literal name (or for -/// `allocator()`/`get_zone_t()`, which cannot expand a per-T static on -/// stable Rust without a proc-macro). +/// process-global map for callers that pass a non-literal name. // TODO(port): could be replaced with a `#[heap_label]` derive that expands // `get_zone!` directly. #[allow(clippy::assertions_on_constants)] @@ -283,20 +224,28 @@ unsafe extern "C" { /// No preconditions; returns the process default malloc zone. pub safe fn malloc_default_zone() -> *mut Zone; /// No preconditions; allocates a new zone (process-lifetime). - pub safe fn malloc_create_zone(start_size: vm_size_t, flags: c_uint) -> *mut Zone; + pub(crate) safe fn malloc_create_zone(start_size: vm_size_t, flags: c_uint) -> *mut Zone; pub fn malloc_destroy_zone(zone: *mut Zone); // `&Zone` is ABI-identical to libmalloc's `malloc_zone_t *` (thin non-null // pointer to an `opaque_ffi!` `!Freeze` struct — interior mutation by C is // sound). The reference type encodes the only pointer-validity precondition, // so `safe fn` discharges the link-time proof for the pure-allocation entry // points (alloc/calloc/valloc/memalign return null on failure). - pub safe fn malloc_zone_malloc(zone: &Zone, size: usize) -> *mut c_void; - pub safe fn malloc_zone_calloc(zone: &Zone, num_items: usize, size: usize) -> *mut c_void; + pub(crate) safe fn malloc_zone_malloc(zone: &Zone, size: usize) -> *mut c_void; + pub(crate) safe fn malloc_zone_calloc( + zone: &Zone, + num_items: usize, + size: usize, + ) -> *mut c_void; pub safe fn malloc_zone_valloc(zone: &Zone, size: usize) -> *mut c_void; pub fn malloc_zone_free(zone: *mut Zone, ptr: *mut c_void); pub fn malloc_zone_realloc(zone: *mut Zone, ptr: *mut c_void, size: usize) -> *mut c_void; pub fn malloc_zone_from_ptr(ptr: *const c_void) -> *mut Zone; - pub safe fn malloc_zone_memalign(zone: &Zone, alignment: usize, size: usize) -> *mut c_void; + pub(crate) safe fn malloc_zone_memalign( + zone: &Zone, + alignment: usize, + size: usize, + ) -> *mut c_void; pub fn malloc_zone_batch_malloc( zone: *mut Zone, size: usize, @@ -310,7 +259,7 @@ unsafe extern "C" { pub fn malloc_make_nonpurgeable(ptr: *mut c_void) -> c_int; pub fn malloc_zone_register(zone: *mut Zone); pub fn malloc_zone_unregister(zone: *mut Zone); - pub fn malloc_set_zone_name(zone: *mut Zone, name: *const c_char); + pub(crate) fn malloc_set_zone_name(zone: *mut Zone, name: *const c_char); pub fn malloc_get_zone_name(zone: *mut Zone) -> *const c_char; pub fn malloc_zone_pressure_relief(zone: *mut Zone, goal: usize) -> usize; } @@ -330,7 +279,7 @@ mod stubs { pub unsafe fn malloc_zone_free(_: *mut Zone, _: *mut c_void) { unreachable!() } - pub fn malloc_zone_memalign(_: &Zone, _: usize, _: usize) -> *mut c_void { + pub(crate) fn malloc_zone_memalign(_: &Zone, _: usize, _: usize) -> *mut c_void { unreachable!() } } diff --git a/src/bun_alloc/lib.rs b/src/bun_alloc/lib.rs index a4266a412b9..9b7a3d9f82f 100644 --- a/src/bun_alloc/lib.rs +++ b/src/bun_alloc/lib.rs @@ -99,7 +99,7 @@ impl AllocatorVTable { /// Build a "free-only" vtable: `alloc`/`resize`/`remap` all no-op/fail and /// only `free` is meaningful. Each call site still gets its own `static` - /// (vtable address is an identity tag for `is_instance`/`allocator_has_pointer`). + /// (vtable address is an identity tag for `is_instance`). pub const fn free_only( free: unsafe fn(*mut core::ffi::c_void, &mut [u8], Alignment, usize), ) -> Self { @@ -278,7 +278,7 @@ pub use baby_vec::BabyVec; /// through `<&MimallocArena as Allocator>` (= `mi_heap_realloc_aligned` / /// `mi_free`); reclaimed on arena `reset`/`Drop`. pub type ArenaVec<'a, T> = BabyVec<'a, T>; -pub use mimalloc_arena::{ArenaString, ArenaVecExt, live_arena_heaps}; +pub use mimalloc_arena::{ArenaString, ArenaVecExt}; /// `bumpalo::collections::Vec::from_iter_in` parity for [`ArenaVec`]. #[inline] diff --git a/src/bun_alloc/maybe_owned.rs b/src/bun_alloc/maybe_owned.rs index 005e6d521d5..55833c14262 100644 --- a/src/bun_alloc/maybe_owned.rs +++ b/src/bun_alloc/maybe_owned.rs @@ -27,7 +27,7 @@ pub struct MaybeOwned { // Zig: `pub const Borrowed = MaybeOwned(BorrowedParent);` // Rust has no stable inherent associated types, so expose as a free alias. // `Borrowed` collapsed to `()` — borrows carry no allocator state. -pub type MaybeOwnedBorrowed = MaybeOwned<()>; +pub(crate) type MaybeOwnedBorrowed = MaybeOwned<()>; impl MaybeOwned { /// Creates a `MaybeOwned` allocator that owns memory. diff --git a/src/bun_alloc/memory.rs b/src/bun_alloc/memory.rs index 928c1ba0d1e..717efa9058a 100644 --- a/src/bun_alloc/memory.rs +++ b/src/bun_alloc/memory.rs @@ -1,33 +1,5 @@ //! Basic utilities for working with memory and objects. -use crate::AllocError; - -/// Allocates memory for a value of type `T` and initializes the memory with `value`. -/// -/// In Zig this routed through `bun.tryNew` for extra assertions when `allocator` was -/// `bun.default_allocator`. In Rust the global allocator *is* mimalloc (via -/// `#[global_allocator]`), so the default-vs-custom branch collapses and this is -/// `Box::new`. -// PORT NOTE: `std.mem.Allocator param` param deleted per §Allocators (non-AST -// crate). The `Environment.allow_assert && isDefault(allocator)` branch is gone with it. -#[inline] -pub fn create(value: T) -> Result, AllocError> { - // PERF(port): Zig `allocator.create` is fallible; Rust `Box::new` aborts on OOM. - // If fallible allocation is required, swap to `Box::try_new` (nightly - // `allocator_api`) or a manual `alloc::alloc` + `ptr::write` pair. - Ok(Box::new(value)) -} - -/// Frees memory previously allocated by `create`. -/// -/// The memory must have been allocated by the `create` function in this namespace. -// PORT NOTE: `allocator` param deleted. In Rust, `Box` drops at scope exit, so -// most call sites should delete the `destroy` call entirely rather than invoke this. -#[inline] -pub fn destroy(ptr: Box) { - drop(ptr); -} - /// Default-initializes a value of type `T`. /// /// Zig tried, in order: `T.initDefault()`, then `T.init()`, then `.{}`. All three @@ -106,24 +78,4 @@ pub unsafe fn rebase_slice<'a>(slice: &[u8], old_base: *const u8, new_base: *con unsafe { core::slice::from_raw_parts(new_base.add(offset), slice.len()) } } -/// Removes the trailing sentinel from an owned sentinel-terminated buffer, returning -/// a plain owned slice that can be freed normally. -/// -/// Most allocators perform this without allocating new memory, but unlike a raw cast -/// this will not break allocators that need the exact allocation size to free. -/// -/// In Zig this was generic over `[:x]T` / `[*:x]T` via `@typeInfo`. Rust has no -/// sentinel-carrying slice type in the type system, so this is specialized to the -/// overwhelmingly common case: NUL-terminated bytes (`[:0]u8`). -// TODO(port): add `drop_sentinel_u16` (for `[:0]u16` / WStr) if a caller needs it. -pub fn drop_sentinel(mut buf: Vec) -> Result, AllocError> { - // Zig: try `allocator.remap(slice, slice.len)` (shrink by 1), else dupe+free. - // Rust: `Vec` already tracks capacity vs. len; popping the NUL and shrinking is - // the moral equivalent of `remap`. `into_boxed_slice` reallocates only if - // `cap != len`, matching the Zig fallback. - debug_assert_eq!(buf.last().copied(), Some(0), "buffer is not NUL-terminated"); - buf.pop(); - Ok(buf.into_boxed_slice()) -} - // ported from: src/bun_alloc/memory.zig diff --git a/src/bun_bin/phase_c_exports.rs b/src/bun_bin/phase_c_exports.rs index 8e624e70063..164efec8047 100644 --- a/src/bun_bin/phase_c_exports.rs +++ b/src/bun_bin/phase_c_exports.rs @@ -64,7 +64,7 @@ type VirtualMachine = c_void; // PHASE-C: C++ callback — Zig: `pub export fn Bun__panic(msg, len) noreturn` // REAL: src/main.rs (binary-level export; defined here directly) #[unsafe(no_mangle)] -pub extern "C" fn Bun__panic(msg: *const u8, len: usize) -> ! { +pub(crate) extern "C" fn Bun__panic(msg: *const u8, len: usize) -> ! { let bytes = if msg.is_null() { &b""[..] } else { @@ -132,7 +132,7 @@ pub extern "C" fn Bun__panic(msg: *const u8, len: usize) -> ! { // Bun__VM__allowRejectionHandledWarning #[unsafe(no_mangle)] -pub extern "C" fn Bun__VM__scriptExecutionStatus(_vm: *const VirtualMachine) -> i32 { +pub(crate) extern "C" fn Bun__VM__scriptExecutionStatus(_vm: *const VirtualMachine) -> i32 { // jsc.ScriptExecutionStatus.running = 0 0 } @@ -257,7 +257,7 @@ pub extern "C" fn Bun__VM__scriptExecutionStatus(_vm: *const VirtualMachine) -> // Declared `CPP_DECL` in headers.h:279 but bindings.cpp never defines it. #[unsafe(no_mangle)] -pub extern "C" fn JSC__JSValue__parseJSON( +pub(crate) extern "C" fn JSC__JSValue__parseJSON( _string: *const c_void, _global: *const JSGlobalObject, ) -> JSValue { @@ -268,7 +268,7 @@ pub extern "C" fn JSC__JSValue__parseJSON( // Imported by bun_jsc/bun_sys_jsc as extern but no provider in C++ or Zig. #[unsafe(no_mangle)] -pub extern "C" fn BunString__toErrorInstance( +pub(crate) extern "C" fn BunString__toErrorInstance( _this: *const c_void, _global: *mut JSGlobalObject, ) -> JSValue { @@ -280,15 +280,15 @@ pub extern "C" fn BunString__toErrorInstance( // preventExit/stopPreventingExit protocol commands are no-ops in the inspector // build today. #[unsafe(no_mangle)] -pub extern "C" fn Bun__LifecycleAgentPreventExit(_agent: *mut c_void) {} +pub(crate) extern "C" fn Bun__LifecycleAgentPreventExit(_agent: *mut c_void) {} #[unsafe(no_mangle)] -pub extern "C" fn Bun__LifecycleAgentStopPreventingExit(_agent: *mut c_void) {} +pub(crate) extern "C" fn Bun__LifecycleAgentStopPreventingExit(_agent: *mut c_void) {} // `generated_classes.rs` emits `__getConstructor` externs unconditionally, // but `ZigGeneratedClasses.cpp` only defines them for classes whose `.classes.ts` // declares a `construct` hook. `DNSResolver` has none — the extern is dead. #[unsafe(no_mangle)] -pub extern "C" fn DNSResolver__getConstructor(_global: *mut JSGlobalObject) -> JSValue { +pub(crate) extern "C" fn DNSResolver__getConstructor(_global: *mut JSGlobalObject) -> JSValue { unreachable!("DNSResolver has no JS-visible constructor (no `construct` in .classes.ts)") } diff --git a/src/bun_core/Global.rs b/src/bun_core/Global.rs index 44f5adf7cbc..b43c3096bd2 100644 --- a/src/bun_core/Global.rs +++ b/src/bun_core/Global.rs @@ -130,7 +130,7 @@ impl StoredTrace { } } -/// Zig: `WriteStackTraceLimits`. Aliased as `DumpOptions` for safety/sys callers. +/// Zig: `WriteStackTraceLimits`. #[derive(Copy, Clone, Debug)] pub struct DumpStackTraceOptions { pub frame_count: usize, @@ -150,7 +150,6 @@ impl Default for DumpStackTraceOptions { } } } -pub type DumpOptions = DumpStackTraceOptions; /// Zig-spec name (`crash_handler.WriteStackTraceLimits`); also re-exported from `bun_crash_handler`. pub type WriteStackTraceLimits = DumpStackTraceOptions; @@ -328,11 +327,6 @@ pub mod features { pub fn yaml_parse_inc() { YAML_PARSE.fetch_add(1, core::sync::atomic::Ordering::Relaxed); } - /// install crate calls `bun_core::analytics::Features::lifecycle_scripts_inc(1)`. - #[inline] - pub fn lifecycle_scripts_inc(n: usize) { - LIFECYCLE_SCRIPTS.fetch_add(n, core::sync::atomic::Ordering::Relaxed); - } /// install/yarn crate calls `bun_core::analytics::Features::yarn_migration_inc(1)`. #[inline] pub fn yarn_migration_inc(n: usize) { @@ -400,9 +394,10 @@ pub static JSC_SCOPE: crate::output::ScopedLogger = // Zig: src/cli/cli.zig::debug_flags — debug-build-only breakpoint matchers. pub mod debug_flags { #[cfg(debug_assertions)] - pub static RESOLVE_BREAKPOINTS: crate::Once<&'static [&'static [u8]]> = crate::Once::new(); + pub(crate) static RESOLVE_BREAKPOINTS: crate::Once<&'static [&'static [u8]]> = + crate::Once::new(); #[cfg(debug_assertions)] - pub static PRINT_BREAKPOINTS: crate::Once<&'static [&'static [u8]]> = crate::Once::new(); + pub(crate) static PRINT_BREAKPOINTS: crate::Once<&'static [&'static [u8]]> = crate::Once::new(); #[inline] pub fn has_resolve_breakpoint(str_: &[u8]) -> bool { @@ -534,13 +529,6 @@ pub const arch_name: &str = if cfg!(target_arch = "x86_64") { "unknown" }; -#[inline] -pub fn get_start_time() -> i128 { - crate::start_time() - // TODO(port): Zig reads `bun.start_time` (a global i128). Expose as - // `bun_core::start_time()` or a `static AtomicI128`-equivalent. -} - // ────────────────────────────────────────────────────────────────────────── // Thread naming // ────────────────────────────────────────────────────────────────────────── @@ -591,7 +579,7 @@ pub type ExitFn = extern "C" fn(); static ON_EXIT_CALLBACKS: crate::Mutex> = crate::Mutex::new(Vec::new()); #[unsafe(no_mangle)] -pub extern "C" fn Bun__atexit(function: ExitFn) { +pub(crate) extern "C" fn Bun__atexit(function: ExitFn) { let mut cbs = ON_EXIT_CALLBACKS.lock(); if !cbs.iter().any(|f| *f as usize == function as usize) { cbs.push(function); @@ -616,7 +604,7 @@ pub fn add_pre_exit_callback(function: ExitFn) { } } -pub fn run_exit_callbacks() { +pub(crate) fn run_exit_callbacks() { // Drain under lock, run outside it (callbacks may call `Bun__atexit`). let cbs: Vec = core::mem::take(&mut *ON_EXIT_CALLBACKS.lock()); for callback in &cbs { @@ -627,11 +615,11 @@ pub fn run_exit_callbacks() { static IS_EXITING: AtomicBool = AtomicBool::new(false); #[unsafe(no_mangle)] -pub extern "C" fn bun_is_exiting() -> c_int { +pub(crate) extern "C" fn bun_is_exiting() -> c_int { is_exiting() as c_int } -pub fn is_exiting() -> bool { +pub(crate) fn is_exiting() -> bool { IS_EXITING.load(Ordering::Relaxed) } @@ -802,7 +790,7 @@ pub struct SyncCStr(pub *const c_char); // SAFETY: points into a `'static` string literal; the pointer is never mutated. unsafe impl Sync for SyncCStr {} #[unsafe(no_mangle)] -pub static Bun__userAgent: SyncCStr = +pub(crate) static Bun__userAgent: SyncCStr = SyncCStr(concatcp!(user_agent, "\0").as_ptr().cast::()); /// Prevent the linker from dead-code-eliminating `#[no_mangle]` symbols that are @@ -818,7 +806,7 @@ macro_rules! keep_symbols { } #[unsafe(no_mangle)] -pub extern "C" fn Bun__onExit() { +pub(crate) extern "C" fn Bun__onExit() { // `bun.jsc.Node.FSEvents.closeAndWait()` (spec `Global.zig:220`) — runs // BEFORE the generic exit-callback list, matching Zig ordering. fs_events // pushes into `PRE_EXIT_CALLBACKS` on first loop create. diff --git a/src/bun_core/debug.rs b/src/bun_core/debug.rs index 9a222fd928c..c1dd9ef92be 100644 --- a/src/bun_core/debug.rs +++ b/src/bun_core/debug.rs @@ -278,7 +278,7 @@ pub(crate) const PC_OFFSET: usize = StackIterator::PC_OFFSET; /// If no frame matches (e.g. inlining moved the boundary), the full untrimmed /// trace is returned rather than an empty one — a noisier trace beats none. #[inline(never)] -pub fn capture_current(first_address: Option, out: &mut [usize]) -> usize { +pub(crate) fn capture_current(first_address: Option, out: &mut [usize]) -> usize { #[cfg(windows)] let n = { let cap = out.len().min(u16::MAX as usize) as u32; diff --git a/src/bun_core/env.rs b/src/bun_core/env.rs index 147973ead14..85fe5aadd21 100644 --- a/src/bun_core/env.rs +++ b/src/bun_core/env.rs @@ -13,7 +13,7 @@ pub enum BuildTarget { Wasi, } -pub const BUILD_TARGET: BuildTarget = { +pub(crate) const BUILD_TARGET: BuildTarget = { if cfg!(target_family = "wasm") { BuildTarget::Wasm } else { @@ -21,39 +21,32 @@ pub const BUILD_TARGET: BuildTarget = { } }; -pub const IS_WASM: bool = matches!(BUILD_TARGET, BuildTarget::Wasm); +pub(crate) const IS_WASM: bool = matches!(BUILD_TARGET, BuildTarget::Wasm); pub const IS_NATIVE: bool = matches!(BUILD_TARGET, BuildTarget::Native); -pub const IS_WASI: bool = matches!(BUILD_TARGET, BuildTarget::Wasi); -pub const IS_MAC: bool = IS_NATIVE && cfg!(target_os = "macos"); -pub const IS_BROWSER: bool = !IS_WASI && IS_WASM; +pub(crate) const IS_WASI: bool = matches!(BUILD_TARGET, BuildTarget::Wasi); +pub(crate) const IS_MAC: bool = IS_NATIVE && cfg!(target_os = "macos"); +pub(crate) const IS_BROWSER: bool = !IS_WASI && IS_WASM; pub const IS_WINDOWS: bool = cfg!(windows); -pub const IS_POSIX: bool = !IS_WINDOWS && !IS_WASM; +pub(crate) const IS_POSIX: bool = !IS_WINDOWS && !IS_WASM; pub const IS_DEBUG: bool = cfg!(debug_assertions); -pub const IS_TEST: bool = cfg!(test); +pub(crate) const IS_TEST: bool = cfg!(test); // Zig's `Environment.isLinux` is `builtin.target.os.tag == .linux`, which is // TRUE on Android (Zig models Android as `os.tag == .linux, abi == .android`). // Rust splits them into two `target_os` values, so this const has to OR them // to keep the Zig semantics — otherwise `OS` (below) panics at const-eval on // the `*-linux-android` cross targets and Linux-only code paths are skipped. pub const IS_LINUX: bool = cfg!(any(target_os = "linux", target_os = "android")); -pub const IS_FREEBSD: bool = cfg!(target_os = "freebsd"); +pub(crate) const IS_FREEBSD: bool = cfg!(target_os = "freebsd"); /// kqueue-based event loop (macOS + FreeBSD share most of this path). pub const IS_KQUEUE: bool = IS_MAC || IS_FREEBSD; -pub const IS_AARCH64: bool = cfg!(target_arch = "aarch64"); -pub const IS_X86: bool = cfg!(any(target_arch = "x86", target_arch = "x86_64")); -pub const IS_X64: bool = cfg!(target_arch = "x86_64"); +pub(crate) const IS_AARCH64: bool = cfg!(target_arch = "aarch64"); +pub(crate) const IS_X64: bool = cfg!(target_arch = "x86_64"); pub const IS_MUSL: bool = cfg!(target_env = "musl"); pub const IS_ANDROID: bool = cfg!(target_os = "android"); -pub const IS_GLIBC: bool = IS_LINUX && cfg!(target_env = "gnu"); pub const ALLOW_ASSERT: bool = IS_DEBUG || IS_TEST || build_options::RELEASE_SAFE; pub const CI_ASSERT: bool = IS_DEBUG || IS_TEST || ENABLE_ASAN || (build_options::RELEASE_SAFE && IS_CANARY); pub const SHOW_CRASH_TRACE: bool = IS_DEBUG || IS_TEST || ENABLE_ASAN; -/// Zig gated `@export` blocks behind `output_mode == .Obj` so the -/// `zig translate-c` and codegen pipelines could compile a stripped-down -/// crate. The Rust build is always a single staticlib that exports the C++ -/// surface, so this is a constant `true`. -pub const EXPORT_CPP_APIS: bool = true; pub const REPORTED_NODEJS_VERSION: &str = build_options::REPORTED_NODEJS_VERSION; pub const BASELINE: bool = build_options::BASELINE; @@ -72,7 +65,7 @@ pub const GIT_SHA_SHORTER: &str = if !build_options::SHA.is_empty() { "" }; pub const IS_CANARY: bool = build_options::IS_CANARY; -pub const CANARY_REVISION: &str = if IS_CANARY { +pub(crate) const CANARY_REVISION: &str = if IS_CANARY { build_options::CANARY_REVISION } else { "" @@ -83,14 +76,13 @@ pub const ENABLE_LOGS: bool = build_options::ENABLE_LOGS; pub const ENABLE_ASAN: bool = build_options::ENABLE_ASAN; pub const ENABLE_FUZZILLI: bool = build_options::ENABLE_FUZZILLI; pub const ENABLE_TINYCC: bool = build_options::ENABLE_TINYCC; -pub const CODEGEN_PATH: &[u8] = build_options::CODEGEN_PATH; // TYPE_ONLY: bun_semver::Version moves to bun_core (move-in pass). pub const VERSION: crate::Version = build_options::VERSION; pub const VERSION_STRING: &str = const_format::formatcp!("{}.{}.{}", VERSION.major, VERSION.minor, VERSION.patch); #[allow(non_upper_case_globals)] -pub const version_string: &str = VERSION_STRING; +pub(crate) const version_string: &str = VERSION_STRING; #[inline(always)] pub fn only_mac() { diff --git a/src/bun_core/env_var.rs b/src/bun_core/env_var.rs index 7151d44dd03..9ddfaf7b9a4 100644 --- a/src/bun_core/env_var.rs +++ b/src/bun_core/env_var.rs @@ -673,7 +673,7 @@ macro_rules! platform_specific_new { // set. We expose the default + a const HAS_DEFAULT and always return Option; // a thin `pub fn get() -> ValueType` wrapper that `.unwrap()`s is added when a default // exists. TODO(port): restore the non-nullable `get()` return type for defaulted vars. - pub const DEFAULT: Option = + pub(crate) const DEFAULT: Option = $crate::env_var::__default_opt!($kind, { $($opts)* }); /// Attempt to retrieve the value of the environment variable for the current platform, if @@ -711,13 +711,13 @@ macro_rules! platform_specific_new { } /// Equal to `.platform_key()` except fails to compile if current platform is supported. - pub fn key() -> &'static ZStr { + pub(crate) fn key() -> &'static ZStr { assert_platform_supported(); platform_key().unwrap() } /// Retrieve the key of the environment variable for the current platform, if any. - pub fn platform_key() -> Option<&'static ZStr> { + pub(crate) fn platform_key() -> Option<&'static ZStr> { #[cfg(unix)] { return $crate::env_var::__key_opt!($posix); } #[cfg(windows)] diff --git a/src/bun_core/feature_flags.rs b/src/bun_core/feature_flags.rs index 784ce109a26..e95397b987b 100644 --- a/src/bun_core/feature_flags.rs +++ b/src/bun_core/feature_flags.rs @@ -4,18 +4,12 @@ use crate::env; use crate::feature_flag; -/// Enable breaking changes for the next major release of Bun -// TODO: Make this a CLI flag / runtime var so that we can verify disabled code paths can compile -pub const BREAKING_CHANGES_1_4: bool = false; - /// Store and reuse file descriptors during module resolution /// This was a ~5% performance improvement pub const STORE_FILE_DESCRIPTORS: bool = !env::IS_BROWSER; pub const TRACING: bool = true; -pub const CSS_SUPPORTS_FENCE: bool = true; - pub const ENABLE_ENTRY_CACHE: bool = true; // TODO: remove this flag, it should use bun.Output.scoped @@ -26,8 +20,6 @@ pub const WATCH_DIRECTORIES: bool = true; // This feature flag exists so when you have defines inside package.json, you can use single quotes in nested strings. pub const ALLOW_JSON_SINGLE_QUOTES: bool = true; -pub const IS_MACRO_ENABLED: bool = !env::IS_WASM && !env::IS_WASI; - pub const DISABLE_COMPRESSION_IN_HTTP_CLIENT: bool = false; pub const ENABLE_KEEPALIVE: bool = true; @@ -49,7 +41,7 @@ pub const HARDCODE_LOCALHOST_TO_127_0_0_1: bool = false; /// https://github.com/oven-sh/bun/issues/10733 pub const SUPPORT_JSXS_IN_JSX_TRANSFORM: bool = true; -pub const USE_SIMDUTF: bool = env::IS_NATIVE; +pub(crate) const USE_SIMDUTF: bool = env::IS_NATIVE; pub const INLINE_PROPERTIES_IN_TRANSPILER: bool = true; @@ -100,12 +92,8 @@ pub const UNWRAP_COMMONJS_TO_ESM: bool = true; /// https://github.com/source-map/source-map-rfc/pull/20 pub const SOURCE_MAP_DEBUG_ID: bool = true; -pub const EXPORT_STAR_REDIRECT: bool = false; - pub const STREAMING_FILE_UPLOADS_FOR_HTTP_CLIENT: bool = true; -pub const CONCURRENT_TRANSPILER: bool = true; - // https://github.com/oven-sh/bun/issues/5426#issuecomment-1813865316 pub const DISABLE_AUTO_JS_TO_TS_IN_NODE_MODULES: bool = true; @@ -122,7 +110,7 @@ pub const WINDOWS_BUNX_FAST_PATH: bool = true; // TODO: fix Windows-only test failures in fetch-preconnect.test.ts pub const IS_FETCH_PRECONNECT_SUPPORTED: bool = env::IS_POSIX; -pub const LIBDEFLATE_SUPPORTED: bool = env::IS_NATIVE; +pub(crate) const LIBDEFLATE_SUPPORTED: bool = env::IS_NATIVE; // Mostly exists as a way to turn it off later, if necessary. pub fn is_libdeflate_enabled() -> bool { diff --git a/src/bun_core/heap.rs b/src/bun_core/heap.rs index f42d3049ef1..304bd155a79 100644 --- a/src/bun_core/heap.rs +++ b/src/bun_core/heap.rs @@ -45,13 +45,6 @@ pub fn into_raw(boxed: Box) -> *mut T { Box::into_raw(boxed) } -/// Deprecated alias — see [`into_raw`]. -#[deprecated(note = "renamed to heap::into_raw — this is paired hand-off, not a leak")] -#[inline(always)] -pub fn leak(boxed: Box) -> *mut T { - Box::into_raw(boxed) -} - /// Give up our owning `Box` and return a `&mut T` whose lifetime the caller /// picks (annotate it `&'static mut T` at the call site if the owner is /// process-lifetime). The backing allocation's lifetime is now managed by diff --git a/src/bun_core/lib.rs b/src/bun_core/lib.rs index c99271045d9..215f55f1193 100644 --- a/src/bun_core/lib.rs +++ b/src/bun_core/lib.rs @@ -11,7 +11,7 @@ clippy::disallowed_methods, clippy::disallowed_macros )] -#![warn(unused_must_use, unreachable_pub)] +#![warn(unused_must_use)] pub mod Global; pub mod atomic_cell; @@ -263,7 +263,8 @@ pub mod os { /// (or null if empty). Windows-only; POSIX uses libc's `environ` symbol. #[cfg(windows)] #[inline] -pub fn os_environ_ptr() -> *const *mut core::ffi::c_char { +#[allow(dead_code)] +pub(crate) fn os_environ_ptr() -> *const *mut core::ffi::c_char { // SAFETY: read of a process-global written once at startup. let e = unsafe { os::environ() }; if e.is_empty() { @@ -362,9 +363,6 @@ unsafe extern "C" { // safe: all args by-value; libm `powf` is defined for all f32 inputs. #[link_name = "powf"] safe fn libm_powf(x: f32, y: f32) -> f32; - // safe: all args by-value; libm `pow` is defined for all f64 inputs. - #[link_name = "pow"] - safe fn libm_pow(x: f64, y: f64) -> f64; } #[inline] @@ -372,11 +370,6 @@ pub fn powf(x: f32, y: f32) -> f32 { libm_powf(x, y) } -#[inline] -pub fn pow(x: f64, y: f64) -> f64 { - libm_pow(x, y) -} - /// Safe `Vec` growth helpers — consolidate the /// `reserve(n); spare_capacity_mut(); MaybeUninit::write…; unsafe set_len(n)` /// pattern (S025) so the single `unsafe { set_len }` lives here behind a @@ -457,7 +450,7 @@ pub mod vec { /// Caller must fully write the returned slice before any read of /// `v[prev_len..]` (the slots are uninitialized on entry). #[inline] - pub unsafe fn writable_slice(v: &mut Vec, additional: usize) -> &mut [T] { + pub(crate) unsafe fn writable_slice(v: &mut Vec, additional: usize) -> &mut [T] { v.reserve(additional); let prev = v.len(); // SAFETY: caller contract — slice is fully written before any read. @@ -473,7 +466,10 @@ pub mod vec { /// `v.len() + additional <= v.capacity()`, and the returned slice must be /// fully written before any read. #[inline] - pub unsafe fn writable_slice_assume_capacity(v: &mut Vec, additional: usize) -> &mut [T] { + pub(crate) unsafe fn writable_slice_assume_capacity( + v: &mut Vec, + additional: usize, + ) -> &mut [T] { debug_assert!(v.len() + additional <= v.capacity()); let prev = v.len(); // SAFETY: caller contract — capacity asserted; slice fully written before any read. @@ -2621,8 +2617,10 @@ pub mod strings { // `std::alloc::System` is installed instead. Mirrors `bun_alloc::USE_MIMALLOC`. pub const USE_MIMALLOC: bool = cfg!(not(bun_asan)); pub mod debug_allocator_data { + /// Only referenced from `debug_assert!` — dead in release builds. + #[allow(dead_code)] #[inline] - pub fn deinit_ok() -> bool { + pub(crate) fn deinit_ok() -> bool { true } } @@ -2715,17 +2713,6 @@ pub mod ffi { unsafe { core::ffi::CStr::from_ptr(p) } } - /// Convenience: `cstr(p).to_bytes()`. Dominant shape at call sites - /// (Zig `bun.span(p)` / `std.mem.span(p)` port). - /// - /// # Safety - /// Same contract as [`cstr`]. - #[inline(always)] - pub unsafe fn cstr_bytes<'a>(p: *const core::ffi::c_char) -> &'a [u8] { - // SAFETY: forwarded to `cstr`. - unsafe { cstr(p) }.to_bytes() - } - #[cfg(unix)] static UTSNAME: crate::Once = crate::Once::new(); @@ -2971,10 +2958,13 @@ pub mod ffi { target_os = "openbsd", target_os = "netbsd" ))] + // SAFETY: C POD (integer/array/raw-pointer fields only); all-zero is valid. unsafe impl Zeroable for libc::kevent {} #[cfg(any(target_os = "macos", target_os = "ios"))] + // SAFETY: C POD (integer/array/raw-pointer fields only); all-zero is valid. unsafe impl Zeroable for libc::kevent64_s {} #[cfg(target_os = "freebsd")] + // SAFETY: C POD (integer/array/raw-pointer fields only); all-zero is valid. unsafe impl Zeroable for libc::_umtx_time {} // Windows POD — `bun_windows_sys` `#[repr(C)]` out-param structs that are @@ -3116,8 +3106,6 @@ pub mod asan { //! mimalloc page is reported as a leak. use core::ffi::c_void; - pub const ENABLED: bool = cfg!(bun_asan); - #[cfg(bun_asan)] unsafe extern "C" { // The ASAN/LSAN runtime never dereferences `ptr` — it indexes shadow @@ -3195,7 +3183,7 @@ pub mod asan { // ──────────────────────────────────────────────────────────────────────────── #[cfg(target_os = "linux")] #[unsafe(no_mangle)] -pub extern "C" fn __wrap_gettid() -> libc::pid_t { +pub(crate) extern "C" fn __wrap_gettid() -> libc::pid_t { // SAFETY: SYS_gettid takes no arguments and never fails. unsafe { libc::syscall(libc::SYS_gettid) as libc::pid_t } } diff --git a/src/bun_core/output.rs b/src/bun_core/output.rs index fd1e8394c48..dcf9a7c3c05 100644 --- a/src/bun_core/output.rs +++ b/src/bun_core/output.rs @@ -41,7 +41,7 @@ use crate::io; pub use crate::OutputSink; #[inline] -pub fn output_sink() -> OutputSink { +pub(crate) fn output_sink() -> OutputSink { OutputSink::SYS } @@ -286,7 +286,7 @@ static STDOUT_STREAM_SET: AtomicBool = AtomicBool::new(false); // the C declaration `int32_t bun_stdio_tty[3]`. Using atomics instead of // `RacyCell` makes Rust-side reads/writes fully safe (cell-get reduction). #[unsafe(no_mangle)] -pub static bun_stdio_tty: [AtomicI32; 3] = +pub(crate) static bun_stdio_tty: [AtomicI32; 3] = [AtomicI32::new(0), AtomicI32::new(0), AtomicI32::new(0)]; /// Read `bun_stdio_tty[idx]`. Written once at startup (in `Source::set_init` / @@ -568,14 +568,14 @@ pub mod windows_stdio { /// Write-once at startup → `Once`, not `RacyCell`: `init()` builds the /// snapshot locally and `.set()`s it; `restore()` reads via `.get()`. Both /// sides are fully safe (cell-get reduction). - pub static CONSOLE_MODE: crate::Once<[Option; 3]> = crate::Once::new(); - pub static CONSOLE_CODEPAGE: core::sync::atomic::AtomicU32 = + pub(crate) static CONSOLE_MODE: crate::Once<[Option; 3]> = crate::Once::new(); + pub(crate) static CONSOLE_CODEPAGE: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0); - pub static CONSOLE_OUTPUT_CODEPAGE: core::sync::atomic::AtomicU32 = + pub(crate) static CONSOLE_OUTPUT_CODEPAGE: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0); #[unsafe(no_mangle)] - pub extern "C" fn Bun__restoreWindowsStdio() { + pub(crate) extern "C" fn Bun__restoreWindowsStdio() { restore(); } @@ -703,11 +703,12 @@ pub mod stdio { // does not assert immutability to the optimizer. `safe static` (Rust // 2024 `unsafe extern`) discharges the link-time existence proof here so // readers need no `unsafe` (cell-get reduction). - pub safe static bun_is_stdio_null: [AtomicI32; 3]; + pub(crate) safe static bun_is_stdio_null: [AtomicI32; 3]; /// No preconditions; one-shot stdio fixup at process startup. - pub safe fn bun_initialize_process(); + pub(crate) safe fn bun_initialize_process(); /// No preconditions; restores TTY state on the standard streams. - pub safe fn bun_restore_stdio(); + #[allow(dead_code)] + pub(crate) safe fn bun_restore_stdio(); } /// Read `bun_is_stdio_null[idx]`. Written once by C @@ -877,19 +878,14 @@ pub enum OutputStreamDescriptor { Terminal, } -#[deprecated( - note = "Deprecated to prevent accidentally using the wrong one. Use enable_ansi_colors_stdout or enable_ansi_colors_stderr instead." -)] -pub const ENABLE_ANSI_COLORS: () = (); - pub static ENABLE_ANSI_COLORS_STDERR: AtomicBool = AtomicBool::new(Environment::IS_NATIVE); pub static ENABLE_ANSI_COLORS_STDOUT: AtomicBool = AtomicBool::new(Environment::IS_NATIVE); -pub static ENABLE_BUFFERING: AtomicBool = AtomicBool::new(Environment::IS_NATIVE); -pub static IS_VERBOSE: AtomicBool = AtomicBool::new(false); +pub(crate) static ENABLE_BUFFERING: AtomicBool = AtomicBool::new(Environment::IS_NATIVE); +pub(crate) static IS_VERBOSE: AtomicBool = AtomicBool::new(false); pub static IS_GITHUB_ACTION: AtomicBool = AtomicBool::new(false); -pub static STDERR_DESCRIPTOR_TYPE: crate::Once = crate::Once::new(); -pub static STDOUT_DESCRIPTOR_TYPE: crate::Once = crate::Once::new(); +pub(crate) static STDERR_DESCRIPTOR_TYPE: crate::Once = crate::Once::new(); +pub(crate) static STDOUT_DESCRIPTOR_TYPE: crate::Once = crate::Once::new(); /// Downstream alias (Zig: `Output.OutputStreamDescriptor`). Several call sites /// refer to it as `Output::DescriptorType` for brevity. @@ -917,10 +913,6 @@ pub fn is_stdout_tty() -> bool { stdio_tty_flag(1) } #[inline] -pub fn is_stderr_tty() -> bool { - stdio_tty_flag(2) -} -#[inline] pub fn is_stdin_tty() -> bool { stdio_tty_flag(0) } @@ -1049,8 +1041,6 @@ pub fn panic(args: fmt::Arguments<'_>) -> ! { core::panic!("{args}"); } -pub type WriterType = QuietWriter; - pub fn raw_error_writer() -> StreamType { debug_assert!(SOURCE_SET.get()); SOURCE.with_borrow(|s| s.raw_error_stream) @@ -1085,11 +1075,6 @@ pub fn error_writer_buffered() -> &'static mut io::Writer { source_writer_escape(Source::buffered_error_stream) } -// TODO: investigate returning the buffered_error_stream -pub fn error_stream() -> &'static mut io::Writer { - source_writer_escape(Source::error_stream) -} - pub fn raw_writer() -> StreamType { debug_assert!(SOURCE_SET.get()); SOURCE.with_borrow(|s| s.raw_stream) @@ -1447,7 +1432,7 @@ macro_rules! debug { /// comptime template and therefore *always* appends `\n`. Callers must NOT /// pass a template that already ends in `\n`. Prefer the `debug!` macro. #[inline] -pub fn _debug(args: fmt::Arguments<'_>) { +pub(crate) fn _debug(args: fmt::Arguments<'_>) { debug_assert!(SOURCE_SET.get()); print_to(Destination::Stdout, args); write_bytes(Destination::Stdout, b"\n"); @@ -1469,9 +1454,11 @@ pub fn println(args: fmt::Arguments<'_>) { // Scoped debug logging // ────────────────────────────────────────────────────────────────────────── -/// Debug-only logs which should not appear in release mode +/// Debug-only logs which should not appear in release mode. +/// /// To enable a specific log at runtime, set the environment variable -/// BUN_DEBUG_${TAG} to 1 +/// `BUN_DEBUG_${TAG}` to 1. +/// /// For example, to enable the "foo" log, set the environment variable /// BUN_DEBUG_foo=1 /// To enable all logs, set the environment variable @@ -2060,9 +2047,6 @@ pub fn pretty_fmt_args( } } -/// Legacy name kept for back-compat with crash_handler. -pub type PrettyFmtArgs<'a> = TemplateDisplay<'a, fmt::Arguments<'a>>; - /// Runtime mirror of Zig `prettyFmt` for testing the proc-macro and for the rare /// dynamic case. Produces the same byte sequence the Zig comptime version would. /// @@ -2177,33 +2161,6 @@ pub fn _scoped_use_ansi() -> bool { } } -#[inline] -pub fn pretty_to(dest: Destination, colored: fmt::Arguments<'_>, plain: fmt::Arguments<'_>) { - // Route through `print_to` so the WASM console_log/console_error path stays - // covered (dest_writer alone bypasses it). - if enable_color_for(dest) { - print_to(dest, colored); - } else { - print_to(dest, plain); - } -} - -/// `prettyWithPrinter(fmt, args, printer, dest)` — calls `printer` with the -/// color-appropriate format. Printer takes `fmt::Arguments`. -#[inline] -pub fn pretty_with_printer( - colored: fmt::Arguments<'_>, - plain: fmt::Arguments<'_>, - printer: impl FnOnce(fmt::Arguments<'_>), - dest: Destination, -) { - if enable_color_for(dest) { - printer(colored); - } else { - printer(plain); - } -} - /// Internal: bind each `$arg` exactly once into a `match` tuple, then dispatch /// on the per-destination color flag and call `print_to` with the appropriate /// `pretty_fmt!`-expanded template. Mirrors Zig's `prettyTo` which receives the @@ -2465,8 +2422,6 @@ pub fn enable_ansi_colors_stdout() -> bool { pub fn enable_ansi_colors_stderr() -> bool { ENABLE_ANSI_COLORS_STDERR.load(Ordering::Relaxed) } -/// `Output.enable_ansi_colors` (legacy combined accessor — Zig deprecates the -/// var; expose as stderr to match its historical meaning). #[inline] pub fn enable_ansi_colors() -> bool { ENABLE_ANSI_COLORS_STDERR.load(Ordering::Relaxed) @@ -2649,21 +2604,21 @@ impl ErrName for crate::Error { pub mod scoped_debug_writer { use super::*; - pub static SCOPED_FILE_WRITER: crate::RacyCell = + pub(crate) static SCOPED_FILE_WRITER: crate::RacyCell = crate::RacyCell::new(QuietWriter::ZEROED); thread_local! { - pub static DISABLE_INSIDE_LOG: Cell = const { Cell::new(0) }; + pub(crate) static DISABLE_INSIDE_LOG: Cell = const { Cell::new(0) }; } /// RAII guard that suppresses scoped logging for the lifetime of the guard /// (Zig: `disable_inside_log += 1; defer disable_inside_log -= 1;`). #[must_use] - pub struct DisableGuard(()); + pub(crate) struct DisableGuard(()); impl DisableGuard { #[inline] - pub fn new() -> Self { + pub(crate) fn new() -> Self { DISABLE_INSIDE_LOG.set(DISABLE_INSIDE_LOG.get() + 1); Self(()) } @@ -2681,9 +2636,6 @@ pub fn disable_scoped_debug_writer() { // Zig: `if (!@inComptime())` — always runtime in Rust. scoped_debug_writer::DISABLE_INSIDE_LOG.set(scoped_debug_writer::DISABLE_INSIDE_LOG.get() + 1); } -pub fn enable_scoped_debug_writer() { - scoped_debug_writer::DISABLE_INSIDE_LOG.set(scoped_debug_writer::DISABLE_INSIDE_LOG.get() - 1); -} // TODO(port): move to bun_core_sys unsafe extern "C" { @@ -2691,7 +2643,7 @@ unsafe extern "C" { safe fn getpid() -> c_int; } -pub fn init_scoped_debug_writer_at_startup() { +pub(crate) fn init_scoped_debug_writer_at_startup() { debug_assert!(SOURCE_SET.get()); if let Some(path) = env_var::BUN_DEBUG.get() { @@ -2775,21 +2727,22 @@ pub fn err_fmt(formatter: impl fmt::Display) { // `prompt`/`init`/`publish` callers can read stdin without naming bun_sys. // ────────────────────────────────────────────────────────────────────────── -pub static BUFFERED_STDIN: crate::RacyCell = crate::RacyCell::new(BufferedStdin { - fd: { - #[cfg(windows)] - { - Fd::INVALID // set in WindowsStdio.init - } - #[cfg(not(windows))] - { - Fd::stdin() - } - }, - buf: [0; 4096], - start: 0, - end: 0, -}); +pub(crate) static BUFFERED_STDIN: crate::RacyCell = + crate::RacyCell::new(BufferedStdin { + fd: { + #[cfg(windows)] + { + Fd::INVALID // set in WindowsStdio.init + } + #[cfg(not(windows))] + { + Fd::stdin() + } + }, + buf: [0; 4096], + start: 0, + end: 0, + }); /// `bun.deprecated.BufferedReader(4096, File.Reader)` over the process stdin. /// Layout is local to bun_core; bun_sys never casts into this (it only fills diff --git a/src/bun_core/string/PathString.rs b/src/bun_core/string/PathString.rs index b7c2025040a..8d4481a9e6a 100644 --- a/src/bun_core/string/PathString.rs +++ b/src/bun_core/string/PathString.rs @@ -72,7 +72,7 @@ impl PathString { (self.0 >> POINTER_BITS) as usize } - pub fn estimated_size(&self) -> usize { + pub fn estimated_size(self) -> usize { self.len() } diff --git a/src/bun_core/string/SmolStr.rs b/src/bun_core/string/SmolStr.rs index a4a1d32ed45..dade67f31d9 100644 --- a/src/bun_core/string/SmolStr.rs +++ b/src/bun_core/string/SmolStr.rs @@ -263,7 +263,7 @@ pub trait JsonWriter { pub struct Inlined(u128); #[derive(Debug, thiserror::Error, strum::IntoStaticStr)] -pub enum InlinedError { +pub(crate) enum InlinedError { #[error("StringTooLong")] StringTooLong, } @@ -275,12 +275,12 @@ impl From for crate::Error { } impl Inlined { - pub const MAX_LEN: usize = 120 / 8; // = 15 - pub const EMPTY: Inlined = Inlined(1u128 << 127); // data=0, __len=0, _tag=1 + pub(crate) const MAX_LEN: usize = 120 / 8; // = 15 + pub(crate) const EMPTY: Inlined = Inlined(1u128 << 127); // data=0, __len=0, _tag=1 /// ## Errors /// if `str` is longer than `MAX_LEN` - pub fn init(str: &[u8]) -> Result { + pub(crate) fn init(str: &[u8]) -> Result { if str.len() > Self::MAX_LEN { // PERF(port): @branchHint(.unlikely) — no stable Rust equivalent return Err(InlinedError::StringTooLong); @@ -295,11 +295,11 @@ impl Inlined { } #[inline] - pub fn len(&self) -> u8 { + pub(crate) fn len(&self) -> u8 { ((self.0 >> 120) & 0x7F) as u8 } - pub fn set_len(&mut self, new_len: u8) { + pub(crate) fn set_len(&mut self, new_len: u8) { debug_assert!(new_len < 128); // u7 self.0 = (self.0 & !(0x7Fu128 << 120)) | ((new_len as u128) << 120); } @@ -310,19 +310,13 @@ impl Inlined { self.0 = (self.0 & !(1u128 << 127)) | ((tag as u128) << 127); } - pub fn slice(&self) -> &[u8] { + pub(crate) fn slice(&self) -> &[u8] { // Bytes 0..len of the backing u128 are the inline data on little-endian; // `u128: Pod` lets us view them safely. &crate::bytes_of(&self.0)[..self.len() as usize] } - pub fn slice_mut(&mut self) -> &mut [u8] { - let len = self.len() as usize; - // `u128: Pod` lets us view its bytes safely; first `len` are the data. - &mut crate::bytes_of_mut(&mut self.0)[..len] - } - - pub fn all_chars(&mut self) -> &mut [u8; Self::MAX_LEN] { + pub(crate) fn all_chars(&mut self) -> &mut [u8; Self::MAX_LEN] { // SAFETY: the first 15 bytes of the u128 backing storage are the `data` field // (little-endian, asserted at module top). `ptr()` derives a `*mut u8` from // `&mut self.0`, so the resulting reference has provenance over the full u128 and diff --git a/src/bun_core/string/identifier.rs b/src/bun_core/string/identifier.rs index 1c5c753afb6..5819dfabc25 100644 --- a/src/bun_core/string/identifier.rs +++ b/src/bun_core/string/identifier.rs @@ -85,932 +85,8 @@ pub fn is_identifier_utf16(text: &[u16]) -> bool { // PORT NOTE: Zig `u21` codepoint type → `u32`. Callers must pass cp <= 0x10FFFF // (stage1 tables are sized for that range); out-of-range indexes panic. -/// isIDStartES5 checks if a codepoint is valid in the isIDStartES5 category -pub fn is_id_start_es5(cp: u32) -> bool { - let high = (cp >> 8) as usize; - let low = cp & 0xFF; - let stage2_idx = id_start_es5::STAGE1[high] as u32; - let bit_pos = stage2_idx + low; - let u64_idx = (bit_pos >> 6) as usize; - let bit_idx = bit_pos & 63; - (id_start_es5::STAGE2[u64_idx] & (1u64 << bit_idx)) != 0 -} -mod id_start_es5 { - pub(super) static STAGE1: &[u16] = &[ - 0, 256, 512, 768, 1024, 1280, 1536, 1792, 2048, 2304, 2560, 2816, 3072, 3328, 3584, 3840, - 4096, 4352, 4608, 4864, 5120, 256, 5376, 5632, 5888, 2048, 2048, 2048, 2048, 2048, 6144, - 6400, 6656, 6912, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 7168, 7424, 2048, 2048, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, - 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 7680, 256, 256, 256, - 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, - 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, - 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, - 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, - 256, 256, 256, 256, 256, 256, 7936, 256, 256, 256, 256, 8192, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, - 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, - 256, 256, 256, 256, 256, 256, 256, 256, 256, 8448, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 256, 8704, 8960, - 256, 9216, 9472, 9728, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, - ]; - pub(super) static STAGE2: &[u64] = &[ - 0, - 576460743847706622, - 297241973452963840, - 18410715276682199039, - 18446744073709551615, - 18446744073709551615, - 18446744073709551615, - 18446744073709551615, - 4503586742468607, - 18446744073709486080, - 18014187403249451007, - 70501888360451, - 0, - 288230376151711744, - 18446744056529672000, - 4503599577006079, - 18446744073709551615, - 18446744073709551615, - 18446744073709547523, - 234187180623206815, - 18446181123756130304, - 18446744065161560063, - 255, - 1979120929931264, - 576460743713488896, - 18446181123756132351, - 18446744073709551615, - 2017613045381988351, - 35184371892224, - 0, - 274877906943, - 0, - 0, - 0, - 0, - 0, - 2594073385365405664, - 17163157504, - 271902628478820320, - 844440767823872, - 247132830528276448, - 7881300924956672, - 2589004636761075680, - 4295032832, - 2579997437506199520, - 15837691904, - 270153412153034720, - 0, - 283724577500946400, - 12884901888, - 283724577500946400, - 13958643712, - 288228177128316896, - 12884901888, - 3457638613854978016, - 127, - 3940649673949182, - 127, - 2309762420256548246, - 805306463, - 1, - 8796093021951, - 3840, - 0, - 7679401525247, - 4128768, - 18446744069414584320, - 36028797018898495, - 18446744073709551615, - 18446744071629176831, - 18446743008557662207, - 288230376151711743, - 18446744073709551487, - 18446744070446333311, - 9168625153884503423, - 18446603336212774717, - 18446744071549321215, - 134217599, - 18446744069414584320, - 9007199254740991, - 18446744073709551614, - 18446744073709551615, - 18446744073709551615, - 18446744073709551615, - 18446744073709551615, - 35923243902697471, - 18446744069548802046, - 8796093022207, - 0, - 0, - 4503599627370495, - 0, - 18446744069414584320, - 72057594037927935, - 2199023255551, - 0, - 18446744073709551615, - 18446744073709551615, - 18446744069683019775, - 288230376151711743, - 18446744070475743231, - 4611686017001275199, - 6908521828386340863, - 2295745090394464220, - 0, - 9223372036854775808, - 0, - 0, - 287031153606524036, - 0, - 0, - 0, - 17451448556060768, - 18446744073709551614, - 18446744066732326911, - 8646911284551352319, - 18446216308128219104, - 18446744073709551615, - 72057589742993407, - 0, - 18446744073709551615, - 18446744073709551615, - 18014398509481983, - 0, - 18446744073709551615, - 18446744073709551615, - 274877906943, - 0, - 18446744073709551615, - 18446744073709551615, - 8191, - 0, - 18446744073709551615, - 18446744073709551615, - 68719476735, - 0, - 70368744177663, - 0, - 0, - 0, - 6881498030004502655, - 18446744073709551579, - 1125899906842623, - 18446744073709027328, - 4611686018427387903, - 18446744073709486080, - 18446744073709355007, - 1152640029630136575, - 0, - 18435203599664414720, - 18446744073709551615, - 2305843009213693951, - 576460743713488896, - 18446743798965862398, - 9223372036854775807, - 486341884, - ]; -} - -/// isIDContinueES5 checks if a codepoint is valid in the isIDContinueES5 category -pub fn is_id_continue_es5(cp: u32) -> bool { - let high = (cp >> 8) as usize; - let low = cp & 0xFF; - let stage2_idx = id_continue_es5::STAGE1[high] as u32; - let bit_pos = stage2_idx + low; - let u64_idx = (bit_pos >> 6) as usize; - let bit_idx = bit_pos & 63; - (id_continue_es5::STAGE2[u64_idx] & (1u64 << bit_idx)) != 0 -} -mod id_continue_es5 { - pub(super) static STAGE1: &[u16] = &[ - 0, 256, 512, 768, 1024, 1280, 1536, 1792, 2048, 2304, 2560, 2816, 3072, 3328, 3584, 3840, - 4096, 4352, 4608, 4864, 5120, 256, 5376, 5632, 5888, 2048, 2048, 2048, 2048, 2048, 6144, - 6400, 6656, 6912, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 7168, 7424, 2048, 2048, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, - 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 7680, 256, 256, 256, - 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, - 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, - 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, - 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, - 256, 256, 256, 256, 256, 256, 7936, 256, 256, 256, 256, 8192, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, - 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, 256, - 256, 256, 256, 256, 256, 256, 256, 256, 256, 8448, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 256, 8704, 8960, - 256, 9216, 9472, 9728, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, 2048, - 2048, 2048, 2048, 2048, 2048, - ]; - pub(super) static STAGE2: &[u64] = &[ - 287948901175001088, - 576460745995190270, - 297241973452963840, - 18410715276682199039, - 18446744073709551615, - 18446744073709551615, - 18446744073709551615, - 18446744073709551615, - 4503586742468607, - 18446744073709486080, - 18014187403249451007, - 70501888360451, - 18446744073709551615, - 288230406216515583, - 18446744056529672000, - 4503599577006079, - 18446744073709551615, - 18446744073709551615, - 18446744073709547643, - 234187180623206815, - 18446181123756130304, - 18446744065161560063, - 13546827661950451967, - 1979120929931286, - 576460743713488896, - 18446466992488579071, - 18446744073709551615, - 2305629702346244095, - 18446497783104864256, - 2047, - 562949953421311, - 0, - 0, - 0, - 0, - 0, - 17582052945254416366, - 281268803551231, - 15259882188367831022, - 1125692414638495, - 15235112390417287140, - 9006925953907079, - 17576984196650086382, - 281204393851839, - 17567976997395210222, - 281215949093263, - 14105211467435198444, - 280925229301191, - 14118782632783110126, - 281212990012895, - 14118782632783110124, - 281214063754719, - 14123286232410480620, - 281212992110031, - 3457638613854978028, - 3377704004977791, - 576460752303423486, - 67076095, - 4323434403644581270, - 872365919, - 14024213633433600001, - 18446189919849152255, - 2305843009196855263, - 64, - 272457864671395839, - 67044351, - 18446744069414584320, - 36028797018898495, - 18446744073709551615, - 18446744071629176831, - 18446743008557662207, - 288230376151711743, - 18446744073709551487, - 18446744070446333311, - 9168625153884503423, - 18446603336212774717, - 18446744071549321215, - 1123701017804671, - 18446744069414584320, - 9007199254740991, - 18446744073709551614, - 18446744073709551615, - 18446744073709551615, - 18446744073709551615, - 18446744073709551615, - 35923243902697471, - 18446744069548802046, - 8796093022207, - 0, - 0, - 18446744073709551615, - 4393752592383, - 18446744069481627648, - 72057594037927935, - 4398046511103, - 0, - 18446744073709551615, - 18446744073709551615, - 18446744069683019775, - 288230376151711743, - 18446744070475743231, - 4611686017001275199, - 6908521828386340863, - 2295745090394464220, - 9223372036854775808, - 9223372036854775809, - 0, - 9126739968, - 287031153606524036, - 0, - 0, - 0, - 17728525486260320, - 18446744073709551614, - 18446744066832990207, - 9223372036854775807, - 18446216308128219104, - 18446744073709551615, - 72057589742993407, - 0, - 18446744073709551615, - 18446744073709551615, - 18014398509481983, - 0, - 18446744073709551615, - 18446744073709551615, - 274877906943, - 0, - 18446744073709551615, - 18446744073709551615, - 8191, - 0, - 18446744073709551615, - 18446744073709551615, - 68719476735, - 0, - 70368744177663, - 0, - 0, - 0, - 6881498031078244479, - 18446744073709551579, - 1125899906842623, - 18446744073709027328, - 4611686018427387903, - 18446744073709486080, - 18446744073709355007, - 1152640029630136575, - 6755463865565184, - 18435203599664472064, - 18446744073709551615, - 2305843009213693951, - 9799832780635308032, - 18446743936404815870, - 9223372036854775807, - 486341884, - ]; -} - /// isIDStartESNext checks if a codepoint is valid in the isIDStartESNext category -pub fn is_id_start_es_next(cp: u32) -> bool { +pub(crate) fn is_id_start_es_next(cp: u32) -> bool { let high = (cp >> 8) as usize; let low = cp & 0xFF; let stage2_idx = id_start_es_next::STAGE1[high] as u32; @@ -1785,7 +861,7 @@ mod id_start_es_next { } /// isIDContinueESNext checks if a codepoint is valid in the isIDContinueESNext category -pub fn is_id_continue_es_next(cp: u32) -> bool { +pub(crate) fn is_id_continue_es_next(cp: u32) -> bool { let high = (cp >> 8) as usize; let low = cp & 0xFF; let stage2_idx = id_continue_es_next::STAGE1[high] as u32; diff --git a/src/bun_core/string/immutable/exact_size_matcher.rs b/src/bun_core/string/immutable/exact_size_matcher.rs index 877bd3eaceb..b1f31b44e25 100644 --- a/src/bun_core/string/immutable/exact_size_matcher.rs +++ b/src/bun_core/string/immutable/exact_size_matcher.rs @@ -90,27 +90,6 @@ where } } - /// Zig: `pub fn matchLower(str: anytype) T` - #[inline] - pub fn match_lower(str: &[u8]) -> >::T { - match str.len() { - n if n >= 1 && n < MAX_BYTES => { - let mut tmp = [0u8; MAX_BYTES]; - // @memset(tmp[str.len..], 0) — already zeroed - crate::strings::copy_lowercase(str, &mut tmp[..str.len()]); - Self::read_le(&tmp) - } - n if n == MAX_BYTES => { - // PORT NOTE: Zig does NOT lowercase in the `== max_bytes` arm (matches - // upstream behavior exactly — likely a latent Zig bug, preserved here). - let arr: &[u8; MAX_BYTES] = str.try_into().expect("len == MAX_BYTES"); - Self::read_le(arr) - } - 0 => Self::ZERO, - _ => Self::MAX, - } - } - /// Zig: `pub fn case(comptime str: []const u8) T` /// /// Runtime variant. For const-position (Zig's comptime use in `switch` @@ -171,7 +150,7 @@ macro_rules! exact_case { } #[doc(hidden)] -pub const fn __pad(s: &[u8]) -> [u8; N] { +pub(crate) const fn __pad(s: &[u8]) -> [u8; N] { assert!(s.len() <= N, "str too long for exact_case!"); let mut out = [0u8; N]; let mut i = 0; diff --git a/src/bun_core/string/immutable/grapheme.rs b/src/bun_core/string/immutable/grapheme.rs index c0c172296a1..3250e8ac1bb 100644 --- a/src/bun_core/string/immutable/grapheme.rs +++ b/src/bun_core/string/immutable/grapheme.rs @@ -58,7 +58,7 @@ impl GraphemeBreakNoControl { /// State maintained between sequential calls to grapheme_break. #[repr(u8)] // Zig: enum(u3) — Rust has no u3 repr; values fit in 3 bits #[derive(Copy, Clone, PartialEq, Eq)] -pub enum BreakState { +pub(crate) enum BreakState { Default, RegionalIndicator, ExtendedPictographic, @@ -68,7 +68,7 @@ pub enum BreakState { impl BreakState { #[inline] - pub const fn from_raw(n: u8) -> Self { + pub(crate) const fn from_raw(n: u8) -> Self { // #[repr(u8)] enum with variants 0..=4; caller guarantees range // (round-tripped through `state as u8`). Out-of-range traps — // matches Zig's safety-checked `@enumFromInt`. @@ -95,7 +95,7 @@ pub struct Tables { impl Tables { #[inline] - pub fn get(&self, cp: u32) -> Elem { + pub(crate) fn get(&self, cp: u32) -> Elem { // Zig: cp is u21; Rust uses u32 (caller must pass valid codepoint <= 0x10FFFF). let high = cp >> 8; let low = cp & 0xFF; @@ -111,7 +111,7 @@ pub use grapheme_tables::TABLE; /// /// This function does NOT handle control characters, line feeds, or /// carriage returns. Those must be filtered out before calling. -pub fn grapheme_break(cp1: u32, cp2: u32, state: &mut BreakState) -> bool { +pub(crate) fn grapheme_break(cp1: u32, cp2: u32, state: &mut BreakState) -> bool { let value = precompute::DATA[precompute::Key::new( grapheme_tables::TABLE.get(cp1), grapheme_tables::TABLE.get(cp2), diff --git a/src/bun_core/string/immutable/visible.rs b/src/bun_core/string/immutable/visible.rs index 32e937f93cc..5aafa959b43 100644 --- a/src/bun_core/string/immutable/visible.rs +++ b/src/bun_core/string/immutable/visible.rs @@ -1376,11 +1376,11 @@ pub mod visible { } pub mod width { - pub fn latin1(input: &[u8]) -> usize { + pub(crate) fn latin1(input: &[u8]) -> usize { super::visible_latin1_width(input) } - pub fn utf8(input: &[u8]) -> usize { + pub(crate) fn utf8(input: &[u8]) -> usize { super::visible_utf8_width_fn(input, super::visible_latin1_width) } @@ -1389,7 +1389,7 @@ pub mod visible { } pub mod exclude_ansi_colors { - pub fn latin1(input: &[u8]) -> usize { + pub(crate) fn latin1(input: &[u8]) -> usize { super::super::visible_latin1_width_exclude_ansi_colors(input) } diff --git a/src/bun_core/string/mod.rs b/src/bun_core/string/mod.rs index dfde6ce195f..e378eb88672 100644 --- a/src/bun_core/string/mod.rs +++ b/src/bun_core/string/mod.rs @@ -107,7 +107,7 @@ unsafe extern "C" { /// `void (*)(void*, void*, size_t)` — the third arg is `size_t`, **not** /// `unsigned`. A `u32` here would truncate on 64-bit and (worse) shift the /// stack/register layout for the callee on Win64 where `size_t` ≠ `unsigned`. -pub type ExternalStringImplFreeFunction = +pub(crate) type ExternalStringImplFreeFunction = extern "C" fn(ctx: Ctx, buffer: *mut core::ffi::c_void, len: usize); impl String { @@ -2472,7 +2472,6 @@ pub mod printer { pub const FIRST_ASCII: u32 = 0x20; pub const LAST_ASCII: u32 = 0x7E; pub const FIRST_HIGH_SURROGATE: u32 = 0xD800; - pub const FIRST_LOW_SURROGATE: u32 = 0xDC00; pub const LAST_LOW_SURROGATE: u32 = 0xDFFF; /// Encode a BMP code unit (`c <= 0xFFFF`, including lone surrogates) as the @@ -2501,7 +2500,7 @@ pub mod printer { pub use crate::io::Write as PrinterWriter; #[inline] - pub fn can_print_without_escape(c: i32, ascii_only: bool) -> bool { + pub(crate) fn can_print_without_escape(c: i32, ascii_only: bool) -> bool { if c <= LAST_ASCII as i32 { c >= FIRST_ASCII as i32 && c != b'\\' as i32 diff --git a/src/bun_core/thread_id.rs b/src/bun_core/thread_id.rs index 5ad58663eba..9a1195f6059 100644 --- a/src/bun_core/thread_id.rs +++ b/src/bun_core/thread_id.rs @@ -170,7 +170,7 @@ fn current_uncached() -> ThreadId { } let mut id: u64 = 0; // SAFETY: passing null requests the current thread; `id` is a valid out-ptr. - let rc = unsafe { pthread_threadid_np(core::ptr::null_mut(), &mut id) }; + let rc = unsafe { pthread_threadid_np(core::ptr::null_mut(), &raw mut id) }; debug_assert_eq!(rc, 0); return id; } diff --git a/src/bun_core/windows_sys.rs b/src/bun_core/windows_sys.rs index 9ad2586ad33..06b54e2a9c3 100644 --- a/src/bun_core/windows_sys.rs +++ b/src/bun_core/windows_sys.rs @@ -19,9 +19,9 @@ pub const STD_OUTPUT_HANDLE: DWORD = (-11i32) as DWORD; pub const STD_ERROR_HANDLE: DWORD = (-12i32) as DWORD; // Console mode flags (consoleapi.h). -pub const ENABLE_PROCESSED_OUTPUT: DWORD = 0x0001; -pub const ENABLE_WRAP_AT_EOL_OUTPUT: DWORD = 0x0002; -pub const ENABLE_VIRTUAL_TERMINAL_PROCESSING: DWORD = 0x0004; +pub(crate) const ENABLE_PROCESSED_OUTPUT: DWORD = 0x0001; +pub(crate) const ENABLE_WRAP_AT_EOL_OUTPUT: DWORD = 0x0002; +pub(crate) const ENABLE_VIRTUAL_TERMINAL_PROCESSING: DWORD = 0x0004; /// Wrapper that returns `None` on `INVALID_HANDLE_VALUE` (matches /// `std.os.windows.GetStdHandle` error-union semantics). @@ -64,6 +64,6 @@ pub use kernel32 as c; pub mod libuv { unsafe extern "C" { /// No preconditions; walks the CRT fd table and clears HANDLE_FLAG_INHERIT. - pub safe fn uv_disable_stdio_inheritance(); + pub(crate) safe fn uv_disable_stdio_inheritance(); } } diff --git a/src/bun_output_tags/lib.rs b/src/bun_output_tags/lib.rs index c631f5b0b42..3b5859c4d65 100644 --- a/src/bun_output_tags/lib.rs +++ b/src/bun_output_tags/lib.rs @@ -18,21 +18,21 @@ pub mod ansi { pub const RESET: &str = "\x1b[0m"; pub const BOLD: &str = "\x1b[1m"; pub const DIM: &str = "\x1b[2m"; - pub const ITALIC: &str = "\x1b[3m"; - pub const UNDERLINE: &str = "\x1b[4m"; + pub(crate) const ITALIC: &str = "\x1b[3m"; + pub(crate) const UNDERLINE: &str = "\x1b[4m"; pub const INVERT: &str = "\x1b[7m"; pub const STRIKETHROUGH: &str = "\x1b[9m"; - pub const BLACK: &str = "\x1b[30m"; + pub(crate) const BLACK: &str = "\x1b[30m"; pub const RED: &str = "\x1b[31m"; pub const GREEN: &str = "\x1b[32m"; pub const YELLOW: &str = "\x1b[33m"; pub const BLUE: &str = "\x1b[34m"; pub const MAGENTA: &str = "\x1b[35m"; pub const CYAN: &str = "\x1b[36m"; - pub const WHITE: &str = "\x1b[37m"; + pub(crate) const WHITE: &str = "\x1b[37m"; pub const BRIGHT_WHITE: &str = "\x1b[97m"; - pub const BG_RED: &str = "\x1b[41m"; - pub const BG_GREEN: &str = "\x1b[42m"; + pub(crate) const BG_RED: &str = "\x1b[41m"; + pub(crate) const BG_GREEN: &str = "\x1b[42m"; } /// Byte-slice views of [`ansi`] for callers that write into `&[u8]` buffers @@ -63,7 +63,7 @@ pub mod ansi_b { /// `(tag, ansi_escape)` pairs. 14 entries — linear scan in [`color_for`] is /// intentional; this is only hit on `` markers in diagnostic-output paths. -pub const COLOR_TABLE: &[(&str, &str)] = &[ +pub(crate) const COLOR_TABLE: &[(&str, &str)] = &[ ("b", ansi::BOLD), ("d", ansi::DIM), ("i", ansi::ITALIC), diff --git a/src/bundler/AstBuilder.rs b/src/bundler/AstBuilder.rs index d64ebffa3c4..e728bea1731 100644 --- a/src/bundler/AstBuilder.rs +++ b/src/bundler/AstBuilder.rs @@ -62,21 +62,7 @@ pub struct AstBuilder<'a, 'bump> { // and a `parser_features` decl so `ImportScanner.scan` could duck-type over both // the real parser and `AstBuilder`. In Rust this becomes a trait that both impl. // TODO(port): define `ImportScannerHost` trait in `bun_js_parser` and impl it here. -pub mod parser_features { - pub const TYPESCRIPT: bool = false; -} - impl<'a, 'bump> AstBuilder<'a, 'bump> { - // stub for ImportScanner duck typing — Zig: `comptime options: js_parser.Parser.Options = .{ .jsx = .{}, .bundle = true }` - // TODO(port): expose as trait assoc const once `ImportScannerHost` exists - pub fn options(&self) -> js_parser::parse::parse_entry::Options<'static> { - js_parser::parse::parse_entry::Options { - jsx: Default::default(), - bundle: true, - ..Default::default() - } - } - // stub for ImportScanner duck typing — Zig: `comptime import_items_for_namespace: struct { fn get(_, _) ?Map { return null; } }` pub fn import_items_for_namespace_get( &self, diff --git a/src/bundler/BundleThread.rs b/src/bundler/BundleThread.rs index 04046c92994..5e4c689e785 100644 --- a/src/bundler/BundleThread.rs +++ b/src/bundler/BundleThread.rs @@ -10,7 +10,7 @@ use crate::{BundleV2, Transpiler}; /// Used to keep the bundle thread from spinning on Windows #[cfg(windows)] -pub extern "C" fn timer_callback(_: *mut bun_sys::windows::libuv::Timer) {} +pub(crate) extern "C" fn timer_callback(_: *mut bun_sys::windows::libuv::Timer) {} /// Port of `std.Thread.ResetEvent` — single-shot manual-reset event used to /// block `spawn()` until the bundle thread has initialized its `Waker`. diff --git a/src/bundler/Chunk.rs b/src/bundler/Chunk.rs index 52e43f1be04..34f74806d9d 100644 --- a/src/bundler/Chunk.rs +++ b/src/bundler/Chunk.rs @@ -334,21 +334,21 @@ impl Chunk { } #[derive(Clone, Copy, Default)] -pub struct Order { +pub(crate) struct Order { pub source_index: IndexInt, pub distance: u32, pub tie_breaker: u32, } impl Order { - pub fn less_than(_ctx: Order, a: Order, b: Order) -> bool { + pub(crate) fn less_than(_ctx: Order, a: Order, b: Order) -> bool { (a.distance < b.distance) || (a.distance == b.distance && a.tie_breaker < b.tie_breaker) } /// Sort so files closest to an entry point come first. If two files are /// equidistant to an entry point, then break the tie by sorting on the /// stable source index derived from the DFS over all entry points. - pub fn sort(a: &mut [Order]) { + pub(crate) fn sort(a: &mut [Order]) { // std.sort.pdq → unstable sort a.sort_unstable_by(|a, b| { if Order::less_than(Order::default(), *a, *b) { @@ -404,7 +404,7 @@ pub struct OutputPieces { impl OutputPieces { #[inline] - pub fn new(pieces: Vec, buffer: Box<[u8]>) -> Self { + pub(crate) fn new(pieces: Vec, buffer: Box<[u8]>) -> Self { OutputPieces { pieces, _buffer: buffer, @@ -412,19 +412,14 @@ impl OutputPieces { } #[inline] - pub fn slice(&self) -> &[OutputPiece] { + pub(crate) fn slice(&self) -> &[OutputPiece] { &self.pieces } #[inline] - pub fn len(&self) -> usize { + pub(crate) fn len(&self) -> usize { self.pieces.len() } - - #[inline] - pub fn is_empty(&self) -> bool { - self.pieces.is_empty() - } } pub struct CodeResult { @@ -1087,7 +1082,7 @@ impl IntermediateOutput { /// `RawSlice` (encapsulates the unsafe re-borrow) — the per-chunk piece count /// is bounded by the number of unique-key boundaries, so the extra word per /// piece is negligible against the safety win. -pub struct OutputPiece { +pub(crate) struct OutputPiece { /// Borrows `OutputPieces::_buffer`; `RawSlice` invariant (backing outlives /// holder) is upheld by `OutputPieces` keeping the box alongside `pieces`. data: bun_ptr::RawSlice, @@ -1095,11 +1090,11 @@ pub struct OutputPiece { } impl OutputPiece { - pub fn data(&self) -> &[u8] { + pub(crate) fn data(&self) -> &[u8] { self.data.slice() } - pub fn init(data_slice: &[u8], query: Query) -> OutputPiece { + pub(crate) fn init(data_slice: &[u8], query: Query) -> OutputPiece { OutputPiece { data: bun_ptr::RawSlice::new(data_slice), query, @@ -1161,7 +1156,7 @@ impl QueryKind { /// Single-ASCII-letter tag used in the [`UniqueKey`] wire format. /// `None` has no on-the-wire encoding. #[inline] - pub const fn letter(self) -> u8 { + pub(crate) const fn letter(self) -> u8 { match self { QueryKind::Asset => b'A', QueryKind::Chunk => b'C', @@ -1173,7 +1168,7 @@ impl QueryKind { /// Inverse of [`letter`]; used by the output-piece scanner. #[inline] - pub const fn from_letter(b: u8) -> Option { + pub(crate) const fn from_letter(b: u8) -> Option { match b { b'A' => Some(QueryKind::Asset), b'C' => Some(QueryKind::Chunk), @@ -1185,9 +1180,9 @@ impl QueryKind { } /// Length of the lowercase-hex `unique_key` prefix (16 nibbles of a `u64`). -pub const UNIQUE_KEY_PREFIX_LEN: usize = 16; +pub(crate) const UNIQUE_KEY_PREFIX_LEN: usize = 16; /// Total byte length of a [`UniqueKey`] on the wire: `hex16 + KIND + idx08`. -pub const UNIQUE_KEY_LEN: usize = UNIQUE_KEY_PREFIX_LEN + 1 + 8; +pub(crate) const UNIQUE_KEY_LEN: usize = UNIQUE_KEY_PREFIX_LEN + 1 + 8; /// 25-byte unique-key wire format `{hex16(prefix)}{KIND}{index:08}` shared by /// every emitter (ParseTask file/napi/sqlite loaders, server-component @@ -1195,7 +1190,7 @@ pub const UNIQUE_KEY_LEN: usize = UNIQUE_KEY_PREFIX_LEN + 1 + 8; /// scanner (`LinkerContext::break_output_into_pieces`). Mirrors Zig /// `"{f}{LETTER}{d:0>8}"` with `bun.fmt.hexIntLower` byte-for-byte. #[derive(Clone, Copy)] -pub struct UniqueKey { +pub(crate) struct UniqueKey { pub prefix: u64, pub kind: QueryKind, pub index: u32, @@ -1214,8 +1209,6 @@ impl fmt::Display for UniqueKey { } } -pub type OutputPieceIndex = Query; - /// packed struct(u64) { source_index: u32, entry_point_id: u30, is_entry_point: bool, is_html: bool } #[repr(transparent)] #[derive(Clone, Copy, Default, PartialEq, Eq)] @@ -1223,7 +1216,7 @@ pub struct EntryPoint(u64); /// so `EntryPoint` can be a u64 // TODO(port): Rust has no native u30 — using u32 with mask. Zig: `pub const ID = u30;` -pub type EntryPointId = u32; +pub(crate) type EntryPointId = u32; impl EntryPoint { const ENTRY_POINT_ID_MASK: u64 = (1 << 30) - 1; @@ -1391,7 +1384,7 @@ pub enum Layers { impl Layers { #[inline] - pub fn inner(&self) -> &Vec { + pub(crate) fn inner(&self) -> &Vec { match self { Layers::Borrowed(p) => p.get(), Layers::Owned(b) => b, @@ -1408,20 +1401,20 @@ impl Layers { /// (see TODO(port) above re: `'bump`); `BackRef` encapsulates that /// invariant so `inner()`/`to_owned()` deref sites are safe. #[inline] - pub fn borrow(p: core::ptr::NonNull>) -> Self { + pub(crate) fn borrow(p: core::ptr::NonNull>) -> Self { Layers::Borrowed(bun_ptr::BackRef::from(p)) } /// Zig: `bun.ptr.Cow.replace` — drop owned (arena-backed, so no-op) and /// install a fresh owned value. #[inline] - pub fn replace(&mut self, new: Vec) { + pub(crate) fn replace(&mut self, new: Vec) { *self = Layers::Owned(new); } /// Zig: `bun.ptr.Cow.toOwned` — if borrowed, deep-clone into an owned /// list and return `&mut` to it; if already owned, return as-is. - pub fn to_owned(&mut self) -> &mut Vec { + pub(crate) fn to_owned(&mut self) -> &mut Vec { if let Layers::Borrowed(p) = *self { *self = Layers::Owned(p.deep_clone_with(|l| l.clone())); } @@ -1434,7 +1427,7 @@ impl Layers { impl CssImportOrder { // TODO(port): hasher: anytype — Zig hasher protocol has .update([]const u8) - pub fn hash(&self, hasher: &mut H) { + pub(crate) fn hash(&self, hasher: &mut H) { // TODO: conditions, condition_import_records // Zig: bun.writeAnyToHasher(hasher, std.meta.activeTag(this.kind)) — feeds the small-int @@ -1471,12 +1464,17 @@ impl CssImportOrder { } } - pub fn fmt<'a, 'ctx>(&'a self, ctx: &'a LinkerContext<'ctx>) -> CssImportOrderDebug<'a, 'ctx> { + #[allow(dead_code)] + pub(crate) fn fmt<'a, 'ctx>( + &'a self, + ctx: &'a LinkerContext<'ctx>, + ) -> CssImportOrderDebug<'a, 'ctx> { CssImportOrderDebug { inner: self, ctx } } } -pub struct CssImportOrderDebug<'a, 'ctx> { +#[allow(dead_code)] +pub(crate) struct CssImportOrderDebug<'a, 'ctx> { inner: &'a CssImportOrder, // PORT NOTE: split lifetimes — `LinkerContext<'ctx>` is invariant over `'ctx`, // so coupling the borrow lifetime to the struct param (`&'a LinkerContext<'a>`) @@ -1522,7 +1520,8 @@ impl<'a, 'ctx> fmt::Display for CssImportOrderDebug<'a, 'ctx> { } } -pub type ImportsFromOtherChunks = ArrayHashMap; +pub(crate) type ImportsFromOtherChunks = + ArrayHashMap; // TODO(port): CrossChunkImport.Item.List — assuming exported as ItemList from cross_chunk_import module // `Chunk` is bump-arena-allocated (no Drop on free); boxing the large arm // would leak. The CSS/JS chunk size diff is acceptable. diff --git a/src/bundler/HTMLScanner.rs b/src/bundler/HTMLScanner.rs index e4c3b35a465..9f14e7a16a6 100644 --- a/src/bundler/HTMLScanner.rs +++ b/src/bundler/HTMLScanner.rs @@ -16,7 +16,7 @@ bun_core::declare_scope!(HTMLScanner, hidden); // TODO(port): lifetime — `log`/`source` are borrowed for the scanner's lifetime // (LIFETIMES.tsv had no row for this file; classified locally as BORROW_PARAM). -pub struct HTMLScanner<'a> { +pub(crate) struct HTMLScanner<'a> { // arena field dropped — global mimalloc (see PORTING.md §Allocators). pub import_records: Vec, // Zig: ImportRecord.List pub log: &'a mut Log, @@ -24,7 +24,7 @@ pub struct HTMLScanner<'a> { } impl<'a> HTMLScanner<'a> { - pub fn init(log: &'a mut Log, source: &'a Source) -> HTMLScanner<'a> { + pub(crate) fn init(log: &'a mut Log, source: &'a Source) -> HTMLScanner<'a> { HTMLScanner { import_records: Vec::new(), log, @@ -88,11 +88,11 @@ impl<'a> HTMLScanner<'a> { Ok(()) } - pub fn on_write_html(&mut self, bytes: &[u8]) { + pub(crate) fn on_write_html(&mut self, bytes: &[u8]) { let _ = bytes; // bytes are not written in scan phase } - pub fn on_html_parse_error(&mut self, message: &[u8]) { + pub(crate) fn on_html_parse_error(&mut self, message: &[u8]) { // bun.handleOom → Rust Vec/Box allocations abort on OOM; just call. // Zig `Log.addError` dupes via `log.msgs.allocator`; here `IntoText for // Vec` → `Cow::Owned`, so the Log owns and drops the copy. @@ -101,7 +101,7 @@ impl<'a> HTMLScanner<'a> { .add_error(Some(self.source), Loc::EMPTY, message.to_vec()); } - pub fn on_tag( + pub(crate) fn on_tag( &mut self, _element: &mut lol::Element, path: &[u8], @@ -112,7 +112,7 @@ impl<'a> HTMLScanner<'a> { let _ = self.create_import_record(path, kind); } - pub fn scan(&mut self, input: &[u8]) -> Result<(), Error> { + pub(crate) fn scan(&mut self, input: &[u8]) -> Result<(), Error> { Processor::run(self, input) } } @@ -126,7 +126,7 @@ type Processor<'a> = HTMLProcessor, false>; /// Trait capturing the duck-typed methods Zig's `HTMLProcessor` calls on `T`. /// Zig used `anytype`-style structural calls; Rust needs an explicit bound. -pub trait HTMLProcessorHandler { +pub(crate) trait HTMLProcessorHandler { fn on_tag( &mut self, element: &mut lol::Element, @@ -169,7 +169,7 @@ impl<'a> HTMLProcessorHandler for HTMLScanner<'a> { } } -pub struct HTMLProcessor(PhantomData); +pub(crate) struct HTMLProcessor(PhantomData); #[derive(Clone, Copy)] pub struct TagHandler { @@ -202,7 +202,7 @@ impl TagHandler { } } -pub const TAG_HANDLERS: [TagHandler; 16] = [ +pub(crate) const TAG_HANDLERS: [TagHandler; 16] = [ // Module scripts with src TagHandler::new(b"script[src]", false, b"src", ImportKind::Stmt), // CSS Stylesheets @@ -376,7 +376,7 @@ fn lol_err(_: lol::Error) -> Error { impl HTMLProcessor { - pub fn run(this: &mut T, input: &[u8]) -> Result<(), Error> { + pub(crate) fn run(this: &mut T, input: &[u8]) -> Result<(), Error> { let this_ptr: *mut T = this; let builder = lol::HTMLRewriterBuilder::init(); diff --git a/src/bundler/LinkerContext.rs b/src/bundler/LinkerContext.rs index 81ee5c30f0d..91e3c4735bc 100644 --- a/src/bundler/LinkerContext.rs +++ b/src/bundler/LinkerContext.rs @@ -93,7 +93,7 @@ bun_crash_handler::link_impl_BundleGenerateChunkCtx! { /// Helper for call-sites that previously wrote `Action::BundleGenerateChunk(.{...})`. #[cfg(feature = "show_crash_trace")] #[inline] -pub fn bundle_generate_chunk_action( +pub(crate) fn bundle_generate_chunk_action( ctx: &LinkerContext, chunk: &Chunk, part_range: &PartRange, @@ -110,15 +110,6 @@ pub fn bundle_generate_chunk_action( part_range: core::ptr::from_ref::(part_range).cast::<()>(), }) } -#[cfg(not(feature = "show_crash_trace"))] -#[inline] -pub fn bundle_generate_chunk_action( - _ctx: &LinkerContext, - _chunk: &Chunk, - _part_range: &PartRange, -) -> bun_crash_handler::Action { - bun_crash_handler::Action::BundleGenerateChunk(()) -} // Scoped-log wrappers (LinkerContext.zig:2, :2705); re-exported so `linker_context/*` submodules import directly. bun_core::define_scoped_log!(debug, crate::linker_context_mod::LinkerCtx); @@ -1292,7 +1283,7 @@ impl<'a> LinkerContext<'a> { } #[derive(Clone, Copy, PartialEq, Eq)] -pub enum ScanCssImportsResult { +pub(crate) enum ScanCssImportsResult { Ok, Errors, } @@ -1627,7 +1618,7 @@ pub struct MatchImport { } #[derive(Default, Clone, Copy, PartialEq, Eq)] -pub enum MatchImportKind { +pub(crate) enum MatchImportKind { /// The import is either external or undefined #[default] Ignore, @@ -1651,7 +1642,7 @@ pub struct ChunkMeta { pub dynamic_imports: ArrayHashMap, } -pub type ChunkMetaMap = ArrayHashMap; +pub(crate) type ChunkMetaMap = ArrayHashMap; /// PORT NOTE: raw-pointer fields (was `&'a mut`) because `each_ptr` requires /// `Ctx: Sync + Copy` and the same context is observed from every worker @@ -4307,7 +4298,7 @@ pub struct InsideWrapperPrefix { } impl InsideWrapperPrefix { - pub fn init() -> Self { + pub(crate) fn init() -> Self { Self { stmts: Vec::new(), sync_dependencies_end: 0, @@ -4317,7 +4308,7 @@ impl InsideWrapperPrefix { // deinit → Drop (Vec frees automatically); reset is explicit - pub fn reset(&mut self) { + pub(crate) fn reset(&mut self) { self.stmts.clear(); self.sync_dependencies_end = 0; self.has_async_dependency = false; @@ -4328,17 +4319,17 @@ impl InsideWrapperPrefix { // — bun_js_parser AST builder surface not yet stable. impl InsideWrapperPrefix { - pub fn append_non_dependency(&mut self, stmt: Stmt) -> Result<(), AllocError> { + pub(crate) fn append_non_dependency(&mut self, stmt: Stmt) -> Result<(), AllocError> { self.stmts.push(stmt); Ok(()) } - pub fn append_non_dependency_slice(&mut self, stmts: &[Stmt]) -> Result<(), AllocError> { + pub(crate) fn append_non_dependency_slice(&mut self, stmts: &[Stmt]) -> Result<(), AllocError> { self.stmts.extend_from_slice(stmts); Ok(()) } - pub fn append_sync_dependency(&mut self, call_expr: Expr) -> Result<(), AllocError> { + pub(crate) fn append_sync_dependency(&mut self, call_expr: Expr) -> Result<(), AllocError> { self.stmts.insert( self.sync_dependencies_end, Stmt::alloc( @@ -4353,7 +4344,7 @@ impl InsideWrapperPrefix { Ok(()) } - pub fn append_async_dependency( + pub(crate) fn append_async_dependency( &mut self, call_expr: Expr, promise_all_ref: Ref, @@ -4459,7 +4450,7 @@ impl InsideWrapperPrefix { } impl StmtList { - pub fn reset(&mut self) { + pub(crate) fn reset(&mut self) { self.inside_wrapper_prefix.reset(); self.outside_wrapper_prefix.clear(); self.inside_wrapper_suffix.clear(); @@ -4468,7 +4459,7 @@ impl StmtList { // deinit → Drop (Vec fields free automatically) - pub fn init() -> Self { + pub(crate) fn init() -> Self { Self { inside_wrapper_prefix: InsideWrapperPrefix::init(), outside_wrapper_prefix: Vec::new(), @@ -4477,7 +4468,7 @@ impl StmtList { } } - pub fn append_slice(&mut self, list: StmtListWhich, stmts: &[Stmt]) { + pub(crate) fn append_slice(&mut self, list: StmtListWhich, stmts: &[Stmt]) { match list { StmtListWhich::OutsideWrapperPrefix => { self.outside_wrapper_prefix.extend_from_slice(stmts) @@ -4489,7 +4480,7 @@ impl StmtList { } } - pub fn append(&mut self, list: StmtListWhich, stmt: Stmt) { + pub(crate) fn append(&mut self, list: StmtListWhich, stmt: Stmt) { match list { StmtListWhich::OutsideWrapperPrefix => self.outside_wrapper_prefix.push(stmt), StmtListWhich::InsideWrapperSuffix => self.inside_wrapper_suffix.push(stmt), diff --git a/src/bundler/LinkerGraph.rs b/src/bundler/LinkerGraph.rs index 0e203b4d973..75ee8ede134 100644 --- a/src/bundler/LinkerGraph.rs +++ b/src/bundler/LinkerGraph.rs @@ -170,7 +170,7 @@ impl Default for LinkerGraph<'_> { // thin forwarders for call sites that don't have a split in hand. // ────────────────────────────────────────────────────────────────────────── -pub fn runtime_function(named_exports: &[bundled_ast::NamedExports], name: &[u8]) -> Ref { +pub(crate) fn runtime_function(named_exports: &[bundled_ast::NamedExports], name: &[u8]) -> Ref { named_exports[Index::RUNTIME.get() as usize] .get(name) .expect("runtime function must be a named export of the runtime module") @@ -209,7 +209,7 @@ pub fn generate_new_symbol( ref_ } -pub fn top_level_symbol_to_parts<'a>( +pub(crate) fn top_level_symbol_to_parts<'a>( top_level_symbol_to_parts_overlay: &'a [TopLevelSymbolToParts], top_level_symbols_to_parts: &'a [bundled_ast::TopLevelSymbolToParts], id: u32, @@ -224,7 +224,7 @@ pub fn top_level_symbol_to_parts<'a>( &[] } -pub fn add_part_to_file( +pub(crate) fn add_part_to_file( parts: &mut [part::List<'_>], top_level_symbol_to_parts_overlay: &mut [TopLevelSymbolToParts], top_level_symbols_to_parts: &[bundled_ast::TopLevelSymbolToParts], @@ -811,7 +811,7 @@ impl<'a> LinkerGraph<'a> { } impl<'a> State<'a> { - pub fn visit_all(&mut self) { + pub(crate) fn visit_all(&mut self) { for i in 0..self.import_records.len() { self.visit(i); } @@ -930,7 +930,7 @@ impl Default for File { } } -pub type FileList = MultiArrayList; +pub(crate) type FileList = MultiArrayList; bun_collections::multi_array_columns! { pub trait FileColumns for File { diff --git a/src/bundler/ParseTask.rs b/src/bundler/ParseTask.rs index 4e9f5044d34..2e7971a2ed2 100644 --- a/src/bundler/ParseTask.rs +++ b/src/bundler/ParseTask.rs @@ -47,7 +47,7 @@ declare_scope!(ParseTask, hidden); /// `bun.jsc.EventLoopTask` (ParseTask.zig:Result.task). T6 type erased here. #[allow(non_snake_case)] mod EventLoop { - pub type Task = bun_event_loop::ConcurrentTask::ConcurrentTask; + pub(super) type Task = bun_event_loop::ConcurrentTask::ConcurrentTask; } // PORT NOTE: the per-file parse arena is held as `bump: &'static Bump` (the @@ -79,7 +79,7 @@ pub enum ContentsOrFd { } #[derive(Copy, Clone, Eq, PartialEq, strum::IntoStaticStr)] -pub enum ContentsOrFdTag { +pub(crate) enum ContentsOrFdTag { Fd, Contents, } @@ -159,7 +159,7 @@ pub struct WatcherData { impl WatcherData { /// When no files to watch, this encoding is used. - pub const NONE: WatcherData = WatcherData { + pub(crate) const NONE: WatcherData = WatcherData { fd: Fd::INVALID, dir_fd: Fd::INVALID, }; @@ -351,7 +351,7 @@ impl Default for ParseTask { /// # Safety /// `task` must point at the `io_task` intrusive field of a live `ParseTask` /// scheduled by the thread pool, with provenance over the full `ParseTask`. -pub unsafe fn io_task_callback(task: *mut ThreadPoolLib::Task) { +pub(crate) unsafe fn io_task_callback(task: *mut ThreadPoolLib::Task) { // SAFETY: `task` points to `ParseTask.io_task` (intrusive field) — only // ever invoked by the thread pool against a `ParseTask` it scheduled, so // provenance covers the full `ParseTask` and the `&mut` is unique per the @@ -364,7 +364,7 @@ pub unsafe fn io_task_callback(task: *mut ThreadPoolLib::Task) { /// # Safety /// `task` must point at the `task` intrusive field of a live `ParseTask` /// scheduled by the thread pool, with provenance over the full `ParseTask`. -pub unsafe fn task_callback(task: *mut ThreadPoolLib::Task) { +pub(crate) unsafe fn task_callback(task: *mut ThreadPoolLib::Task) { // SAFETY: `task` points to `ParseTask.task` (intrusive field) — see // `io_task_callback` for the dispatch invariant. let parse_task = unsafe { &mut *bun_core::from_field_ptr!(ParseTask, task, task) }; @@ -1736,7 +1736,7 @@ pub mod parse_worker { ); impl BunLogOptions { - pub fn source_line_text(&self) -> &[u8] { + pub(crate) fn source_line_text(&self) -> &[u8] { if !self.source_line_text_ptr.is_null() && self.source_line_text_len > 0 { // SAFETY: genuine FFI — ptr/len are populated by a third-party native // plugin per `bundler_plugin.h`'s `BunLogOptions` ABI. Non-null and @@ -1753,7 +1753,7 @@ pub mod parse_worker { b"" } - pub fn path(&self) -> &[u8] { + pub(crate) fn path(&self) -> &[u8] { if !self.path_ptr.is_null() && self.path_len > 0 { // SAFETY: genuine FFI — ptr/len are populated by a third-party native // plugin per `bundler_plugin.h`'s `BunLogOptions` ABI. Non-null and @@ -1765,7 +1765,7 @@ pub mod parse_worker { b"" } - pub fn message(&self) -> &[u8] { + pub(crate) fn message(&self) -> &[u8] { if !self.message_ptr.is_null() && self.message_len > 0 { // SAFETY: genuine FFI — ptr/len are populated by a third-party native // plugin per `bundler_plugin.h`'s `BunLogOptions` ABI. Non-null and @@ -1777,7 +1777,7 @@ pub mod parse_worker { b"" } - pub fn append(&self, log: &mut Log, namespace: &'static [u8]) { + pub(crate) fn append(&self, log: &mut Log, namespace: &'static [u8]) { // Zig (ParseTask.zig:874-884) passes `this.path()` through and dupes // `source_line_text` via `log.msgs.arena`. `Location.{file,line_text}` // are `&'static [u8]` here; `Log::dupe` copies into Log-owned storage @@ -1828,7 +1828,7 @@ pub mod parse_worker { /// `args_` and `log_options_`, when non-null, must point at live /// `OnBeforeParseArguments` / `BunLogOptions` for the duration of the /// call (the native-plugin FFI contract). - pub unsafe extern "C" fn log_fn( + pub(crate) unsafe extern "C" fn log_fn( args_: *mut OnBeforeParseArguments, log_options_: *mut BunLogOptions, ) { @@ -1848,7 +1848,7 @@ pub mod parse_worker { } #[repr(C)] - pub struct OnBeforeParseResultWrapper { + pub(crate) struct OnBeforeParseResultWrapper { pub original_source: *const u8, pub original_source_len: usize, pub original_source_fd: Fd, @@ -1882,7 +1882,7 @@ pub mod parse_worker { /// `result` must be the `.result` field of a live /// `OnBeforeParseResultWrapper`, with provenance covering the wrapper /// (derived via `addr_of_mut!(wrapper.result)`). - pub unsafe fn get_wrapper( + pub(crate) unsafe fn get_wrapper( result: *mut OnBeforeParseResult, ) -> *mut OnBeforeParseResultWrapper { // SAFETY: result points to OnBeforeParseResultWrapper.result (always @@ -1902,7 +1902,7 @@ pub mod parse_worker { /// `args` and `result_ptr` must point at the live `OnBeforeParseArguments` /// / `OnBeforeParseResultWrapper.result` set up by `OnBeforeParsePlugin::run` /// (the native-plugin FFI contract). - pub unsafe extern "C" fn fetch_source_code( + pub(crate) unsafe extern "C" fn fetch_source_code( args: *mut OnBeforeParseArguments, result_ptr: *mut OnBeforeParseResult, ) -> i32 { @@ -1995,7 +1995,7 @@ pub mod parse_worker { /// constructed by `OnBeforeParsePlugin::run` (called from C++ with that /// pointer). #[unsafe(no_mangle)] - pub unsafe extern "C" fn OnBeforeParseResult__reset(this: *mut OnBeforeParseResult) { + pub(crate) unsafe extern "C" fn OnBeforeParseResult__reset(this: *mut OnBeforeParseResult) { // SAFETY: `this` is the wrapper's `.result` field (caller contract). let wrapper = unsafe { OnBeforeParseResult::get_wrapper(this) }; // SAFETY: called from C++ with valid ptr embedded in wrapper. Operate on @@ -2019,7 +2019,7 @@ pub mod parse_worker { /// `this` must point at the live `OnBeforeParsePlugin` set up by /// `OnBeforeParsePlugin::run` (called from C++ with that pointer). #[unsafe(no_mangle)] - pub unsafe extern "C" fn OnBeforeParsePlugin__isDone( + pub(crate) unsafe extern "C" fn OnBeforeParsePlugin__isDone( this: *mut OnBeforeParsePlugin<'_, '_>, ) -> i32 { // SAFETY: called from C++ with valid ptr. Read via raw pointers (mirrors @@ -2747,7 +2747,7 @@ pub mod parse_worker { // CONCURRENCY: see `task_callback` — `&mut ParseTask` is unique per callback // invocation; all shared state is accessed via `&BundleV2` (read-only) or // the per-OS-thread `Worker` arena. - pub fn run_from_thread_pool(this: &mut ParseTask) { + pub(crate) fn run_from_thread_pool(this: &mut ParseTask) { run_from_thread_pool_impl(this); } diff --git a/src/bundler/PathToSourceIndexMap.rs b/src/bundler/PathToSourceIndexMap.rs index d802823afd4..e8c04ddf2ce 100644 --- a/src/bundler/PathToSourceIndexMap.rs +++ b/src/bundler/PathToSourceIndexMap.rs @@ -30,7 +30,7 @@ pub type Map = StringHashMap; /// Mirrors Zig's `Map.GetOrPutResult` — std `HashMap::entry` doesn't expose /// `found_existing` + value-ptr together, so we hand-roll a thin shim. -pub type GetOrPutResult<'a> = bun_collections::string_hash_map::GetOrPutResult<'a, IndexInt>; +pub(crate) type GetOrPutResult<'a> = bun_collections::string_hash_map::GetOrPutResult<'a, IndexInt>; impl PathToSourceIndexMap { pub fn get_path(&self, path: &impl PathLike) -> Option { diff --git a/src/bundler/ServerComponentParseTask.rs b/src/bundler/ServerComponentParseTask.rs index ac993a5af6c..88335528a1a 100644 --- a/src/bundler/ServerComponentParseTask.rs +++ b/src/bundler/ServerComponentParseTask.rs @@ -29,7 +29,7 @@ pub use crate::ThreadPool; pub use crate::DeferredBatchTask::DeferredBatchTask; pub use crate::parse_task::ParseTask; -pub struct ServerComponentParseTask { +pub(crate) struct ServerComponentParseTask { pub task: ThreadPoolTask, pub data: Data, // BACKREF (LIFETIMES.tsv) — Zig `*BundleV2` is mutable; written through in `on_complete`. @@ -202,12 +202,6 @@ fn task_callback( }) } -impl ServerComponentParseTask { - /// Expose the thread-pool callback so callers can construct - /// `ThreadPoolLib::Task { callback: Self::TASK_CALLBACK }`. - pub const TASK_CALLBACK: fn(*mut ThreadPoolTask) = task_callback_wrap; -} - impl Default for ServerComponentParseTask { /// Mirrors Zig's `task: ThreadPoolLib.Task = .{ .callback = &taskCallbackWrap }` /// default-field-value. Callers (`bundle_v2.rs`) supply `data`/`ctx`/`source` diff --git a/src/bundler/ThreadPool.rs b/src/bundler/ThreadPool.rs index 43116dfa76e..236f17412b9 100644 --- a/src/bundler/ThreadPool.rs +++ b/src/bundler/ThreadPool.rs @@ -34,7 +34,7 @@ bun_core::declare_scope!(ThreadPool, visible); /// `std.Thread.Id` — `bun_threading::current_thread_id()` returns `u64` on /// every platform (`gettid`/`pthread_threadid_np`/`GetCurrentThreadId`). -pub type ThreadId = u64; +pub(crate) type ThreadId = u64; pub struct ThreadPool { /// macOS holds an IORWLock on every file open. @@ -118,7 +118,7 @@ mod io_thread_pool { /// N > 1 means N-1 `ThreadPool`s are using the IO thread pool. static REF_COUNT: AtomicUsize = AtomicUsize::new(0); - pub fn acquire() -> NonNull { + pub(super) fn acquire() -> NonNull { let mut count = REF_COUNT.load(Ordering::Acquire); loop { if count == 0 { @@ -170,12 +170,12 @@ mod io_thread_pool { .expect("UnsafeCell::get is non-null") } - pub fn release() { + pub(super) fn release() { let old = REF_COUNT.fetch_sub(1, Ordering::Release); debug_assert!(old > 1, "IOThreadPool: too many calls to release()"); } - pub fn shutdown() -> bool { + pub(super) fn shutdown() -> bool { // Acquire instead of AcqRel is okay because we only need to ensure that other // threads are done using the IO pool if we read 1 from the ref count. // diff --git a/src/bundler/analyze_transpiled_module.rs b/src/bundler/analyze_transpiled_module.rs index 0d9b2af0aba..8c5b6b30821 100644 --- a/src/bundler/analyze_transpiled_module.rs +++ b/src/bundler/analyze_transpiled_module.rs @@ -28,7 +28,7 @@ pub type RequestedModuleValue = FetchParameters; /// Legacy name used by `linker_context::postProcessJSChunk` — the Zig side /// renamed `ImportAttributes` → `FetchParameters` but the bundler call site /// still spells `ImportAttributes::None`. -pub type ImportAttributes = FetchParameters; +pub(crate) type ImportAttributes = FetchParameters; // ────────────────────────────────────────────────────────────────────────── // RecordKind @@ -453,7 +453,7 @@ fn bytes_as_slice(bytes: &[u8]) -> Result<&[T], Modu /// Extension constructor: `StringID::from_raw(u32)` — used by /// `linker_context::generateChunksInParallel` when rewriting cross-chunk /// specifier IDs. -pub trait StringIDExt { +pub(crate) trait StringIDExt { fn from_raw(raw: u32) -> StringID; } impl StringIDExt for StringID { @@ -536,7 +536,7 @@ impl ModuleInfoExt for ModuleInfo { // (Zig `comptime { _ = @import }` force-reference dropped per porting guide.) #[unsafe(no_mangle)] -pub extern "C" fn zig__ModuleInfo__destroy(info: *mut ModuleInfo) { +pub(crate) extern "C" fn zig__ModuleInfo__destroy(info: *mut ModuleInfo) { // SAFETY: C++ caller passes a non-null pointer obtained from `ModuleInfo::create`. let info = unsafe { NonNull::new(info).unwrap_unchecked() }; // SAFETY: `info` came from `bun_core::heap::into_raw` and ownership is transferred back here. @@ -544,7 +544,7 @@ pub extern "C" fn zig__ModuleInfo__destroy(info: *mut ModuleInfo) { } #[unsafe(no_mangle)] -pub extern "C" fn zig__ModuleInfoDeserialized__deinit(info: *mut ModuleInfoDeserialized) { +pub(crate) extern "C" fn zig__ModuleInfoDeserialized__deinit(info: *mut ModuleInfoDeserialized) { // SAFETY: C++ caller passes a non-null pointer obtained from `create` or // `ModuleInfoExt::into_deserialized`. let info = unsafe { NonNull::new(info).unwrap_unchecked() }; @@ -553,7 +553,7 @@ pub extern "C" fn zig__ModuleInfoDeserialized__deinit(info: *mut ModuleInfoDeser } #[unsafe(no_mangle)] -pub extern "C" fn zig_log(msg: *const c_char) { +pub(crate) extern "C" fn zig_log(msg: *const c_char) { // SAFETY: C++ caller passes a non-null, NUL-terminated C string. let msg = unsafe { NonNull::new(msg.cast_mut()).unwrap_unchecked() }; // SAFETY: `msg` is non-null and points to a NUL-terminated C string per the contract above. diff --git a/src/bundler/barrel_imports.rs b/src/bundler/barrel_imports.rs index befa49b5ba7..c58fcf28a43 100644 --- a/src/bundler/barrel_imports.rs +++ b/src/bundler/barrel_imports.rs @@ -36,7 +36,7 @@ impl RequestedExports { /// `get_or_put`-shaped entry on the dense `Vec>` storage. /// Returns `(found_existing, &mut value)`; inserts `Default` when absent. #[inline] - pub fn entry(map: &mut Vec>, idx: u32) -> (bool, &mut Self) { + pub(crate) fn entry(map: &mut Vec>, idx: u32) -> (bool, &mut Self) { let i = idx as usize; if i >= map.len() { map.resize_with(i + 1, || None); @@ -47,7 +47,7 @@ impl RequestedExports { } #[inline] - pub fn lookup(map: &[Option], idx: u32) -> Option<&Self> { + pub(crate) fn lookup(map: &[Option], idx: u32) -> Option<&Self> { map.get(idx as usize).and_then(Option::as_ref) } } @@ -92,7 +92,10 @@ fn resolve_barrel_export( /// 3. It is not an export star target of another barrel. /// /// Export * records are never deferred (always resolved) to avoid circular races. -pub fn apply_barrel_optimization(this: &mut BundleV2, parse_result: &mut parse_task::Result) { +pub(crate) fn apply_barrel_optimization( + this: &mut BundleV2, + parse_result: &mut parse_task::Result, +) { // bun.handleOom: Rust aborts on OOM via the global arena; unwrap is for // bun_collections ops that still surface AllocError. apply_barrel_optimization_impl(this, parse_result).expect("OOM"); @@ -362,7 +365,7 @@ fn resolve_barrel_records( /// to un-defer needed records. Un-deferred records are re-resolved through /// resolveImportRecords (same path as initial resolution). /// Returns the number of newly scheduled parse tasks. -pub fn schedule_barrel_deferred_imports( +pub(crate) fn schedule_barrel_deferred_imports( this: &mut BundleV2, result_source_index: u32, result_ast_target: bun_ast::Target, diff --git a/src/bundler/bundle_v2.rs b/src/bundler/bundle_v2.rs index 46fa55abf49..a02d010eb91 100644 --- a/src/bundler/bundle_v2.rs +++ b/src/bundler/bundle_v2.rs @@ -158,7 +158,7 @@ bun_core::declare_scope!(scan_counter, visible); /// `bundle_v2.zig` `ResolveQueue = std.StringArrayHashMap(*ParseTask)`. /// Values are raw `*mut ParseTask` (arena-owned by `graph.heap`); the map only /// dedups by path during a single `on_parse_task_complete` pass. -pub type ResolveQueue = StringHashMap<*mut ParseTask>; +pub(crate) type ResolveQueue = StringHashMap<*mut ParseTask>; /// `bundle_v2.zig:BakeOptions`. pub struct BakeOptions<'a> { @@ -418,7 +418,7 @@ pub mod bv2_impl { pub kind: CacheKind, } /// Mirrors src/bake/DevServer.zig `ASSET_PREFIX` (= INTERNAL_PREFIX ++ "/asset" = "/_bun/asset"). - pub const ASSET_PREFIX: &str = "/_bun/asset"; + pub(crate) const ASSET_PREFIX: &str = "/_bun/asset"; /// Mirrors src/bake/bake.zig:355 `BuiltInModule = union(enum)`. TYPE_ONLY moved /// down to bundler (T5); bake (in runtime, T6) constructs values of this type. @@ -591,7 +591,7 @@ pub mod bv2_impl { /// Mirrors src/bake/bake.zig:936 `server_virtual_source` / :942 `client_virtual_source`. /// `bun_ast::Source` is not `const`-constructible (owns a `fs::Path`), so these /// are lazy statics. PERF(port): was `pub const` in Zig. - pub static SERVER_VIRTUAL_SOURCE: std::sync::LazyLock = + pub(crate) static SERVER_VIRTUAL_SOURCE: std::sync::LazyLock = std::sync::LazyLock::new(|| { // Port of `Fs.Path.initForKitBuiltIn("bun", "bake/server")` (fs.zig:1992) — // inlined because `bun_paths::fs::Path<'static>` is the local TYPE_ONLY stub and @@ -608,7 +608,7 @@ pub mod bv2_impl { ..Default::default() } }); - pub static CLIENT_VIRTUAL_SOURCE: std::sync::LazyLock = + pub(crate) static CLIENT_VIRTUAL_SOURCE: std::sync::LazyLock = std::sync::LazyLock::new(|| bun_ast::Source { path: bun_paths::fs::Path { pretty: b"bun:bake/client", @@ -620,8 +620,6 @@ pub mod bv2_impl { index: bun_ast::Index(crate::Index::BAKE_CLIENT_DATA.get()), ..Default::default() }); - /// Alias kept for callers that referenced the DevServer constant name directly. - pub const DEV_SERVER_ASSET_PREFIX: &str = ASSET_PREFIX; /// Canonical port of src/bake/production.zig:844 `EntryPointMap`. /// Lives in the bundler (lower tier) so both `bun_runtime::bake::production` @@ -1482,7 +1480,7 @@ pub mod bv2_impl { /// `Watcher.enableHotModuleReloading(this, null)` for `bun build --watch`. #[inline] - pub fn enable_hot_module_reloading_for_bundler(bv2: *mut super::BundleV2<'_>) { + pub(crate) fn enable_hot_module_reloading_for_bundler(bv2: *mut super::BundleV2<'_>) { let bv2 = core::ptr::NonNull::new(bv2.cast::>()) .expect("BundleV2 watcher: bv2 is non-null"); // SAFETY: link-time-resolved Rust-ABI fn in `bun_jsc::hot_reloader`. @@ -4347,7 +4345,7 @@ pub mod bv2_impl { BundleV2::on_resolve(unsafe { &mut *resolve }, unsafe { &mut *this }); } - pub fn on_load_from_js_loop(load: &mut jsc_api::JSBundler::Load) { + pub(crate) fn on_load_from_js_loop(load: &mut jsc_api::JSBundler::Load) { // SAFETY: `bv2` is a live backref set in `Load::init`. let bv2 = unsafe { &mut *load.bv2 }; BundleV2::on_load(load, bv2); @@ -4538,7 +4536,7 @@ pub mod bv2_impl { } } - pub fn on_resolve_from_js_loop(resolve: &mut jsc_api::JSBundler::Resolve) { + pub(crate) fn on_resolve_from_js_loop(resolve: &mut jsc_api::JSBundler::Resolve) { // SAFETY: `bv2` is a live backref set in `Resolve::init`. let bv2 = unsafe { &mut *resolve.bv2 }; BundleV2::on_resolve(resolve, bv2); @@ -7575,17 +7573,6 @@ pub mod bv2_impl { free: |ctx, buf, a, ra| ExternalFreeFunctionAllocator::free(ctx, buf, a, ra), }; - /// Returns true if `arena` definitely has a valid `.ptr`. - /// May return false even if `.ptr` is valid. - /// - /// This function should check whether `arena` matches any internal arena types known to - /// have valid pointers. Allocators defined outside of this file, like `std.heap.ArenaAllocator`, - /// don't need to be checked. - pub fn allocator_has_pointer(arena: &bun_alloc::StdAllocator) -> bool { - // bundle_v2.zig:4443 — vtable identity check. - core::ptr::eq(arena.vtable, &raw const EXTERNAL_FREE_VTABLE) - } - // LAYERING: `BuildResult` / `BundleV2Result` are defined once in // `BundleThread.rs` (the trait that consumes them lives there). The previous // duplicate here meant `CompletionStruct::set_result` and `BundleV2:: @@ -7597,7 +7584,6 @@ pub mod bv2_impl { // re-exports pub use crate::HTMLScanner::HTMLScanner; pub use crate::IndexStringMap::IndexStringMap; - pub type BitSet = DynamicBitSetUnmanaged; pub use bun_ast::Loc; // C++ binding for lazy metafile getter (defined in BundlerMetafile.cpp) diff --git a/src/bundler/bundled_ast.rs b/src/bundler/bundled_ast.rs index f123d61f0c8..02a103c1daf 100644 --- a/src/bundler/bundled_ast.rs +++ b/src/bundler/bundled_ast.rs @@ -21,11 +21,11 @@ pub use bun_css::BundlerStyleSheet; /// the type system. `StoreRef`'s `Deref`/`DerefMut` encapsulate the single /// documented `unsafe` deref justified by that invariant; callers use `&*r` /// (or `Option::as_deref`) instead of open-coded `unsafe { &*ptr }`. -pub type CssAstRef = bun_ast::StoreRef; +pub(crate) type CssAstRef = bun_ast::StoreRef; /// Element type of the `css` SoA column (`items_css()`). Exposed so bundler /// call sites can name the column without re-spelling the pointer shape. -pub type CssCol = Option; +pub(crate) type CssCol = Option; use bun_ast::import_record; use bun_core::strings; @@ -34,10 +34,9 @@ use bun_ast::ast_result::Ast; use bun_ast::{CharFreq, ExportsKind, Ref, Scope, SlotCounts, StoreStr, TlaCheck}; use bun_ast::{part, symbol}; -pub type CommonJSNamedExports = bun_ast::ast_result::CommonJSNamedExports; -pub type ConstValuesMap = bun_ast::ast_result::ConstValuesMap; -pub type NamedExports = bun_ast::ast_result::NamedExports; -pub type NamedImports = bun_ast::ast_result::NamedImports; +pub(crate) type CommonJSNamedExports = bun_ast::ast_result::CommonJSNamedExports; +pub(crate) type NamedExports = bun_ast::ast_result::NamedExports; +pub(crate) type NamedImports = bun_ast::ast_result::NamedImports; pub type TopLevelSymbolToParts = bun_ast::ast_result::TopLevelSymbolToParts; // PORT NOTE: Zig stores `MultiArrayList(BundledAst)` on `Graph.ast` / diff --git a/src/bundler/lib.rs b/src/bundler/lib.rs index 3785caf4ec7..e45b28b0d71 100644 --- a/src/bundler/lib.rs +++ b/src/bundler/lib.rs @@ -255,10 +255,6 @@ pub mod options { /// Re-export of the canonical def in `crate::bake_types` (bundle_v2.rs). pub use crate::bake_types::Side; - /// Name used by `resolver/package_json.rs::load_define_defaults` — - /// alias of the canonical `options_impl::EnvEntry` brought in via the glob. - pub type EnvDefault = EnvEntry; - /// Legacy `options::Framework` (referenced by `resolver/package_json.zig`'s /// `FrameworkRouterPair`). The full struct is `bun.bake.Framework` which /// lives in a higher-tier crate; minimal real struct lives in `bake_types`. diff --git a/src/bundler/linker.rs b/src/bundler/linker.rs index 39c0bcdf706..20c38df88bf 100644 --- a/src/bundler/linker.rs +++ b/src/bundler/linker.rs @@ -33,9 +33,6 @@ pub enum CSSResolveError { } bun_core::named_error_set!(CSSResolveError); -pub type OnImportCallback = - fn(resolve_result: &resolver::Result, import_record: &mut ImportRecord, origin: &URL<'_>); - type HashedFileNameMap = HashMap; // PORT NOTE: `_transpiler.Transpiler.isCacheEnabled` is gated in the draft body @@ -68,7 +65,7 @@ pub struct Linker { pub plugin_runner: Option<*mut dyn PluginResolver>, } -pub const RUNTIME_SOURCE_PATH: &[u8] = b"bun:wrap"; +pub(crate) const RUNTIME_SOURCE_PATH: &[u8] = b"bun:wrap"; #[derive(Default)] pub struct TaggedResolution { @@ -91,7 +88,7 @@ pub struct TaggedResolution { // fallback under a `LazyLock` instead — same lifetime semantics // (process-static, never freed), just not BSS-backed. Swap to the macro once // the crate-level feature flag lands. -pub type ImportPathsList = bun_alloc::BSSStringList<{ 512 * 2 }, { 128 + 1 }>; +pub(crate) type ImportPathsList = bun_alloc::BSSStringList<{ 512 * 2 }, { 128 + 1 }>; /// `Send + Sync` newtype around the leaked `BSSStringList` heap allocation so /// it can sit inside a `LazyLock`. The underlying list serializes its own @@ -124,14 +121,14 @@ fn relative_paths_list_ptr() -> *mut ImportPathsList { mod hardcoded_module { use super::*; #[derive(Default, Clone, Copy)] - pub struct AliasOptions { + pub(super) struct AliasOptions { pub rewrite_jest_for_tests: bool, } - pub struct Alias { + pub(super) struct Alias { pub path: &'static [u8], pub tag: ImportRecordTag, } - pub fn get(name: &[u8], target: BundleTarget, opts: AliasOptions) -> Option { + pub(super) fn get(name: &[u8], target: BundleTarget, opts: AliasOptions) -> Option { bun_resolve_builtins::Alias::get( name, target, diff --git a/src/bundler/linker_context/computeCrossChunkDependencies.rs b/src/bundler/linker_context/computeCrossChunkDependencies.rs index c75ac58db3e..92507d00716 100644 --- a/src/bundler/linker_context/computeCrossChunkDependencies.rs +++ b/src/bundler/linker_context/computeCrossChunkDependencies.rs @@ -84,7 +84,7 @@ pub fn compute_cross_chunk_dependencies( compute_cross_chunk_dependencies_with_chunk_metas(c, chunks, &mut chunk_metas) } -pub struct CrossChunkDependencies<'a, 'bump> { +pub(crate) struct CrossChunkDependencies<'a, 'bump> { chunk_meta: &'a mut [ChunkMeta], // PORT NOTE: `BackRef` — the same `[Chunk]` slice is also iterated mutably by // the caller's sequential `walk` loop; `walk` only reads `chunks[other].unique_key` @@ -125,7 +125,7 @@ impl<'a, 'bump> CrossChunkDependencies<'a, 'bump> { // membership — debug-asserted in `assign_chunk_index`). // Reads `ctx`/`chunks`/SoA columns shared. Never forms `&mut // LinkerContext` (`ctx` is a `BackRef`, deref'd to `&`). - pub fn walk(&mut self, chunk: &mut Chunk, chunk_index: usize) { + pub(crate) fn walk(&mut self, chunk: &mut Chunk, chunk_index: usize) { let deps = self; // `ctx` / `chunks` are `BackRef`s into `LinkerContext` / the caller's chunk // slice, valid for the link pass (see PORT NOTE on the struct fields). diff --git a/src/bundler/linker_context/findImportedFilesInCSSOrder.rs b/src/bundler/linker_context/findImportedFilesInCSSOrder.rs index bfad521bbeb..8e7e9e55153 100644 --- a/src/bundler/linker_context/findImportedFilesInCSSOrder.rs +++ b/src/bundler/linker_context/findImportedFilesInCSSOrder.rs @@ -105,7 +105,7 @@ pub fn find_imported_files_in_css_order<'a>( BStr::new(&sources[source_index.get() as usize].path.pretty) } - pub fn visit( + pub(crate) fn visit( &mut self, source_index: Index, wrapping_conditions: &mut Vec, @@ -835,7 +835,7 @@ fn import_conditions_are_equal(a: &[ImportConditions], b: &[ImportConditions]) - /// /// Note that all of this deliberately ignores the existence of "@layer" because /// that is handled separately. All of this is only for handling unlayered styles. -pub fn is_conditional_import_redundant( +pub(crate) fn is_conditional_import_redundant( earlier: &Vec, later: &Vec, ) -> bool { diff --git a/src/bundler/options.rs b/src/bundler/options.rs index 2863de3b5fe..4aad43274d4 100644 --- a/src/bundler/options.rs +++ b/src/bundler/options.rs @@ -19,14 +19,14 @@ use std::borrow::Cow; mod analytics { #[allow(non_upper_case_globals)] - pub mod features { + pub(super) mod features { use core::sync::atomic::AtomicUsize; // Zig: `analytics.Features.{define,loaders,macros,external} += n`. // Real statics live in `bun_analytics::features::*` (AtomicUsize). - pub static define: AtomicUsize = AtomicUsize::new(0); - pub static loaders: AtomicUsize = AtomicUsize::new(0); - pub static macros: AtomicUsize = AtomicUsize::new(0); - pub static external: AtomicUsize = AtomicUsize::new(0); + pub(crate) static define: AtomicUsize = AtomicUsize::new(0); + pub(crate) static loaders: AtomicUsize = AtomicUsize::new(0); + pub(crate) static macros: AtomicUsize = AtomicUsize::new(0); + pub(crate) static external: AtomicUsize = AtomicUsize::new(0); } } use enum_map::EnumMap; @@ -55,7 +55,7 @@ pub type LoaderEnumMap = EnumMap; /// `bun.http.MimeType` lives in `bun_http_types` (lower tier), not `bun_http`. mod bun_http { - pub use bun_http_types::MimeType::MimeType; + pub(super) use bun_http_types::MimeType::MimeType; } /// `bun.StringSet` (re-exported for `BundleOptions.bundler_feature_flags`). pub use bun_collections::StringSet; diff --git a/src/bundler/transpiler.rs b/src/bundler/transpiler.rs index aeaf6762ecd..e7994707d25 100644 --- a/src/bundler/transpiler.rs +++ b/src/bundler/transpiler.rs @@ -17,12 +17,12 @@ use bun_router::Router; use crate::options; /// Port of `transpiler.zig:ResolveResults` — keyed by source path hash. -pub type ResolveResults = HashMap; +pub(crate) type ResolveResults = HashMap; /// Port of `transpiler.zig:ResolveQueue` — `std.fifo.LinearFifo(resolver.Result, .Dynamic)`. // PORT NOTE: `bun_collections::LinearFifo>` would be exact, // but `DynamicBuffer` isn't re-exported from `bun_collections` yet. `VecDeque` // is structurally equivalent (growable ring buffer); swap once the re-export lands. -pub type ResolveQueue = std::collections::VecDeque; +pub(crate) type ResolveQueue = std::collections::VecDeque; /// Spec `JSGlobalObject.BunPluginTarget` (JSGlobalObject.zig:265). Defined at /// this tier (lowest crate that needs to name it) and re-exported from @@ -1022,7 +1022,7 @@ use bun_options_types::schema::api; // keep their pre-unification semantics (parser only ever sees a resolved // runtime; options.zig:1199 default). #[inline] -pub fn to_parser_jsx_pragma( +pub(crate) fn to_parser_jsx_pragma( mut p: crate::options_impl::jsx::Pragma, ) -> js_ast::parser::options::JSX::Pragma { use crate::options_impl::jsx::Runtime; @@ -3312,18 +3312,4 @@ enum TransformOutstream { Dir(#[expect(dead_code)] bun_sys::Fd), } -/// Port of `transpiler.zig:374 BuildResolveResultPair`. -#[derive(Default)] -pub struct BuildResolveResultPair { - pub written: usize, - pub input_fd: Option, - pub empty: bool, -} - -/// Port of `transpiler.zig:1405 ServeResult`. -pub struct ServeResult { - pub file: options::OutputFile, - pub mime_type: bun_http_types::MimeType::MimeType, -} - // ported from: src/bundler/transpiler.zig diff --git a/src/bundler/ungate_support.rs b/src/bundler/ungate_support.rs index 59396217477..a8ffc8a5846 100644 --- a/src/bundler/ungate_support.rs +++ b/src/bundler/ungate_support.rs @@ -42,7 +42,7 @@ pub mod perf { pub use bun_perf::{Ctx, PerfEvent}; #[inline] - pub fn trace(_name: &'static str) -> Ctx { + pub(crate) fn trace(_name: &'static str) -> Ctx { bun_perf::trace(PerfEvent::_Stub) } } @@ -151,7 +151,7 @@ pub struct CrossChunkImport { } /// `Chunk.zig:ImportsFromOtherChunks`. pub mod cross_chunk_import { - pub type ItemList = super::CrossChunkImportItemList; + pub(crate) type ItemList = super::CrossChunkImportItemList; } #[repr(u8)] @@ -423,7 +423,7 @@ pub struct ContentHasher { // structs only occupy the type namespace, so the two coexist. bun_core::declare_scope!(ContentHasher, hidden); impl ContentHasher { - pub fn write(&mut self, bytes: &[u8]) { + pub(crate) fn write(&mut self, bytes: &[u8]) { bun_core::scoped_log!( ContentHasher, "HASH_UPDATE {}:\n{}\n----------\n", @@ -433,17 +433,17 @@ impl ContentHasher { self.hasher.update(&(bytes.len() as u64).to_ne_bytes()); self.hasher.update(bytes); } - pub fn run(bytes: &[u8]) -> u64 { + pub(crate) fn run(bytes: &[u8]) -> u64 { let mut h = ContentHasher::default(); h.write(bytes); h.digest() } /// `bundle_v2.zig:ContentHasher.writeInts` — `std.mem.sliceAsBytes(i)`. - pub fn write_ints(&mut self, i: &[u32]) { + pub(crate) fn write_ints(&mut self, i: &[u32]) { bun_core::scoped_log!(ContentHasher, "HASH_UPDATE: {:?}\n", i); self.hasher.update(bytemuck::cast_slice::(i)); } - pub fn digest(&self) -> u64 { + pub(crate) fn digest(&self) -> u64 { self.hasher.digest() } } @@ -486,14 +486,14 @@ pub mod bun_renamer { } impl ChunkRenamer { - pub fn name_for_symbol(&mut self, ref_: bun_ast::Ref) -> &[u8] { + pub(crate) fn name_for_symbol(&mut self, ref_: bun_ast::Ref) -> &[u8] { match self { ChunkRenamer::None => unreachable!("ChunkRenamer not initialized"), ChunkRenamer::Number(r) => r.name_for_symbol(ref_), ChunkRenamer::Minify(r) => r.name_for_symbol(ref_), } } - pub fn as_renamer(&mut self) -> bun_js_printer::renamer::Renamer<'_, '_> { + pub(crate) fn as_renamer(&mut self) -> bun_js_printer::renamer::Renamer<'_, '_> { match self { ChunkRenamer::None => unreachable!("ChunkRenamer not initialized"), ChunkRenamer::Number(r) => bun_js_printer::renamer::Renamer::NumberRenamer(r), @@ -523,7 +523,7 @@ pub mod html_import_manifest { /// literal body (`writePreQuotedString`). Chunk.rs uses this with /// `bun_core::fmt::count` for the counting pass. #[inline] - pub fn format_escaped_json<'a>( + pub(crate) fn format_escaped_json<'a>( index: u32, graph: &'a Graph, chunks: &'a [Chunk], @@ -594,7 +594,7 @@ pub use bun_js_printer::MangledProps; /// `bun.logger` — alias used by the original drafts as `crate::bun_ast::Source`. /// `js_ast.BundledAst` (the bundler-facing AST view). -pub type JSAst<'a> = crate::BundledAst<'a>; +pub(crate) type JSAst<'a> = crate::BundledAst<'a>; pub(crate) use bun_ast::{Part, Ref}; /// `bundle_v2.zig:EntryPoint` — both a struct and (via the sibling module @@ -695,7 +695,7 @@ pub mod js_meta { } } /// Alias used by `LinkerGraph::generate_symbol_import_and_use`. - pub type ImportToBind = ImportData; + pub(crate) type ImportToBind = ImportData; pub struct ExportData { pub potentially_ambiguous_export_star_refs: AstVec, @@ -710,7 +710,7 @@ pub mod js_meta { } } /// Alias used by `LinkerGraph::load`. - pub type ResolvedExport = ExportData; + pub(crate) type ResolvedExport = ExportData; pub type RefImportData = ArrayHashMap; pub type ResolvedExports = StringArrayHashMap; diff --git a/src/bundler_jsc/PluginRunner.rs b/src/bundler_jsc/PluginRunner.rs index acc0354b7b5..fe427df7100 100644 --- a/src/bundler_jsc/PluginRunner.rs +++ b/src/bundler_jsc/PluginRunner.rs @@ -6,7 +6,6 @@ pub use bun_resolver::fs::Path as FsPath; /// Spec `PluginRunner.zig:MacroJSCtx` — re-export of the canonical newtype /// (defined at the lowest tier that stores it, `bun_ast::Macro`). pub use bun_bundler::transpiler::MacroJSCtx as MacroJsCtx; -pub const DEFAULT_MACRO_JS_VALUE: MacroJsCtx = MacroJsCtx::ZERO; /// Spec `PluginRunner.zig:PluginRunner` — re-export of the concrete struct. /// `extract_namespace` / `could_be_plugin` (pure byte parsing) live in diff --git a/src/bundler_jsc/analyze_jsc.rs b/src/bundler_jsc/analyze_jsc.rs index 71e7b58a9cc..831f4718f4f 100644 --- a/src/bundler_jsc/analyze_jsc.rs +++ b/src/bundler_jsc/analyze_jsc.rs @@ -13,7 +13,7 @@ use analyze::{ModuleInfoDeserialized, RecordKind, RequestedModuleValue, StringID use bun_bundler::analyze_transpiled_module as analyze; #[unsafe(no_mangle)] -pub extern "C" fn zig__ModuleInfoDeserialized__toJSModuleRecord( +pub(crate) extern "C" fn zig__ModuleInfoDeserialized__toJSModuleRecord( global_object: &JSGlobalObject, vm: &VM, module_key: &IdentifierArray, @@ -263,8 +263,8 @@ impl IdentifierArray { } bun_opaque::opaque_ffi! { - pub struct SourceCode; - pub struct JSModuleRecord; + pub(crate) struct SourceCode; + pub(crate) struct JSModuleRecord; } unsafe extern "C" { fn JSC_JSModuleRecord__create( @@ -279,13 +279,6 @@ unsafe extern "C" { has_tla: bool, ) -> *mut JSModuleRecord; - fn JSC_JSModuleRecord__declaredVariables( - module_record: *mut JSModuleRecord, - ) -> *mut VariableEnvironment; - fn JSC_JSModuleRecord__lexicalVariables( - module_record: *mut JSModuleRecord, - ) -> *mut VariableEnvironment; - fn JSC_JSModuleRecord__addIndirectExport( module_record: *mut JSModuleRecord, identifier_array: *mut IdentifierArray, @@ -374,7 +367,7 @@ unsafe extern "C" { } impl JSModuleRecord { #[inline] - pub fn create( + pub(crate) fn create( global_object: &JSGlobalObject, vm: &VM, module_key: &IdentifierArray, @@ -400,20 +393,6 @@ impl JSModuleRecord { ) } } - // Forwards `this` to C++ without dereferencing; not_unsafe_ptr_arg_deref is a false positive on opaque-token forwarding. - #[allow(clippy::not_unsafe_ptr_arg_deref)] - #[inline] - pub fn declared_variables(this: *mut JSModuleRecord) -> *mut VariableEnvironment { - // SAFETY: `this` is a valid JSModuleRecord*. - unsafe { JSC_JSModuleRecord__declaredVariables(this) } - } - // Forwards `this` to C++ without dereferencing; not_unsafe_ptr_arg_deref is a false positive on opaque-token forwarding. - #[allow(clippy::not_unsafe_ptr_arg_deref)] - #[inline] - pub fn lexical_variables(this: *mut JSModuleRecord) -> *mut VariableEnvironment { - // SAFETY: `this` is a valid JSModuleRecord*. - unsafe { JSC_JSModuleRecord__lexicalVariables(this) } - } } // Thin method shims over the raw `*mut JSModuleRecord` returned by `create`. diff --git a/src/bundler_jsc/options_jsc.rs b/src/bundler_jsc/options_jsc.rs index dc25d405255..7fcd92a0b3e 100644 --- a/src/bundler_jsc/options_jsc.rs +++ b/src/bundler_jsc/options_jsc.rs @@ -5,7 +5,6 @@ // from the lower-tier source crate directly. use bun_core::ZigString; use bun_jsc::ComptimeStringMapExt as _; -use bun_options_types::bundle_enums::Format; use bun_options_types::compile_target::CompileTarget; use crate::{JSGlobalObject, JSValue, JsResult}; @@ -20,22 +19,6 @@ pub fn target_from_js( bun_ast::Target::MAP.from_js(global, value) } -pub fn format_from_js(global: &JSGlobalObject, format: JSValue) -> JsResult> { - if format.is_undefined_or_null() { - return Ok(None); - } - - if !format.is_string() { - return Err(global.throw_invalid_arguments(format_args!("format must be a string"))); - } - - let Some(v) = Format::MAP.from_js(global, format)? else { - return Err(global - .throw_invalid_arguments(format_args!("Invalid format - must be esm, cjs, or iife"))); - }; - Ok(Some(v)) -} - pub fn loader_from_js( global: &JSGlobalObject, loader: JSValue, diff --git a/src/bunfig/bunfig.rs b/src/bunfig/bunfig.rs index fddca2eedd6..8ed18c0faf5 100644 --- a/src/bunfig/bunfig.rs +++ b/src/bunfig/bunfig.rs @@ -144,7 +144,7 @@ fn num_to_u32(n: f64) -> u32 { // Parser // ───────────────────────────────────────────────────────────────────────────── -pub struct Parser<'a> { +pub(crate) struct Parser<'a> { json: Expr, source: &'a bun_ast::Source, log: &'a mut bun_ast::Log, @@ -188,7 +188,7 @@ impl<'a> Parser<'a> { Err(err!("Invalid Bunfig")) } - pub fn expect_string(&mut self, expr: &Expr) -> Result<(), bun_core::Error> { + pub(crate) fn expect_string(&mut self, expr: &Expr) -> Result<(), bun_core::Error> { match &expr.data { ExprData::EString(_) => Ok(()), _ => self.add_error_format( @@ -216,7 +216,7 @@ impl<'a> Parser<'a> { Ok(()) } - pub fn expect(&mut self, expr: &Expr, token: ExprTag) -> Result<(), bun_core::Error> { + pub(crate) fn expect(&mut self, expr: &Expr, token: ExprTag) -> Result<(), bun_core::Error> { if expr.data.tag() != token { return self.add_error_format( expr.loc, @@ -353,7 +353,7 @@ impl<'a> Parser<'a> { // already derives `enum_map::Enum`, which conflicts). The Zig original // monomorphised over `cmd` purely to dead-code-eliminate untaken arms; the // runtime branches below are equivalent and the few hot fields are tiny. - pub fn parse(&mut self, cmd: CommandTag) -> Result<(), bun_core::Error> { + pub(crate) fn parse(&mut self, cmd: CommandTag) -> Result<(), bun_core::Error> { bun_analytics::features::bunfig.fetch_add(1, Ordering::Relaxed); let json = self.json; diff --git a/src/bunfig/lib.rs b/src/bunfig/lib.rs index 2979b021a28..081e628aabf 100644 --- a/src/bunfig/lib.rs +++ b/src/bunfig/lib.rs @@ -8,7 +8,6 @@ //! introduced; this only makes the existing edge direct. #![allow(non_snake_case)] -#![warn(unreachable_pub)] pub mod arguments; pub mod bunfig; diff --git a/src/cares_sys/lib.rs b/src/cares_sys/lib.rs index cb97bc676bd..c3fdfecfacd 100644 --- a/src/cares_sys/lib.rs +++ b/src/cares_sys/lib.rs @@ -6,13 +6,13 @@ pub mod c_ares_draft; /// Winsock typedefs not provided by `libc` on `x86_64-pc-windows-msvc`. #[cfg(windows)] -pub(crate) mod winsock { +pub mod winsock { use core::ffi::{c_int, c_long}; - pub type socklen_t = c_int; // ws2tcpip.h: `typedef int socklen_t;` + pub(crate) type socklen_t = c_int; // ws2tcpip.h: `typedef int socklen_t;` // Same nominal type as `bun_sys::posix::sockaddr*`; sin_addr is `in_addr{s_addr}` // (vs the previous `[u8;4]`) but the only caller (c_ares.rs `get_sockaddr`) // takes `&raw mut → cast`, so the field's nominal type is transparent. - pub use bun_libuv_sys::{sockaddr, sockaddr_in, sockaddr_in6}; + pub(crate) use bun_libuv_sys::{sockaddr, sockaddr_in, sockaddr_in6}; #[repr(C)] #[derive(Clone, Copy)] pub struct timeval { diff --git a/src/clap/comptime.rs b/src/clap/comptime.rs index aba595a2f80..66f8257ff0b 100644 --- a/src/clap/comptime.rs +++ b/src/clap/comptime.rs @@ -147,7 +147,7 @@ pub const fn convert_params_array(params: &[Param]) -> [ /// /// Panics (at const-eval, i.e. a build error) if `name` is not in `converted` /// — matching Zig's `@compileError("no param '…'")`. -pub const fn find_param_index(converted: &[Param], name: &[u8]) -> usize { +pub(crate) const fn find_param_index(converted: &[Param], name: &[u8]) -> usize { if name.len() > 2 && name[0] == b'-' && name[1] == b'-' { let (_, key) = name.split_at(2); let mut i = 0; @@ -243,7 +243,7 @@ pub const fn build_long_index(params: &[Param]) -> [Long } /// `[i16; 128]` ASCII → index into `converted`. `-1` = no such short. -pub const fn build_short_index(converted: &[Param]) -> [i16; 128] { +pub(crate) const fn build_short_index(converted: &[Param]) -> [i16; 128] { let mut idx = [-1i16; 128]; let mut i = 0; while i < converted.len() { @@ -262,7 +262,7 @@ pub const fn build_short_index(converted: &[Param]) -> [i16; 128] { /// FNV-1a 64. `const fn` so `comptime_table!` can pre-hash; also used at /// runtime for the long-name index. #[inline] -pub const fn fnv1a64(bytes: &[u8]) -> u64 { +pub(crate) const fn fnv1a64(bytes: &[u8]) -> u64 { let mut h: u64 = 0xcbf2_9ce4_8422_2325; let mut i = 0; while i < bytes.len() { diff --git a/src/clap/lib.rs b/src/clap/lib.rs index 8e0689501a6..5682f644186 100644 --- a/src/clap/lib.rs +++ b/src/clap/lib.rs @@ -1,5 +1,4 @@ #![warn(unused_must_use)] -#![warn(unreachable_pub)] use core::fmt; use core::fmt::Write as _; diff --git a/src/clap/streaming.rs b/src/clap/streaming.rs index c104aaa734c..4a29582339b 100644 --- a/src/clap/streaming.rs +++ b/src/clap/streaming.rs @@ -10,7 +10,7 @@ use crate::args::ArgIter; pub static WARN_ON_UNRECOGNIZED_FLAG: AtomicBool = AtomicBool::new(false); /// The result returned from StreamingClap.next -pub struct Arg<'p, 'a, Id> { +pub(crate) struct Arg<'p, 'a, Id> { pub param: &'p clap::Param, pub value: Option<&'a [u8]>, } @@ -28,7 +28,7 @@ pub enum State<'a> { } #[derive(thiserror::Error, strum::IntoStaticStr, Debug, Copy, Clone, PartialEq, Eq)] -pub enum ArgError { +pub(crate) enum ArgError { #[error("DoesntTakeValue")] DoesntTakeValue, #[error("MissingValue")] @@ -73,7 +73,7 @@ where ArgIterator: ArgIter<'a>, { /// Get the next Arg that matches a Param. - pub fn next(&mut self) -> Result>, ArgError> { + pub(crate) fn next(&mut self) -> Result>, ArgError> { match self.state { State::Normal => self.normal(), State::Chaining(state) => self.chainging(state), diff --git a/src/codegen/Cargo.toml b/src/codegen/Cargo.toml deleted file mode 100644 index 39e028beec3..00000000000 --- a/src/codegen/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "bun_codegen" -version.workspace = true -edition.workspace = true - -[lib] -path = "lib.rs" - -[lints] -workspace = true - -[dependencies] -strum.workspace = true -phf.workspace = true -bstr.workspace = true -scopeguard.workspace = true -const_format.workspace = true -enum-map.workspace = true -enumset.workspace = true -libc.workspace = true -bitflags.workspace = true -bun_core.workspace = true diff --git a/src/codegen/generate-string-map.ts b/src/codegen/generate-string-map.ts index 5b21f732289..4951d433d20 100644 --- a/src/codegen/generate-string-map.ts +++ b/src/codegen/generate-string-map.ts @@ -137,7 +137,7 @@ function emitLookup( out.push(`#[inline]`); out.push(`#[allow(clippy::all)]`); - out.push(`pub fn ${fnName}(key: &[u8]) -> Option<${retTy}> {`); + out.push(`pub(crate) fn ${fnName}(key: &[u8]) -> Option<${retTy}> {`); out.push(` match key.len() {`); for (const len of lens) { const bucket = buckets.get(len)!; diff --git a/src/codegen/lib.rs b/src/codegen/lib.rs deleted file mode 100644 index bd74742dff1..00000000000 --- a/src/codegen/lib.rs +++ /dev/null @@ -1,9 +0,0 @@ -// Build-time codegen tool — runs on the host before bun_* crates exist. -#![allow( - clippy::disallowed_methods, - clippy::disallowed_types, - clippy::disallowed_macros -)] -#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals)] -#![warn(unused_must_use)] -pub mod process_windows_translate_c; diff --git a/src/codegen/process_windows_translate_c.rs b/src/codegen/process_windows_translate_c.rs deleted file mode 100644 index d53332bf817..00000000000 --- a/src/codegen/process_windows_translate_c.rs +++ /dev/null @@ -1,107 +0,0 @@ -// translate-c is unable to translate the unsuffixed windows functions -// like `SetCurrentDirectory` since they are defined with an odd macro -// that translate-c doesn't handle. -// -// #define SetCurrentDirectory __MINGW_NAME_AW(SetCurrentDirectory) -// -// In these cases, it's better to just reference the underlying function -// directly: SetCurrentDirectoryW. To make the error better, a post -// processing step is applied to the translate-c file. - -use bstr::{BStr, ByteSlice}; -use std::io::Write as _; - -// TODO(port): standalone build-time codegen binary — uses std::env / std::fs::{read,write} -// directly (PORTING.md bans std::fs for runtime code). The Zig original also calls std.fs -// directly (not bun.sys) since this never links into the runtime. Either keep as-is -// for build tooling, or swap to bun_sys::File::read_from / bun_sys::File::write_file. - -static SYMBOL_REPLACEMENTS: phf::Map<&'static [u8], &'static [u8]> = phf::phf_map! { - b"NTSTATUS" => b"@import(\"std\").os.windows.NTSTATUS", - b"HANDLE" => b"@import(\"std\").os.windows.HANDLE", - b"PHANDLE" => b"*HANDLE", -}; - -pub fn main() -> Result<(), bun_core::Error> { - // TODO(port): narrow error set - let mut args = std::env::args(); - assert(args.next().is_some()); // skip argv[0] - - let input: Vec = 'brk: { - let in_path = args.next().unwrap_or_else(|| panic!("missing argument")); - // Zig: openFile + readToEndAllocOptions(.., sentinel 0). Sentinel was only - // needed for std.zig.Tokenizer; the inline scan below doesn't require it. - break 'brk std::fs::read(&in_path).map_err(|_| bun_core::err!("ReadFailed"))?; - }; - let in_bytes: &[u8] = &input; - - let mut out: Vec = Vec::with_capacity(in_bytes.len()); - - let mut i: usize = 0; - while let Some(pub_i) = index_of_pos(in_bytes, i, b"pub const ") { - // TODO(port): std.zig.Tokenizer replaced with an inline ASCII identifier scan. - // translate-c emits plain `[A-Za-z_][A-Za-z0-9_]*` identifiers here; verify the - // `@"…"` raw-identifier form never appears after `pub const ` in the input. - let symbol_start = pub_i + b"pub const ".len(); - let symbol_end = symbol_start - + in_bytes[symbol_start..] - .iter() - .position(|&b| !(b.is_ascii_alphanumeric() || b == b'_')) - .unwrap_or(in_bytes.len() - symbol_start); - assert(symbol_end > symbol_start); // Zig: assert(symbol_name_token.tag == .identifier) - let symbol_name = &in_bytes[symbol_start..symbol_end]; - - out.extend_from_slice(&in_bytes[i..symbol_end]); - i = symbol_end; - - let mut end_of_line = - index_of_scalar_pos(in_bytes, symbol_end, b'\n').unwrap_or(in_bytes.len()); - if in_bytes[end_of_line - 1] != b';' { - // skip multiline decl - out.extend_from_slice(&in_bytes[i..end_of_line]); - i = end_of_line; - continue; - } - end_of_line += 1; // include the \n - - if let Some(replace) = SYMBOL_REPLACEMENTS.get(symbol_name) { - writeln!(&mut out, " = {};", BStr::new(replace)).expect("unreachable"); - } else if in_bytes[i..].starts_with(b" = __MINGW_NAME_AW(") { - writeln!( - &mut out, - " = @compileError(\"Use '{}W' instead.\");", - BStr::new(symbol_name), - ) - .expect("unreachable"); - } else { - out.extend_from_slice(&in_bytes[i..end_of_line]); - } - i = end_of_line; - } - out.extend_from_slice(&in_bytes[i..]); - - let out_path = args.next().unwrap_or_else(|| panic!("missing argument")); - use bun_core::OrWriteFailed as _; - std::fs::write(&out_path, &out).or_write_failed()?; - Ok(()) -} - -fn assert(cond: bool) { - if !cond { - panic!("unhandled"); - } -} - -// Cold-path helpers mirroring std.mem.indexOfPos / indexOfScalarPos. -fn index_of_pos(haystack: &[u8], start: usize, needle: &[u8]) -> Option { - haystack[start..].find(needle).map(|p| start + p) -} - -fn index_of_scalar_pos(haystack: &[u8], start: usize, scalar: u8) -> Option { - haystack[start..] - .iter() - .position(|&b| b == scalar) - .map(|p| start + p) -} - -// ported from: src/codegen/process_windows_translate_c.zig diff --git a/src/collections/array_list.rs b/src/collections/array_list.rs index 0d38c6766bb..4446c5afa8d 100644 --- a/src/collections/array_list.rs +++ b/src/collections/array_list.rs @@ -64,7 +64,7 @@ pub struct ArrayListAlignedIn { } /// Zig: `Unmanaged = std.ArrayListAlignedUnmanaged(T, alignment)` -pub type Unmanaged = Vec; +pub(crate) type Unmanaged = Vec; /// Zig: `Slice = Unmanaged.Slice` (= `[]align(alignment) T`, an owned slice when detached). // TODO(port): Zig `Slice` is used both as a borrow (`items()`) and as an owned return diff --git a/src/collections/bit_set.rs b/src/collections/bit_set.rs index 1c571bb8cc5..28ca40fd3d0 100644 --- a/src/collections/bit_set.rs +++ b/src/collections/bit_set.rs @@ -790,11 +790,6 @@ pub struct DynamicBitSetUnmanaged { // fails. } -/// The integer type used to represent a mask in this bit set -pub type DynMaskInt = usize; -/// The integer type used to shift a mask in this bit set -pub type DynShiftInt = u32; - const DYN_MASK_BITS: u32 = usize::BITS; // Never modified — the Zig comment about needing `static mut` was a Zig @@ -1438,9 +1433,10 @@ unsafe fn dyn_realloc( // ───────────────────────────── AutoBitSet ───────────────────────────── /// Static arm size: `@bitSizeOf(DynamicBitSetUnmanaged) - 1`. -pub const AUTO_STATIC_BITS: usize = mem::size_of::() * 8 - 1; +pub(crate) const AUTO_STATIC_BITS: usize = mem::size_of::() * 8 - 1; -pub type AutoBitSetStatic = ArrayBitSet; +pub(crate) type AutoBitSetStatic = + ArrayBitSet; pub enum AutoBitSet { Static(AutoBitSetStatic), @@ -1557,7 +1553,7 @@ impl AutoBitSet { // (see ArrayBitSet::iterator / DynamicBitSetUnmanaged::iterator), so the // wrapper enum was a no-op layer of indirection. Keep the public name as a // type alias for any external callers. -pub type AutoBitSetIterator<'a, const KIND_SET: bool, const DIR_FWD: bool> = +pub(crate) type AutoBitSetIterator<'a, const KIND_SET: bool, const DIR_FWD: bool> = BitSetIterator<'a, KIND_SET, DIR_FWD>; impl Drop for AutoBitSet { diff --git a/src/collections/hive_array.rs b/src/collections/hive_array.rs index 92f5230eb5b..20761f9a912 100644 --- a/src/collections/hive_array.rs +++ b/src/collections/hive_array.rs @@ -790,9 +790,6 @@ pub struct HiveRef { pub value: T, } -/// Convenience alias mirroring Zig's nested `const HiveAllocator`. -pub type HiveAllocator = Fallback, CAPACITY>; - impl HiveRef { /// Zig: `pub fn init(value, allocator) !*@This()`. /// @@ -1250,7 +1247,7 @@ mod tests { let drops = core::cell::Cell::new(0u32); const CAP: usize = 2; - type Pool<'c> = HiveAllocator, CAP>; + type Pool<'c> = Fallback, CAP>, CAP>; let pool: Pool = Fallback::init(); let pool_ptr: *const Pool = &pool; @@ -1322,7 +1319,7 @@ mod tests { let drops = core::cell::Cell::new(0u32); const CAP: usize = 1; - type Pool<'c> = HiveAllocator, CAP>; + type Pool<'c> = Fallback, CAP>, CAP>; let pool: Pool = Fallback::init(); let pool_ptr: *const Pool = &pool; diff --git a/src/collections/lib.rs b/src/collections/lib.rs index 2f1da109c68..709b79818ea 100644 --- a/src/collections/lib.rs +++ b/src/collections/lib.rs @@ -11,9 +11,7 @@ allocator_api )] #![allow(incomplete_features, internal_features)] -#![warn(unused_must_use, unreachable_pub)] - -extern crate self as bun_collections; +#![warn(unused_must_use)] pub mod hive_array; pub mod multi_array_list; diff --git a/src/collections/multi_array_list.rs b/src/collections/multi_array_list.rs index bb386e97588..43061c51d03 100644 --- a/src/collections/multi_array_list.rs +++ b/src/collections/multi_array_list.rs @@ -246,7 +246,7 @@ macro_rules! __mal_column_impl { /// cached in fixed-size `[_; MAX_FIELDS]` arrays so `Slice` can be a plain /// value type without a `where [(); field_count::()]:` bound propagating to /// every caller. -pub const MAX_FIELDS: usize = 32; +pub(crate) const MAX_FIELDS: usize = 32; // ──────────────────────── const-eval reflection helpers ─────────────────── @@ -270,7 +270,7 @@ const fn fields_of() -> &'static [core::mem::type_info::Field] { /// Number of fields in `T`. #[inline(always)] -pub const fn field_count() -> usize { +pub(crate) const fn field_count() -> usize { fields_of::().len() } diff --git a/src/collections/pool.rs b/src/collections/pool.rs index fe268da0818..f23dde33c12 100644 --- a/src/collections/pool.rs +++ b/src/collections/pool.rs @@ -369,7 +369,7 @@ where // generic `impl`; storage is supplied via the `S: PoolStorage` type // parameter (see `object_pool!` for the usual declaration). #[inline] - pub fn data(f: impl FnOnce(&RefCell>) -> R) -> R { + pub(crate) fn data(f: impl FnOnce(&RefCell>) -> R) -> R { S::with(f) } @@ -383,13 +383,6 @@ where }) } - pub fn has() -> bool { - Self::data(|cell| { - let d = cell.borrow(); - d.loaded && !d.list.first.is_null() - }) - } - pub fn push(pooled: T) { if cfg!(debug_assertions) { // PORT NOTE: Zig gated on `env.allow_assert`; that is diff --git a/src/collections/zig_hash_map.rs b/src/collections/zig_hash_map.rs index f52488059be..f8753b433a8 100644 --- a/src/collections/zig_hash_map.rs +++ b/src/collections/zig_hash_map.rs @@ -674,12 +674,6 @@ impl<'a, K, V, C> MapEntry<'a, K, V, C> where C: HashContext, { - pub fn or_insert(self, default: V) -> &'a mut V { - match self { - MapEntry::Occupied(o) => o.into_mut(), - MapEntry::Vacant(v) => v.insert(default), - } - } pub fn or_insert_with V>(self, f: F) -> &'a mut V { match self { MapEntry::Occupied(o) => o.into_mut(), diff --git a/src/crash_handler/CPUFeatures.rs b/src/crash_handler/CPUFeatures.rs index 539e0fc1c29..c9deab1ab63 100644 --- a/src/crash_handler/CPUFeatures.rs +++ b/src/crash_handler/CPUFeatures.rs @@ -7,7 +7,7 @@ unsafe extern "C" { } #[derive(Copy, Clone)] -pub struct CPUFeatures { +pub(crate) struct CPUFeatures { pub flags: Flags, } @@ -89,18 +89,18 @@ impl fmt::Display for CPUFeatures { } impl CPUFeatures { - pub fn is_empty(self) -> bool { + pub(crate) fn is_empty(self) -> bool { self.flags.bits() == 0 } #[cfg(target_arch = "x86_64")] - pub fn has_any_avx(self) -> bool { + pub(crate) fn has_any_avx(self) -> bool { self.flags.contains(Flags::AVX) || self.flags.contains(Flags::AVX2) || self.flags.contains(Flags::AVX512) } - pub fn get() -> CPUFeatures { + pub(crate) fn get() -> CPUFeatures { let raw = bun_cpu_features(); let flags = Flags::from_bits_retain(raw); // sanity check: `none` bit clear and no padding bits set diff --git a/src/crash_handler/lib.rs b/src/crash_handler/lib.rs index 789cd5403e3..8d79544897d 100644 --- a/src/crash_handler/lib.rs +++ b/src/crash_handler/lib.rs @@ -18,11 +18,14 @@ //! A lot of this handler is based on the Zig Standard Library implementation //! for std.debug.panicImpl and their code for gathering backtraces. -#![feature(core_intrinsics)] +// The cfg is the union of the two intrinsic call sites: `abort()` on the +// non-Windows crash path (all profiles) and `breakpoint()` on Windows debug +// builds only. Declaring the feature where neither is compiled (Windows +// release) trips `unused_features`. +#![cfg_attr(any(not(windows), debug_assertions), feature(core_intrinsics))] #![allow(internal_features)] #![allow(nonstandard_style, static_mut_refs, unexpected_cfgs)] #![warn(unused_must_use)] -#![warn(unreachable_pub)] #[path = "CPUFeatures.rs"] pub mod cpu_features; @@ -48,7 +51,7 @@ pub(crate) fn out_of_memory() -> ! { /// time. Lives in `.text` (read-only) so memory corruption cannot redirect it. #[doc(hidden)] #[unsafe(no_mangle)] -pub extern "Rust" fn __bun_crash_handler_out_of_memory() -> ! { +pub(crate) extern "Rust" fn __bun_crash_handler_out_of_memory() -> ! { out_of_memory() } @@ -56,7 +59,7 @@ pub extern "Rust" fn __bun_crash_handler_out_of_memory() -> ! { /// at link time. Lives in `.text` (read-only). #[doc(hidden)] #[unsafe(no_mangle)] -pub extern "Rust" fn __bun_crash_handler_dump_stack_trace( +pub(crate) extern "Rust" fn __bun_crash_handler_dump_stack_trace( first_address: Option, limits: bun_core::DumpStackTraceOptions, ) { @@ -85,7 +88,7 @@ pub mod debug { /// Zig: `std.debug.captureStackTrace`. Thin re-export of the canonical safe /// wrapper in bun_core so this crate's internal callers don't churn. #[inline] - pub fn capture_stack_trace(begin: usize, addrs: &mut [usize]) -> usize { + pub(crate) fn capture_stack_trace(begin: usize, addrs: &mut [usize]) -> usize { bun_core::capture_stack_trace(begin, addrs) } @@ -94,8 +97,8 @@ pub mod debug { panic!("{}", bstr::BStr::new(msg)) } - pub const HAVE_ERROR_RETURN_TRACING: bool = false; - pub const STRIP_DEBUG_INFO: bool = !cfg!(debug_assertions); + pub(crate) const HAVE_ERROR_RETURN_TRACING: bool = false; + pub(crate) const STRIP_DEBUG_INFO: bool = !cfg!(debug_assertions); // ── SelfInfo (vendor/zig/lib/std/debug/SelfInfo.zig) ───────────────── // D104: canonical home for the dladdr-backed `std.debug.SelfInfo` shim. @@ -222,9 +225,9 @@ pub mod debug { fn lookup_module_dyld(&mut self, address: usize) -> Result<&mut Module, Error> { // PORT NOTE: Zig walks `_dyld_get_image_header` + LoadCommandIterator. `dladdr` // gives the same `{base_address, fname}` pair on Darwin without the MachO walk. - // SAFETY: dladdr only reads; out-param is a valid Dl_info. let mut info: libc::Dl_info = bun_core::ffi::zeroed(); - let rc = unsafe { libc::dladdr(address as *const c_void, &mut info) }; + // SAFETY: dladdr only reads; out-param is a valid Dl_info. + let rc = unsafe { libc::dladdr(address as *const c_void, &raw mut info) }; if rc == 0 { return Err(err!("MissingDebugInfo")); } @@ -313,9 +316,9 @@ pub mod debug { #[cfg(target_vendor = "apple")] fn lookup_module_name_dyld(address: usize) -> Option> { - // SAFETY: dladdr only reads; out-param is a valid Dl_info. let mut info: libc::Dl_info = bun_core::ffi::zeroed(); - let rc = unsafe { libc::dladdr(address as *const c_void, &mut info) }; + // SAFETY: dladdr only reads; out-param is a valid Dl_info. + let rc = unsafe { libc::dladdr(address as *const c_void, &raw mut info) }; if rc == 0 || info.dli_fname.is_null() { return None; } @@ -346,7 +349,8 @@ pub mod debug { } } /// Zig: `std.io.tty.detectConfig(std.io.getStdErr())`. - pub fn detect_tty_config_stderr() -> TtyConfig { + #[allow(dead_code)] + pub(crate) fn detect_tty_config_stderr() -> TtyConfig { if bun_core::Output::ENABLE_ANSI_COLORS_STDERR.load(core::sync::atomic::Ordering::Relaxed) { TtyConfig::EscapeCodes } else { @@ -411,8 +415,8 @@ pub use bun_io::{FmtAdapter, Write}; /// `bun_sys::stderr_writer()` (not yet exposed by T1). /// Only impls `bun_io::Write` — `write!` resolves to `bun_io::Write::write_fmt` /// (alloc-free stack `Bridge`, async-signal-safe). -pub struct StderrWriter; -pub fn stderr_writer() -> StderrWriter { +pub(crate) struct StderrWriter; +pub(crate) fn stderr_writer() -> StderrWriter { StderrWriter } impl Write for StderrWriter { @@ -511,8 +515,7 @@ mod draft { { #[cfg(debug_assertions)] core::intrinsics::breakpoint(); - // SAFETY: ExitProcess never returns. - unsafe { bun_sys::windows::kernel32::ExitProcess(3) } + bun_sys::windows::kernel32::ExitProcess(3) } #[cfg(not(windows))] // SAFETY: libc::abort has no preconditions; never returns. @@ -552,14 +555,11 @@ mod draft { pub fn set_main_thread_id(id: u64) { MAIN_THREAD_ID.store(id, Ordering::Relaxed); } - pub fn set_cmd_char(c: u8) { - CMD_CHAR.store(c, Ordering::Relaxed); - } pub fn is_main_thread() -> bool { MAIN_THREAD_ID.load(Ordering::Relaxed) == bun_threading::current_thread_id() } - pub fn cmd_char() -> Option { + pub(crate) fn cmd_char() -> Option { match CMD_CHAR.load(Ordering::Relaxed) { 0 => None, c => Some(c), @@ -573,7 +573,7 @@ mod draft { /// Set this to false if you want to disable all uses of this panic handler. /// This is useful for testing as a crash in here will not 'panicked during a panic'. - pub const ENABLE: bool = true; + pub(crate) const ENABLE: bool = true; /// Overridable with BUN_CRASH_REPORT_URL environment variable. const DEFAULT_REPORT_BASE_URL: &str = "https://bun.report"; @@ -709,7 +709,7 @@ mod draft { #[cfg(feature = "show_crash_trace")] #[derive(Clone, Copy)] - pub struct ResolverAction { + pub(crate) struct ResolverAction { pub source_dir: &'static [u8], pub import_path: &'static [u8], pub kind: bun_ast::ImportKind, @@ -775,7 +775,7 @@ mod draft { /// Set (or clear) the thread-local `CURRENT_ACTION`. Paired with /// [`current_action`] for scoped restore via `scopeguard`. #[inline] - pub fn set_current_action(action: Option) { + pub(crate) fn set_current_action(action: Option) { CURRENT_ACTION.with(|c| c.set(action)); } @@ -1061,10 +1061,11 @@ mod draft { // `noreturn` crash path immediately before `ExitProcess(3)`, // so the leak is intentional. } else { - // SAFETY: GetCurrentThreadId is an infallible Win32 call with no pointer/precondition requirements - if write!(writer, "(thread {})", unsafe { + if write!( + writer, + "(thread {})", bun_sys::windows::kernel32::GetCurrentThreadId() - }) + ) .is_err() { abort(); @@ -1559,19 +1560,7 @@ mod draft { ); } - fn panic_builtin( - msg: &[u8], - error_return_trace: Option<&StackTrace>, - begin_addr: Option, - ) -> ! { - // TODO(port): std.debug.panicImpl — fall back to Rust's std panic machinery - debug::panic_impl(error_return_trace, begin_addr, msg); - } - - pub const PANIC: fn(&[u8], Option<&StackTrace>, Option) -> ! = - if ENABLE { panic_impl } else { panic_builtin }; - - pub fn report_base_url() -> &'static [u8] { + pub(crate) fn report_base_url() -> &'static [u8] { // PORTING.md §Concurrency: OnceLock for lazy global init (was a raw mutable global Option). static BASE_URL: std::sync::OnceLock<&'static [u8]> = std::sync::OnceLock::new(); *BASE_URL.get_or_init(|| { @@ -1796,7 +1785,7 @@ mod draft { /// One-shot state registration into lower-tier crates. Storage moved down: /// `bun_core::CRASH_HANDLER_INSTALLED` is a plain `AtomicBool`; T0's /// `raise_ignoring_panic_handler` does the SIG_DFL reset itself with libc. - pub fn install_hooks() { + pub(crate) fn install_hooks() { bun_core::CRASH_HANDLER_INSTALLED.store(true, Ordering::Relaxed); // T0 `bun_alloc::out_of_memory()` and `bun_core::dump_current_stack_trace()` // reach this crate via link-time `extern "Rust"` symbols @@ -1997,7 +1986,7 @@ mod draft { } } - pub fn reset_segfault_handler() { + pub(crate) fn reset_segfault_handler() { if !ENABLE { return; } @@ -2036,7 +2025,7 @@ mod draft { } #[cfg(windows)] - pub extern "system" fn handle_segfault_windows( + pub(crate) extern "system" fn handle_segfault_windows( info: *mut bun_sys::windows::EXCEPTION_POINTERS, ) -> c_long { // SAFETY: kernel provides a valid EXCEPTION_POINTERS @@ -2085,7 +2074,7 @@ mod draft { // `size_t`; `AtomicUsize` has the same size/alignment as `usize` so the // symbol layout is unchanged, and the Rust side reads it race-free. #[unsafe(no_mangle)] - pub static Bun__reported_memory_size: AtomicUsize = AtomicUsize::new(0); + pub(crate) static Bun__reported_memory_size: AtomicUsize = AtomicUsize::new(0); pub fn print_metadata(writer: &mut impl Write) -> Result<(), bun_core::Error> { #[cfg(debug_assertions)] @@ -2181,7 +2170,7 @@ mod draft { } #[cfg(target_os = "macos")] { - write!(writer, "macOS v{}\n", bstr::BStr::new(platform.version)) + writeln!(writer, "macOS v{}", bstr::BStr::new(platform.version)) .map_err(fmt_err)?; } #[cfg(windows)] @@ -2471,12 +2460,11 @@ mod draft { // https://github.com/ziglang/zig/blob/215de3ee67f75e2405c177b262cb5c1cd8c8e343/lib/std/debug.zig#L1783 let address = if addr == 0 { 0 } else { addr - 1 }; - // SAFETY: dyld APIs are safe to call - let image_count = unsafe { bun_sys::c::_dyld_image_count() }; + let image_count = bun_sys::c::_dyld_image_count(); let mut i: u32 = 0; while i < image_count { - let header = unsafe { bun_sys::c::_dyld_get_image_header(i) }; + let header = bun_sys::c::_dyld_get_image_header(i); if header.is_null() { i += 1; continue; @@ -2487,8 +2475,7 @@ mod draft { continue; } // This 'slide' is the ASLR offset. Subtract from `address` to get a stable address - let vmaddr_slide = - unsafe { bun_sys::c::_dyld_get_image_vmaddr_slide(i) } as usize; + let vmaddr_slide = bun_sys::c::_dyld_get_image_vmaddr_slide(i) as usize; // SAFETY: header points to a valid mach_header_64 let header_ref = unsafe { &*header }; @@ -3182,9 +3169,9 @@ mod draft { // SAFETY: lazy debug-only singleton; sole `&mut` for the dump below. Ok(d) => unsafe { &mut *d }, Err(err) => { - let _ = write!( + let _ = writeln!( stderr, - "Unable to dump stack trace: Unable to open debug info: {}\n", + "Unable to dump stack trace: Unable to open debug info: {}", bstr::BStr::new(err.name()) ); return; @@ -3392,7 +3379,7 @@ mod draft { let _ = list.remove(index); } - pub struct SourceAtAddress { + pub(crate) struct SourceAtAddress { pub source_location: Option, pub symbol_name: Box<[u8]>, pub compile_unit_name: Box<[u8]>, @@ -3519,7 +3506,7 @@ mod draft { } /// Clone of `debug.printSourceAtAddress` but it returns the metadata as well. - pub fn get_source_at_address( + pub(crate) fn get_source_at_address( debug_info: &mut SelfInfo, address: usize, ) -> Result, bun_core::Error> { @@ -3785,14 +3772,14 @@ mod draft { } #[unsafe(no_mangle)] - pub extern "C" fn CrashHandler__setInsideNativePlugin(name: *const c_char) { + pub(crate) extern "C" fn CrashHandler__setInsideNativePlugin(name: *const c_char) { INSIDE_NATIVE_PLUGIN.with(|c| c.set(if name.is_null() { None } else { Some(name) })); } /// # Safety /// `name` must be a valid NUL-terminated C string. #[unsafe(no_mangle)] - pub unsafe extern "C" fn CrashHandler__unsupportedUVFunction(name: *const c_char) { + pub(crate) unsafe extern "C" fn CrashHandler__unsupportedUVFunction(name: *const c_char) { // TODO(port): bun_analytics::Features::increment_unsupported_uv_function UNSUPPORTED_UV_FUNCTION.with(|c| c.set(if name.is_null() { None } else { Some(name) })); if env_var::feature_flag::BUN_INTERNAL_SUPPRESS_CRASH_ON_UV_STUB::get() == Some(true) { @@ -3814,7 +3801,10 @@ mod draft { /// # Safety /// `message_ptr` must be valid for reads of `message_len` bytes. #[unsafe(no_mangle)] - pub unsafe extern "C" fn Bun__crashHandler(message_ptr: *const u8, message_len: usize) -> ! { + pub(crate) unsafe extern "C" fn Bun__crashHandler( + message_ptr: *const u8, + message_len: usize, + ) -> ! { // SAFETY: caller passes a valid (ptr, len) byte slice let msg = unsafe { core::slice::from_raw_parts(message_ptr, message_len) }; crash_handler( @@ -3827,7 +3817,7 @@ mod draft { /// # Safety /// `action` must be null or a valid NUL-terminated C string that outlives the dlopen call. #[unsafe(no_mangle)] - pub unsafe extern "C" fn CrashHandler__setDlOpenAction(action: *const c_char) { + pub(crate) unsafe extern "C" fn CrashHandler__setDlOpenAction(action: *const c_char) { if !action.is_null() { debug_assert!(CURRENT_ACTION.with(|c| c.get()).is_none()); // SAFETY: action is a valid NUL-terminated C string for the duration of the dlopen call diff --git a/src/csrf/lib.rs b/src/csrf/lib.rs index 58039f90444..77285aedeae 100644 --- a/src/csrf/lib.rs +++ b/src/csrf/lib.rs @@ -3,7 +3,6 @@ //! by generating and validating tokens using HMAC signatures #![warn(unused_must_use)] -#![warn(unreachable_pub)] use bun_boringssl_sys as boring; use bun_core::strings; use bun_sha_hmac::hmac; diff --git a/src/css/declaration.rs b/src/css/declaration.rs index 1700f2183de..a537474326a 100644 --- a/src/css/declaration.rs +++ b/src/css/declaration.rs @@ -327,7 +327,7 @@ impl<'bump> DeclarationBlock<'bump> { // ─── PropertyDeclarationParser ──────────────────────────────────────────── -pub struct PropertyDeclarationParser<'a, 'bump> { +pub(crate) struct PropertyDeclarationParser<'a, 'bump> { pub important_declarations: &'a mut DeclarationList<'bump>, pub declarations: &'a mut DeclarationList<'bump>, pub options: &'a css::ParserOptions<'a>, diff --git a/src/css/generics.rs b/src/css/generics.rs index 04106545982..080a7cd4376 100644 --- a/src/css/generics.rs +++ b/src/css/generics.rs @@ -208,11 +208,11 @@ pub fn implement_eql(this: &T, other: &T) -> bool { } #[inline] -pub fn eql(lhs: &T, rhs: &T) -> bool { +pub(crate) fn eql(lhs: &T, rhs: &T) -> bool { lhs.eql(rhs) } -pub fn eql_list(lhs: &ArrayList<'_, T>, rhs: &ArrayList<'_, T>) -> bool { +pub(crate) fn eql_list(lhs: &ArrayList<'_, T>, rhs: &ArrayList<'_, T>) -> bool { if lhs.len() != rhs.len() { return false; } @@ -903,13 +903,13 @@ pub fn hash(this: &T, hasher: &mut Wyhash) { this.hash(hasher) } -pub fn hash_array_list(this: &ArrayList<'_, V>, hasher: &mut Wyhash) { +pub(crate) fn hash_array_list(this: &ArrayList<'_, V>, hasher: &mut Wyhash) { for item in this.iter() { item.hash(hasher); } } -pub fn hash_baby_list(this: &Vec, hasher: &mut Wyhash) { +pub(crate) fn hash_baby_list(this: &Vec, hasher: &mut Wyhash) { for item in this.slice_const() { item.hash(hasher); } @@ -1094,7 +1094,7 @@ pub trait IsCompatible { pub use bun_css_derive::IsCompatible; #[inline] -pub fn is_compatible(val: &T, browsers: &crate::targets::Browsers) -> bool { +pub(crate) fn is_compatible(val: &T, browsers: &crate::targets::Browsers) -> bool { val.is_compatible(browsers) } @@ -1351,7 +1351,7 @@ pub trait ToCss { } #[inline] -pub fn to_css(this: &T, dest: &mut Printer) -> core::result::Result<(), PrintErr> { +pub(crate) fn to_css(this: &T, dest: &mut Printer) -> core::result::Result<(), PrintErr> { this.to_css(dest) } @@ -1512,11 +1512,6 @@ pub trait TryFromAngle: Sized { fn try_from_angle(angle: Angle) -> Option; } -#[inline] -pub fn try_from_angle(angle: Angle) -> Option { - T::try_from_angle(angle) -} - impl TryFromAngle for CSSNumber { #[inline] fn try_from_angle(angle: Angle) -> Option { @@ -1528,11 +1523,6 @@ pub trait TrySign { fn try_sign(&self) -> Option; } -#[inline] -pub fn try_sign(val: &T) -> Option { - val.try_sign() -} - impl TrySign for CSSNumber { #[inline] fn try_sign(&self) -> Option { @@ -1547,11 +1537,6 @@ pub trait TryMap: Sized { fn try_map(&self, map_fn: impl Fn(f32) -> f32) -> Option; } -#[inline] -pub fn try_map(val: &T, map_fn: impl Fn(f32) -> f32) -> Option { - val.try_map(map_fn) -} - impl TryMap for CSSNumber { #[inline] fn try_map(&self, map_fn: impl Fn(f32) -> f32) -> Option { @@ -1566,16 +1551,6 @@ pub trait TryOpTo: Sized { fn try_op_to(&self, rhs: &Self, ctx: C, op_fn: impl Fn(C, f32, f32) -> R) -> Option; } -#[inline] -pub fn try_op_to( - lhs: &T, - rhs: &T, - ctx: C, - op_fn: impl Fn(C, f32, f32) -> R, -) -> Option { - lhs.try_op_to(rhs, ctx, op_fn) -} - impl TryOpTo for CSSNumber { #[inline] fn try_op_to(&self, rhs: &Self, ctx: C, op_fn: impl Fn(C, f32, f32) -> R) -> Option { @@ -1595,16 +1570,6 @@ pub trait TryOp: Sized { fn try_op(&self, rhs: &Self, ctx: C, op_fn: impl Fn(C, f32, f32) -> f32) -> Option; } -#[inline] -pub fn try_op( - lhs: &T, - rhs: &T, - ctx: C, - op_fn: impl Fn(C, f32, f32) -> f32, -) -> Option { - lhs.try_op(rhs, ctx, op_fn) -} - impl TryOp for CSSNumber { #[inline] fn try_op(&self, rhs: &Self, ctx: C, op_fn: impl Fn(C, f32, f32) -> f32) -> Option { @@ -1617,12 +1582,7 @@ pub trait PartialCmp { } #[inline] -pub fn partial_cmp(lhs: &T, rhs: &T) -> Option { - lhs.partial_cmp(rhs) -} - -#[inline] -pub fn partial_cmp_f32(lhs: f32, rhs: f32) -> Option { +pub(crate) fn partial_cmp_f32(lhs: f32, rhs: f32) -> Option { let lte = lhs <= rhs; let rte = lhs >= rhs; if !lte && !rte { diff --git a/src/css/lib.rs b/src/css/lib.rs index 148dc2cf41b..101d7f2b906 100644 --- a/src/css/lib.rs +++ b/src/css/lib.rs @@ -98,7 +98,7 @@ pub use css_parser::{ // namespace). `Str` is the arena-borrowed `[]const u8` slice alias; here // it's `*const [u8]` (matches `error.rs` / `values::ident` field shape) and // becomes `&'bump [u8]` once the arena lifetime is plumbed. -pub type Str = *const [u8]; +pub(crate) type Str = *const [u8]; /// Dereference an arena-owned [`Str`] into a slice borrow. /// @@ -113,7 +113,7 @@ pub type Str = *const [u8]; /// `p` must be a non-null fat pointer into the parser's source text or bump /// arena, and that backing storage must outlive the returned reference. #[inline(always)] -pub unsafe fn arena_str(p: Str) -> &'static [u8] { +pub(crate) unsafe fn arena_str(p: Str) -> &'static [u8] { // SAFETY: caller contract (documented above) guarantees `p` is a non-null, // well-aligned fat pointer into the parser's immutable source/bump arena, // whose backing storage outlives the returned reference. @@ -188,8 +188,6 @@ pub mod values_stub { } // ─── stub re-exports referenced cross-crate ──────────────────────────────── -// TODO(port): replace stub with `rules::custom_media::CustomMediaRule`. -pub type CustomMedia = (); /// Hoisted from `css_parser.rs` (gated). Single-variant error type returned by /// every `to_css` path; the *kind* lives in `Printer.error_kind` (PrinterError) @@ -215,7 +213,7 @@ impl core::error::Error for PrintErr {} /// path. Distinct from `css_parser::PrintResult = Maybe`, /// which carries the rich `Err` — this is just the bubbled /// signal (the *kind* lives in `Printer.error_kind`). -pub type PrintResult = core::result::Result; +pub(crate) type PrintResult = core::result::Result; pub use dependencies::Dependency; diff --git a/src/css/media_query.rs b/src/css/media_query.rs index aa1bfa7a374..328d6423a18 100644 --- a/src/css/media_query.rs +++ b/src/css/media_query.rs @@ -216,11 +216,11 @@ bitflags::bitflags! { impl QueryConditionFlags { #[inline] - pub fn allow_or(self) -> bool { + pub(crate) fn allow_or(self) -> bool { self.contains(Self::ALLOW_OR) } #[inline] - pub fn allow_style(self) -> bool { + pub(crate) fn allow_style(self) -> bool { self.contains(Self::ALLOW_STYLE) } } @@ -242,7 +242,7 @@ pub enum MediaCondition { /// `MediaFeature` is the media-query specialization of the generic /// `QueryFeature` (also used by `@container`). -pub type MediaFeature = QueryFeature; +pub(crate) type MediaFeature = QueryFeature; /// A media feature name (either a known `MediaFeatureId` or a custom/unknown ident). #[derive(Debug, Clone)] @@ -555,7 +555,7 @@ pub enum MediaFeatureId { impl MediaFeatureId { // Zig: `pub const valueType = css.DeriveValueType(@This(), ValueTypeMap).valueType;` - pub fn value_type(self) -> MediaFeatureType { + pub(crate) fn value_type(self) -> MediaFeatureType { use MediaFeatureId::*; use MediaFeatureType as T; match self { @@ -764,7 +764,7 @@ impl MediaQuery { /// Zig: `toCssWithParensIfNeeded` — wraps `v.to_css()` in parentheses when the /// caller's grammar position requires it. -pub fn to_css_with_parens_if_needed( +pub(crate) fn to_css_with_parens_if_needed( v: &T, dest: &mut Printer, needs_parens: bool, @@ -780,7 +780,7 @@ pub fn to_css_with_parens_if_needed( } /// Zig: `operationToCss` — serialize `a OP b OP c ...` with per-child parens. -pub fn operation_to_css( +pub(crate) fn operation_to_css( operator: Operator, conditions: &[C], dest: &mut Printer, @@ -885,7 +885,7 @@ impl QueryCondition for MediaCondition { } impl QueryFeature { - pub fn needs_parens( + pub(crate) fn needs_parens( &self, parent_operator: Option, targets: &css::targets::Targets, @@ -895,7 +895,7 @@ impl QueryFeature { && targets.should_compile_same(css::compat::Feature::MediaIntervalSyntax) } - pub fn to_css(&self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { dest.write_char(b'(')?; match self { @@ -953,14 +953,14 @@ impl QueryFeature { impl MediaFeatureName { /// Zig: `MediaFeatureName.valueType`. - pub fn value_type(&self) -> MediaFeatureType { + pub(crate) fn value_type(&self) -> MediaFeatureType { match self { MediaFeatureName::Standard(standard) => standard.value_type(), _ => MediaFeatureType::Unknown, } } - pub fn to_css(&self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { match self { MediaFeatureName::Standard(v) => v.to_css(dest), // PORT NOTE: Zig `DashedIdentFns.toCss` → `dest.writeDashedIdent` @@ -970,7 +970,7 @@ impl MediaFeatureName { } } - pub fn to_css_with_prefix( + pub(crate) fn to_css_with_prefix( &self, prefix: &str, dest: &mut Printer, @@ -993,7 +993,7 @@ impl MediaFeatureName { /// prefix (lowered to `>=`/`<=`). /// /// Zig: `MediaFeatureName.parse`. - pub fn parse(input: &mut Parser) -> Result<(Self, Option)> { + pub(crate) fn parse(input: &mut Parser) -> Result<(Self, Option)> { use bun_core::strings; let ident = input.expect_ident_cloned()?; @@ -1055,7 +1055,7 @@ impl MediaFeatureName { } impl MediaFeatureComparison { - pub fn to_css(self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { + pub(crate) fn to_css(self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { match self { // PORT NOTE(suspect): Zig emits '-' for `Equal` (media_query.zig:1156), // diverging from the spec `=` and from this enum's strum tag. Ported @@ -1076,7 +1076,7 @@ impl MediaFeatureComparison { } } - pub fn opposite(self) -> Self { + pub(crate) fn opposite(self) -> Self { match self { MediaFeatureComparison::GreaterThan => MediaFeatureComparison::LessThan, MediaFeatureComparison::GreaterThanEqual => MediaFeatureComparison::LessThanEqual, @@ -1088,7 +1088,7 @@ impl MediaFeatureComparison { } impl MediaFeatureValue { - pub fn to_css(&self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { match self { MediaFeatureValue::Length(len) => len.to_css(dest), MediaFeatureValue::Number(num) => css::to_css::float32(*num, dest), @@ -1109,7 +1109,7 @@ impl MediaFeatureValue { /// Zig: `addF32` — adjust by `other` for strict-inequality → min/max /// boundary lowering. Consumes `self`. - pub fn add_f32(self, other: f32) -> MediaFeatureValue { + pub(crate) fn add_f32(self, other: f32) -> MediaFeatureValue { match self { // Zig: `len.add(arena, Length.px(other))` — calc lattice. MediaFeatureValue::Length(len) => MediaFeatureValue::Length(len.add(Length::px(other))), @@ -1126,7 +1126,7 @@ impl MediaFeatureValue { } /// Zig: `MediaFeatureValue.valueType`. - pub fn value_type(&self) -> MediaFeatureType { + pub(crate) fn value_type(&self) -> MediaFeatureType { use MediaFeatureValue as V; match self { V::Length(_) => MediaFeatureType::Length, @@ -1141,7 +1141,7 @@ impl MediaFeatureValue { } /// Zig: `MediaFeatureValue.checkType`. - pub fn check_type(&self, expected_type: MediaFeatureType) -> bool { + pub(crate) fn check_type(&self, expected_type: MediaFeatureType) -> bool { let vt = self.value_type(); if expected_type == MediaFeatureType::Unknown || vt == MediaFeatureType::Unknown { return true; @@ -1151,7 +1151,7 @@ impl MediaFeatureValue { /// Parses a single media query feature value, with an expected type. /// If the type is unknown, pass `MediaFeatureType::Unknown` instead. - pub fn parse( + pub(crate) fn parse( input: &mut Parser, expected_type: MediaFeatureType, options: &css::ParserOptions, @@ -1162,7 +1162,7 @@ impl MediaFeatureValue { MediaFeatureValue::parse_unknown(input, options) } - pub fn parse_known( + pub(crate) fn parse_known( input: &mut Parser, expected_type: MediaFeatureType, ) -> Result { @@ -1188,7 +1188,7 @@ impl MediaFeatureValue { }) } - pub fn parse_unknown( + pub(crate) fn parse_unknown( input: &mut Parser, options: &css::ParserOptions, ) -> Result { @@ -1326,14 +1326,14 @@ impl MediaType { /// Zig: `css.implementDeepClone` — `Custom([]const u8)` is an arena-owned /// slice (identity copy under the generics.zig "const strings" rule). #[inline] - pub fn deep_clone(&self, _bump: &bun_alloc::Arena) -> Self { + pub(crate) fn deep_clone(&self, _bump: &bun_alloc::Arena) -> Self { *self } } impl MediaCondition { /// Zig: `MediaCondition.deepClone` — variant-wise recursion. - pub fn deep_clone(&self, bump: &bun_alloc::Arena) -> Self { + pub(crate) fn deep_clone(&self, bump: &bun_alloc::Arena) -> Self { let alloc = ArenaPtr::new(bump); match self { MediaCondition::Feature(f) => { @@ -1360,7 +1360,7 @@ impl MediaFeatureName { /// Zig: struct-copy (`name = this.plain.name`). All payloads are `Copy` / /// arena-slice idents; `derive(Clone)` is the faithful deep clone. #[inline] - pub fn deep_clone(&self, _bump: &bun_alloc::Arena) -> Self { + pub(crate) fn deep_clone(&self, _bump: &bun_alloc::Arena) -> Self { self.clone() } } @@ -1368,7 +1368,7 @@ impl MediaFeatureName { impl QueryFeature { /// Zig: `QueryFeature.deepClone` — variant-wise; `name`/`operator` are /// value-copied, `MediaFeatureValue` recurses. - pub fn deep_clone(&self, bump: &bun_alloc::Arena) -> Self { + pub(crate) fn deep_clone(&self, bump: &bun_alloc::Arena) -> Self { match self { QueryFeature::Plain { name, value } => QueryFeature::Plain { name: name.deep_clone(bump), @@ -1405,7 +1405,7 @@ impl QueryFeature { impl MediaFeatureValue { /// Zig: `MediaFeatureValue.deepClone` — variant-wise. - pub fn deep_clone(&self, bump: &bun_alloc::Arena) -> Self { + pub(crate) fn deep_clone(&self, bump: &bun_alloc::Arena) -> Self { use MediaFeatureValue as V; match self { // Zig: `l.deepClone(arena)` — real `values::length::Length` @@ -1433,12 +1433,12 @@ impl MediaFeatureValue { // ───────────────────────── parse impl bodies ───────────────────────── impl MediaType { - pub fn parse(input: &mut Parser) -> Result { + pub(crate) fn parse(input: &mut Parser) -> Result { let name = input.expect_ident()?; Ok(MediaType::from_str(name)) } - pub fn from_str(name: &[u8]) -> MediaType { + pub(crate) fn from_str(name: &[u8]) -> MediaType { use bun_core::eql_case_insensitive_ascii_check_length as eq; if eq(name, b"all") { return MediaType::All; @@ -1530,7 +1530,7 @@ impl MediaQuery { impl MediaCondition { #[inline] - pub fn parse_with_flags( + pub(crate) fn parse_with_flags( input: &mut Parser, flags: QueryConditionFlags, options: &css::ParserOptions, @@ -1670,13 +1670,16 @@ impl QueryFeature { /// Forwarder kept for callers that don't yet thread `ParserOptions` /// (e.g. `rules::container::ContainerCondition::parse_feature`). #[inline] - pub fn parse(input: &mut Parser) -> Result { + pub(crate) fn parse(input: &mut Parser) -> Result { Self::parse_with_options(input, &css::ParserOptions::default(None)) } /// `QueryFeature.parse` with `ParserOptions` threaded so the `env()` /// arm of `MediaFeatureValue::parse_unknown` is reachable. - pub fn parse_with_options(input: &mut Parser, options: &css::ParserOptions) -> Result { + pub(crate) fn parse_with_options( + input: &mut Parser, + options: &css::ParserOptions, + ) -> Result { match input.try_parse(|i| Self::parse_name_first(i, options)) { Ok(res) => Ok(res), Err(e) => { @@ -1692,7 +1695,10 @@ impl QueryFeature { } /// Zig: `QueryFeature.parseNameFirst`. - pub fn parse_name_first(input: &mut Parser, options: &css::ParserOptions) -> Result { + pub(crate) fn parse_name_first( + input: &mut Parser, + options: &css::ParserOptions, + ) -> Result { let (name, legacy_op) = MediaFeatureName::::parse(input)?; let operator = match input.try_parse(|i| consume_operation_or_colon(i, true)) { @@ -1725,7 +1731,10 @@ impl QueryFeature { } /// Zig: `QueryFeature.parseValueFirst`. - pub fn parse_value_first(input: &mut Parser, options: &css::ParserOptions) -> Result { + pub(crate) fn parse_value_first( + input: &mut Parser, + options: &css::ParserOptions, + ) -> Result { // We need to find the feature name first so we know the type. let start = input.state(); // PORT NOTE: Zig loops `MediaFeatureName.parse` then checks diff --git a/src/css/prefixes.rs b/src/css/prefixes.rs index b935ee6a3fd..2fce358a90f 100644 --- a/src/css/prefixes.rs +++ b/src/css/prefixes.rs @@ -2244,11 +2244,6 @@ impl Feature { // Module-level re-exports so callers can `use css::prefixes::is_flex_2009`. #[inline] -pub fn is_flex_2009(browsers: &Browsers) -> bool { +pub(crate) fn is_flex_2009(browsers: &Browsers) -> bool { Feature::is_flex_2009(browsers) } - -#[inline] -pub fn is_webkit_gradient(browsers: &Browsers) -> bool { - Feature::is_webkit_gradient(browsers) -} diff --git a/src/css/printer.rs b/src/css/printer.rs index 0f2f0503826..3655a704f66 100644 --- a/src/css/printer.rs +++ b/src/css/printer.rs @@ -171,7 +171,7 @@ pub struct Printer<'a> { #[cfg(debug_assertions)] thread_local! { - pub static IN_DEBUG_FMT: Cell = const { Cell::new(false) }; + pub(crate) static IN_DEBUG_FMT: Cell = const { Cell::new(false) }; } impl<'a> Printer<'a> { diff --git a/src/css/properties/align.rs b/src/css/properties/align.rs index e1c8cb323a8..b060d038b3f 100644 --- a/src/css/properties/align.rs +++ b/src/css/properties/align.rs @@ -47,12 +47,12 @@ pub struct AlignContentContentPosition { } impl AlignContentContentPosition { - pub fn parse(input: &mut Parser) -> CssResult { + pub(crate) fn parse(input: &mut Parser) -> CssResult { let overflow = input.try_parse(OverflowPosition::parse).ok(); let value = ContentPosition::parse(input)?; Ok(Self { overflow, value }) } - pub fn to_inner(&self) -> ContentPositionInner { + pub(crate) fn to_inner(&self) -> ContentPositionInner { ContentPositionInner { overflow: self.overflow, value: self.value, @@ -75,7 +75,7 @@ pub enum BaselinePosition { } impl BaselinePosition { - pub fn parse(input: &mut Parser) -> CssResult { + pub(crate) fn parse(input: &mut Parser) -> CssResult { let location = input.current_source_location(); let ident = input.expect_ident_cloned()?; @@ -93,7 +93,7 @@ impl BaselinePosition { }} } - pub fn to_css(self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(self, dest: &mut Printer) -> Result<(), PrintErr> { match self { BaselinePosition::First => dest.write_str("baseline"), BaselinePosition::Last => dest.write_str("last baseline"), @@ -135,7 +135,7 @@ pub struct JustifyContentContentPosition { } impl JustifyContentContentPosition { - pub fn to_inner(&self) -> ContentPositionInner { + pub(crate) fn to_inner(&self) -> ContentPositionInner { ContentPositionInner { overflow: self.overflow, value: self.value, @@ -144,7 +144,7 @@ impl JustifyContentContentPosition { } impl JustifyContent { - pub fn parse(input: &mut Parser) -> CssResult { + pub(crate) fn parse(input: &mut Parser) -> CssResult { if input .try_parse(|i| i.expect_ident_matching(b"normal")) .is_ok() @@ -176,7 +176,7 @@ impl JustifyContent { }} } - pub fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { match self { JustifyContent::Normal => dest.write_str("normal"), JustifyContent::ContentDistribution(value) => value.to_css(dest), @@ -237,14 +237,14 @@ pub struct AlignSelfSelfPosition { } impl AlignSelfSelfPosition { - pub fn to_inner(&self) -> SelfPositionInner { + pub(crate) fn to_inner(&self) -> SelfPositionInner { SelfPositionInner { overflow: self.overflow, value: self.value, } } - pub fn parse(input: &mut Parser) -> CssResult { + pub(crate) fn parse(input: &mut Parser) -> CssResult { let overflow = input.try_parse(OverflowPosition::parse).ok(); let self_position = SelfPosition::parse(input)?; Ok(Self { @@ -292,7 +292,7 @@ pub struct JustifySelfSelfPosition { } impl JustifySelfSelfPosition { - pub fn to_inner(&self) -> SelfPositionInner { + pub(crate) fn to_inner(&self) -> SelfPositionInner { SelfPositionInner { overflow: self.overflow, value: self.value, @@ -301,7 +301,7 @@ impl JustifySelfSelfPosition { } impl JustifySelf { - pub fn parse(input: &mut Parser) -> CssResult { + pub(crate) fn parse(input: &mut Parser) -> CssResult { if input .try_parse(|i| i.expect_ident_matching(b"auto")) .is_ok() @@ -344,7 +344,7 @@ impl JustifySelf { }} } - pub fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { match self { JustifySelf::Auto => dest.write_str("auto"), JustifySelf::Normal => dest.write_str("normal"), @@ -405,14 +405,14 @@ pub struct AlignItemsSelfPosition { } impl AlignItemsSelfPosition { - pub fn to_inner(&self) -> SelfPositionInner { + pub(crate) fn to_inner(&self) -> SelfPositionInner { SelfPositionInner { overflow: self.overflow, value: self.value, } } - pub fn parse(input: &mut Parser) -> CssResult { + pub(crate) fn parse(input: &mut Parser) -> CssResult { let overflow = input.try_parse(OverflowPosition::parse).ok(); let self_position = SelfPosition::parse(input)?; Ok(Self { @@ -460,7 +460,7 @@ pub struct JustifyItemsSelfPosition { } impl JustifyItemsSelfPosition { - pub fn to_inner(&self) -> SelfPositionInner { + pub(crate) fn to_inner(&self) -> SelfPositionInner { SelfPositionInner { overflow: self.overflow, value: self.value, @@ -469,7 +469,7 @@ impl JustifyItemsSelfPosition { } impl JustifyItems { - pub fn parse(input: &mut Parser) -> CssResult { + pub(crate) fn parse(input: &mut Parser) -> CssResult { if input .try_parse(|i| i.expect_ident_matching(b"normal")) .is_ok() @@ -510,7 +510,7 @@ impl JustifyItems { }} } - pub fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { match self { JustifyItems::Normal => dest.write_str("normal"), JustifyItems::Stretch => dest.write_str("stretch"), @@ -557,7 +557,7 @@ pub enum LegacyJustify { } impl LegacyJustify { - pub fn parse(input: &mut Parser) -> CssResult { + pub(crate) fn parse(input: &mut Parser) -> CssResult { let location = input.current_source_location(); let ident = input.expect_ident_cloned()?; @@ -588,7 +588,7 @@ impl LegacyJustify { }} } - pub fn to_css(self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(self, dest: &mut Printer) -> Result<(), PrintErr> { dest.write_str("legacy ")?; match self { LegacyJustify::Left => dest.write_str("left"), @@ -627,7 +627,7 @@ impl Gap { // TODO(port): PropertyFieldMap was a comptime struct mapping fields → CSS property names // (.row = "row-gap", .column = "column-gap"); could encode as derive attrs. - pub fn parse(input: &mut Parser) -> CssResult { + pub(crate) fn parse(input: &mut Parser) -> CssResult { let row = GapValue::parse(input)?; let column = input .try_parse(GapValue::parse) @@ -635,7 +635,7 @@ impl Gap { Ok(Self { row, column }) } - pub fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { self.row.to_css(dest)?; if self.column != self.row { dest.write_str(" ")?; @@ -662,7 +662,7 @@ impl PlaceItems { // TODO(port): PropertyFieldMap (.align = "align-items", .justify = "justify-items") // TODO(port): VendorPrefixMap (.align = true) - pub fn parse(input: &mut Parser) -> CssResult { + pub(crate) fn parse(input: &mut Parser) -> CssResult { let align = AlignItems::parse(input)?; let justify = match input.try_parse(JustifyItems::parse) { Ok(v) => v, @@ -682,7 +682,7 @@ impl PlaceItems { Ok(Self { align, justify }) } - pub fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { self.align.to_css(dest)?; let is_equal = match &self.justify { JustifyItems::Normal => self.align == AlignItems::Normal, @@ -727,7 +727,7 @@ impl PlaceSelf { // TODO(port): PropertyFieldMap (.align = "align-self", .justify = "justify-self") // TODO(port): VendorPrefixMap (.align = true) - pub fn parse(input: &mut Parser) -> CssResult { + pub(crate) fn parse(input: &mut Parser) -> CssResult { let align = AlignSelf::parse(input)?; let justify = match input.try_parse(JustifySelf::parse) { Ok(v) => v, @@ -746,7 +746,7 @@ impl PlaceSelf { Ok(Self { align, justify }) } - pub fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { self.align.to_css(dest)?; let is_equal = match &self.justify { JustifySelf::Auto => true, @@ -822,7 +822,7 @@ impl PlaceContent { // TODO(port): PropertyFieldMap (.align = PropertyIdTag::AlignContent, .justify = PropertyIdTag::JustifyContent) // TODO(port): VendorPrefixMap (.align = true, .justify = true) - pub fn parse(input: &mut Parser) -> CssResult { + pub(crate) fn parse(input: &mut Parser) -> CssResult { let align = AlignContent::parse(input)?; let justify = match JustifyContent::parse(input) { Ok(v) => v, @@ -849,7 +849,7 @@ impl PlaceContent { Ok(Self { align, justify }) } - pub fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { self.align.to_css(dest)?; let is_equal = match &self.justify { JustifyContent::Normal => 'brk: { @@ -946,7 +946,7 @@ pub enum ContentPosition { // ────────────────────────────────────────────────────────────────────────────── #[derive(Clone, Copy, PartialEq, Eq)] -pub struct SelfPositionInner { +pub(crate) struct SelfPositionInner { /// An overflow alignment mode. pub overflow: Option, /// A self position keyword. @@ -954,7 +954,7 @@ pub struct SelfPositionInner { } #[derive(Clone, Copy, PartialEq, Eq)] -pub struct ContentPositionInner { +pub(crate) struct ContentPositionInner { /// An overflow alignment mode. pub overflow: Option, /// A content position keyword. @@ -1211,7 +1211,7 @@ impl PlaceItems { } impl AlignHandler { - pub fn handle_property( + pub(crate) fn handle_property( &mut self, property: &Property, dest: &mut DeclarationList<'_>, @@ -1354,7 +1354,7 @@ impl AlignHandler { true } - pub fn finalize( + pub(crate) fn finalize( &mut self, dest: &mut DeclarationList<'_>, context: &mut PropertyHandlerContext<'_>, diff --git a/src/css/properties/background.rs b/src/css/properties/background.rs index bbc04f4b085..de6369e50a1 100644 --- a/src/css/properties/background.rs +++ b/src/css/properties/background.rs @@ -5,9 +5,8 @@ use crate::css_values::color::CssColor; use crate::css_values::image::Image; use crate::css_values::length::LengthPercentageOrAuto; use crate::css_values::position::{HorizontalPosition, Position, VerticalPosition}; -use crate::css_values::ratio::Ratio; use crate::generics::{CssEql, DeepClone}; -use crate::properties::{Property, PropertyId, PropertyIdTag}; +use crate::properties::{Property, PropertyId}; use crate::{ DeclarationList, Parser, PrintErr, Printer, PropertyHandlerContext, SmallList, VendorPrefix, }; @@ -39,7 +38,7 @@ pub struct Background { impl Background { // Zig `deinit` was a no-op (all allocations in CSS parser are in arena) — Drop handles it. - pub fn parse(input: &mut Parser) -> css::Result { + pub(crate) fn parse(input: &mut Parser) -> css::Result { let mut color: Option = None; let mut position: Option = None; let mut size: Option = None; @@ -135,7 +134,7 @@ impl Background { }) } - pub fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { let mut has_output = false; if self.color != CssColor::default() { @@ -218,30 +217,33 @@ impl Background { Ok(()) } - pub fn get_image(&self) -> &Image { + pub(crate) fn get_image(&self) -> &Image { &self.image } - pub fn with_image(&self, arena: &Bump, image: Image) -> Self { + pub(crate) fn with_image(&self, arena: &Bump, image: Image) -> Self { let mut ret = self.deep_clone(arena); ret.image = image; ret } - pub fn get_fallback(&self, arena: &Bump, kind: ColorFallbackKind) -> Background { + pub(crate) fn get_fallback(&self, arena: &Bump, kind: ColorFallbackKind) -> Background { let mut ret = self.deep_clone(arena); ret.color = self.color.get_fallback(arena, kind); ret.image = self.image.get_fallback(arena, kind); ret } - pub fn get_necessary_fallbacks(&self, targets: &css::targets::Targets) -> ColorFallbackKind { + pub(crate) fn get_necessary_fallbacks( + &self, + targets: &css::targets::Targets, + ) -> ColorFallbackKind { self.color.get_necessary_fallbacks(targets) | self.get_image().get_necessary_fallbacks(targets) } #[inline] - pub fn deep_clone(&self, arena: &Bump) -> Self { + pub(crate) fn deep_clone(&self, arena: &Bump) -> Self { // PORT NOTE: `css.implementDeepClone` reflection — expanded field-wise. // `Image` is the only non-`Clone` field; it provides its own `deep_clone`. Self { @@ -256,7 +258,7 @@ impl Background { } } - pub fn eql(&self, rhs: &Self) -> bool { + pub(crate) fn eql(&self, rhs: &Self) -> bool { self.image.eql(&rhs.image) && self.color == rhs.color && self.position == rhs.position @@ -287,15 +289,8 @@ pub struct ExplicitBackgroundSize { pub height: LengthPercentageOrAuto, } -impl ExplicitBackgroundSize { - #[inline] - pub fn deep_clone(&self, _arena: &Bump) -> Self { - self.clone() - } -} - impl BackgroundSize { - pub fn parse(input: &mut Parser) -> css::Result { + pub(crate) fn parse(input: &mut Parser) -> css::Result { if let Ok(width) = input.try_parse(LengthPercentageOrAuto::parse) { let height = input .try_parse(LengthPercentageOrAuto::parse) @@ -316,7 +311,7 @@ impl BackgroundSize { }} } - pub fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { match self { BackgroundSize::Cover => dest.write_str("cover"), BackgroundSize::Contain => dest.write_str("contain"), @@ -331,7 +326,7 @@ impl BackgroundSize { } } - pub fn default() -> Self { + pub(crate) fn default() -> Self { BackgroundSize::Explicit(ExplicitBackgroundSize { width: LengthPercentageOrAuto::Auto, height: LengthPercentageOrAuto::Auto, @@ -339,7 +334,7 @@ impl BackgroundSize { } #[inline] - pub fn deep_clone(&self, _arena: &Bump) -> Self { + pub(crate) fn deep_clone(&self, _arena: &Bump) -> Self { self.clone() } } @@ -354,30 +349,25 @@ pub struct BackgroundPosition { } impl BackgroundPosition { - // PORT NOTE: PropertyFieldMap — Zig comptime struct mapping fields → PropertyIdTag. - // Encoded here as associated consts. - pub const PROPERTY_FIELD_MAP_X: PropertyIdTag = PropertyIdTag::BackgroundPositionX; - pub const PROPERTY_FIELD_MAP_Y: PropertyIdTag = PropertyIdTag::BackgroundPositionY; - - pub fn parse(input: &mut Parser) -> css::Result { + pub(crate) fn parse(input: &mut Parser) -> css::Result { let pos = Position::parse(input)?; Ok(BackgroundPosition::from_position(pos)) } - pub fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { let pos = self.into_position(); pos.to_css(dest) } - pub fn default() -> Self { + pub(crate) fn default() -> Self { BackgroundPosition::from_position(Position::default()) } - pub fn from_position(pos: Position) -> BackgroundPosition { + pub(crate) fn from_position(pos: Position) -> BackgroundPosition { BackgroundPosition { x: pos.x, y: pos.y } } - pub fn into_position(&self) -> Position { + pub(crate) fn into_position(&self) -> Position { Position { x: self.x.clone(), y: self.y.clone(), @@ -385,7 +375,7 @@ impl BackgroundPosition { } #[inline] - pub fn deep_clone(&self, _arena: &Bump) -> Self { + pub(crate) fn deep_clone(&self, _arena: &Bump) -> Self { self.clone() } } @@ -400,14 +390,14 @@ pub struct BackgroundRepeat { } impl BackgroundRepeat { - pub fn default() -> Self { + pub(crate) fn default() -> Self { BackgroundRepeat { x: BackgroundRepeatKeyword::Repeat, y: BackgroundRepeatKeyword::Repeat, } } - pub fn parse(input: &mut Parser) -> css::Result { + pub(crate) fn parse(input: &mut Parser) -> css::Result { let state = input.state(); let ident = input.expect_ident_cloned()?; @@ -429,7 +419,7 @@ impl BackgroundRepeat { Ok(BackgroundRepeat { x, y }) } - pub fn to_css(self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(self, dest: &mut Printer) -> Result<(), PrintErr> { use BackgroundRepeatKeyword::{NoRepeat, Repeat}; if self.x == Repeat && self.y == NoRepeat { @@ -445,10 +435,6 @@ impl BackgroundRepeat { Ok(()) } } - - pub fn deep_clone(self, _arena: &Bump) -> Self { - self - } } crate::css_eql_partialeq!( @@ -488,7 +474,7 @@ pub enum BackgroundAttachment { } impl BackgroundAttachment { - pub fn default() -> Self { + pub(crate) fn default() -> Self { BackgroundAttachment::Scroll } } @@ -522,11 +508,11 @@ pub enum BackgroundClip { } impl BackgroundClip { - pub fn default() -> BackgroundClip { + pub(crate) fn default() -> BackgroundClip { BackgroundClip::BorderBox } - pub fn eql_origin(self, other: BackgroundOrigin) -> bool { + pub(crate) fn eql_origin(self, other: BackgroundOrigin) -> bool { match self { BackgroundClip::BorderBox => other == BackgroundOrigin::BorderBox, BackgroundClip::PaddingBox => other == BackgroundOrigin::PaddingBox, @@ -535,7 +521,7 @@ impl BackgroundClip { } } - pub fn is_background_box(self) -> bool { + pub(crate) fn is_background_box(self) -> bool { matches!( self, BackgroundClip::BorderBox | BackgroundClip::PaddingBox | BackgroundClip::ContentBox @@ -543,15 +529,6 @@ impl BackgroundClip { } } -/// A value for the [aspect-ratio](https://drafts.csswg.org/css-sizing-4/#aspect-ratio) property. -#[derive(Copy, Clone)] -pub struct AspectRatio { - /// The `auto` keyword. - pub auto: bool, - /// A preferred aspect ratio for the box, specified as width / height. - pub ratio: Option, -} - bitflags::bitflags! { #[derive(Clone, Copy, PartialEq, Eq, Default)] pub struct BackgroundProperty: u16 { @@ -568,19 +545,18 @@ bitflags::bitflags! { } impl BackgroundProperty { - pub const BACKGROUND_COLOR: Self = Self::COLOR; - pub const BACKGROUND_IMAGE: Self = Self::IMAGE; - pub const BACKGROUND_POSITION_X: Self = Self::POSITION_X; - pub const BACKGROUND_POSITION_Y: Self = Self::POSITION_Y; - pub const BACKGROUND_POSITION: Self = + pub(crate) const BACKGROUND_COLOR: Self = Self::COLOR; + pub(crate) const BACKGROUND_IMAGE: Self = Self::IMAGE; + pub(crate) const BACKGROUND_POSITION_X: Self = Self::POSITION_X; + pub(crate) const BACKGROUND_POSITION_Y: Self = Self::POSITION_Y; + pub(crate) const BACKGROUND_POSITION: Self = Self::from_bits_truncate(Self::POSITION_X.bits() | Self::POSITION_Y.bits()); - pub const BACKGROUND_REPEAT: Self = Self::REPEAT; - pub const BACKGROUND_SIZE: Self = Self::SIZE; - pub const BACKGROUND_ATTACHMENT: Self = Self::ATTACHMENT; - pub const BACKGROUND_ORIGIN: Self = Self::ORIGIN; - pub const BACKGROUND_CLIP: Self = Self::CLIP; + pub(crate) const BACKGROUND_REPEAT: Self = Self::REPEAT; + pub(crate) const BACKGROUND_SIZE: Self = Self::SIZE; + pub(crate) const BACKGROUND_ATTACHMENT: Self = Self::ATTACHMENT; + pub(crate) const BACKGROUND_ORIGIN: Self = Self::ORIGIN; - pub const BACKGROUND: Self = Self::from_bits_truncate( + pub(crate) const BACKGROUND: Self = Self::from_bits_truncate( Self::COLOR.bits() | Self::IMAGE.bits() | Self::POSITION_X.bits() @@ -593,7 +569,7 @@ impl BackgroundProperty { ); // blocked_on: PropertyId variant arity (BackgroundClip carries VendorPrefix payload) - pub fn try_from_property_id(property_id: PropertyId) -> Option { + pub(crate) fn try_from_property_id(property_id: PropertyId) -> Option { match property_id { PropertyId::BackgroundColor => Some(Self::BACKGROUND_COLOR), PropertyId::BackgroundImage => Some(Self::BACKGROUND_IMAGE), @@ -670,7 +646,7 @@ macro_rules! push_property { } impl BackgroundHandler { - pub fn handle_property( + pub(crate) fn handle_property( &mut self, property: &Property, dest: &mut DeclarationList, @@ -1166,7 +1142,11 @@ impl BackgroundHandler { self.clips = None; } - pub fn finalize(&mut self, dest: &mut DeclarationList, context: &mut PropertyHandlerContext) { + pub(crate) fn finalize( + &mut self, + dest: &mut DeclarationList, + context: &mut PropertyHandlerContext, + ) { // If the last declaration is prefixed, pop the last value // so it isn't duplicated when we flush. if self.has_prefix { diff --git a/src/css/properties/border.rs b/src/css/properties/border.rs index bcb1182e733..2a16afa7951 100644 --- a/src/css/properties/border.rs +++ b/src/css/properties/border.rs @@ -21,27 +21,27 @@ use bun_alloc::Arena as Bump; // ────────────────────────────────────────────────────────────────────────── /// A value for the [border-top](https://www.w3.org/TR/css-backgrounds-3/#propdef-border-top) shorthand property. -pub type BorderTop = GenericBorder; +pub(crate) type BorderTop = GenericBorder; /// A value for the [border-right](https://www.w3.org/TR/css-backgrounds-3/#propdef-border-right) shorthand property. -pub type BorderRight = GenericBorder; +pub(crate) type BorderRight = GenericBorder; /// A value for the [border-bottom](https://www.w3.org/TR/css-backgrounds-3/#propdef-border-bottom) shorthand property. -pub type BorderBottom = GenericBorder; +pub(crate) type BorderBottom = GenericBorder; /// A value for the [border-left](https://www.w3.org/TR/css-backgrounds-3/#propdef-border-left) shorthand property. -pub type BorderLeft = GenericBorder; +pub(crate) type BorderLeft = GenericBorder; /// A value for the [border-block-start](https://drafts.csswg.org/css-logical/#propdef-border-block-start) shorthand property. -pub type BorderBlockStart = GenericBorder; +pub(crate) type BorderBlockStart = GenericBorder; /// A value for the [border-block-end](https://drafts.csswg.org/css-logical/#propdef-border-block-end) shorthand property. -pub type BorderBlockEnd = GenericBorder; +pub(crate) type BorderBlockEnd = GenericBorder; /// A value for the [border-inline-start](https://drafts.csswg.org/css-logical/#propdef-border-inline-start) shorthand property. -pub type BorderInlineStart = GenericBorder; +pub(crate) type BorderInlineStart = GenericBorder; /// A value for the [border-inline-end](https://drafts.csswg.org/css-logical/#propdef-border-inline-end) shorthand property. -pub type BorderInlineEnd = GenericBorder; +pub(crate) type BorderInlineEnd = GenericBorder; /// A value for the [border-block](https://drafts.csswg.org/css-logical/#propdef-border-block) shorthand property. -pub type BorderBlock = GenericBorder; +pub(crate) type BorderBlock = GenericBorder; /// A value for the [border-inline](https://drafts.csswg.org/css-logical/#propdef-border-inline) shorthand property. -pub type BorderInline = GenericBorder; +pub(crate) type BorderInline = GenericBorder; /// A value for the [border](https://www.w3.org/TR/css-backgrounds-3/#propdef-border) shorthand property. -pub type Border = GenericBorder; +pub(crate) type Border = GenericBorder; // ────────────────────────────────────────────────────────────────────────── // GenericBorder @@ -161,7 +161,7 @@ where out } - pub fn deep_clone(&self, arena: &Bump) -> Self { + pub(crate) fn deep_clone(&self, arena: &Bump) -> Self { css::implement_deep_clone(self, arena) } @@ -171,7 +171,7 @@ where /// multiple `Border*` aliases. Needed when one logical value must be /// emitted as two distinct physical `Property` variants (e.g. /// inline-start → BorderLeft + BorderRight). - pub fn clone_as(&self, arena: &Bump) -> GenericBorder { + pub(crate) fn clone_as(&self, arena: &Bump) -> GenericBorder { let cloned = self.deep_clone(arena); GenericBorder { width: cloned.width, @@ -179,19 +179,6 @@ where color: cloned.color, } } - - pub fn eql(&self, other: &Self) -> bool { - css::implement_eql(self, other) - } - - #[inline] - pub fn default() -> Self { - Self { - width: BorderSideWidth::Medium, - style: S::default(), - color: CssColor::CurrentColor, - } - } } // ────────────────────────────────────────────────────────────────────────── @@ -444,14 +431,14 @@ struct BorderShorthand { } impl BorderShorthand { - pub fn eql(&self, rhs: &Self) -> bool { + pub(crate) fn eql(&self, rhs: &Self) -> bool { css::generic::eql(&self.width, &rhs.width) && css::generic::eql(&self.style, &rhs.style) && css::generic::eql(&self.color, &rhs.color) } // `border: anytype` — any GenericBorder - pub fn set_border(&mut self, arena: &Bump, border: &GenericBorder) + pub(crate) fn set_border(&mut self, arena: &Bump, border: &GenericBorder) where S: for<'a> css::DeepClone<'a> + Into, { @@ -567,7 +554,7 @@ bitflags::bitflags! { // blocked_on: PropertyIdTag variant name verification (PascalCase mapping) impl BorderProperty { - pub fn try_from_property_id(property_id: PropertyIdTag) -> Option { + pub(crate) fn try_from_property_id(property_id: PropertyIdTag) -> Option { // TODO(port): Zig used `inline for` over PropertyIdTag fields + @hasDecl. // Expanded to an explicit match over every PropertyIdTag whose name // starts with "border" and has a matching const above. @@ -1242,7 +1229,7 @@ mod border_handler_body { } impl BorderHandler { - pub fn handle_property( + pub(crate) fn handle_property( &mut self, property: &Property, dest: &mut DeclarationList, @@ -1493,7 +1480,7 @@ mod border_handler_body { true } - pub fn finalize( + pub(crate) fn finalize( &mut self, dest: &mut DeclarationList, context: &mut PropertyHandlerContext, diff --git a/src/css/properties/border_image.rs b/src/css/properties/border_image.rs index 0728e86a426..f6f76f85fbc 100644 --- a/src/css/properties/border_image.rs +++ b/src/css/properties/border_image.rs @@ -45,14 +45,14 @@ impl BorderImage { // repeat -> PropertyIdTag::BorderImageRepeat // VendorPrefixMap: all fields = true - pub fn parse(input: &mut css::Parser) -> Result { + pub(crate) fn parse(input: &mut css::Parser) -> Result { // PORT NOTE: Zig passed `{}` ctx + a no-op callback struct; collapsed to a closure. Self::parse_with_callback(input, |_: &mut css::Parser| false) } // PORT NOTE: Zig signature was (input, ctx: anytype, comptime callback: anytype) // where callback(ctx, input) -> bool. Collapsed ctx into the closure capture. - pub fn parse_with_callback( + pub(crate) fn parse_with_callback( input: &mut css::Parser, mut callback: impl FnMut(&mut css::Parser) -> bool, ) -> Result { @@ -143,7 +143,7 @@ impl BorderImage { Err(input.new_custom_error(css::ParserError::invalid_declaration)) } - pub fn to_css(&self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { Self::to_css_internal( &self.source, &self.slice, @@ -154,7 +154,7 @@ impl BorderImage { ) } - pub fn to_css_internal( + pub(crate) fn to_css_internal( source: &Image, slice: &BorderImageSlice, width: &Rect, @@ -194,7 +194,7 @@ impl BorderImage { Ok(()) } - pub fn get_fallbacks( + pub(crate) fn get_fallbacks( &mut self, arena: &Arena, targets: &css::targets::Targets, @@ -213,7 +213,7 @@ impl BorderImage { res } - pub fn deep_clone(&self, arena: &Arena) -> Self { + pub(crate) fn deep_clone(&self, arena: &Arena) -> Self { // PORT NOTE: Zig css.implementDeepClone iterated @typeInfo fields. Expanded // explicitly here — keep in sync with the BorderImage field list. BorderImage { @@ -225,7 +225,7 @@ impl BorderImage { } } - pub fn eql(&self, other: &BorderImage) -> bool { + pub(crate) fn eql(&self, other: &BorderImage) -> bool { self.source.eql(&other.source) && self.slice.eql(&other.slice) && self.width.eql(&other.width) @@ -233,7 +233,7 @@ impl BorderImage { && self.repeat.eql(&other.repeat) } - pub fn default() -> BorderImage { + pub(crate) fn default() -> BorderImage { BorderImage { source: Image::default(), slice: BorderImageSlice::default(), @@ -253,7 +253,7 @@ pub struct BorderImageRepeat { } impl BorderImageRepeat { - pub fn parse(input: &mut css::Parser) -> Result { + pub(crate) fn parse(input: &mut css::Parser) -> Result { let horizontal = BorderImageRepeatKeyword::parse(input)?; let vertical = input.try_parse(BorderImageRepeatKeyword::parse).ok(); Ok(BorderImageRepeat { @@ -262,7 +262,7 @@ impl BorderImageRepeat { }) } - pub fn to_css(&self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { self.horizontal.to_css(dest)?; if self.horizontal != self.vertical { dest.write_str(" ")?; @@ -271,22 +271,22 @@ impl BorderImageRepeat { Ok(()) } - pub fn is_compatible(&self, browsers: &css::targets::Browsers) -> bool { + pub(crate) fn is_compatible(&self, browsers: &css::targets::Browsers) -> bool { self.horizontal.is_compatible(browsers) && self.vertical.is_compatible(browsers) } - pub fn default() -> BorderImageRepeat { + pub(crate) fn default() -> BorderImageRepeat { BorderImageRepeat { horizontal: BorderImageRepeatKeyword::Stretch, vertical: BorderImageRepeatKeyword::Stretch, } } - pub fn eql(&self, other: &BorderImageRepeat) -> bool { + pub(crate) fn eql(&self, other: &BorderImageRepeat) -> bool { self.horizontal == other.horizontal && self.vertical == other.vertical } - pub fn deep_clone(&self, _arena: &Arena) -> Self { + pub(crate) fn deep_clone(&self, _arena: &Arena) -> Self { BorderImageRepeat { horizontal: self.horizontal, vertical: self.vertical, @@ -309,7 +309,7 @@ impl BorderImageSideWidth { // PORT NOTE: `css.DeriveParse(@This()).parse` / `css.DeriveToCss(@This()).toCss` // were comptime-reflected derives. Hand-expanded — declaration order matches // Zig (Number → LengthPercentage → keyword `auto`). - pub fn parse(input: &mut css::Parser) -> Result { + pub(crate) fn parse(input: &mut css::Parser) -> Result { if let Ok(n) = input.try_parse(CSSNumberFns::parse) { return Ok(BorderImageSideWidth::Number(n)); } @@ -320,7 +320,7 @@ impl BorderImageSideWidth { Ok(BorderImageSideWidth::Auto) } - pub fn to_css(&self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { match self { BorderImageSideWidth::Number(n) => CSSNumberFns::to_css(*n, dest), BorderImageSideWidth::LengthPercentage(lp) => lp.to_css(dest), @@ -328,15 +328,15 @@ impl BorderImageSideWidth { } } - pub fn default() -> BorderImageSideWidth { + pub(crate) fn default() -> BorderImageSideWidth { BorderImageSideWidth::Number(1.0) } - pub fn deep_clone(&self, _arena: &Arena) -> Self { + pub(crate) fn deep_clone(&self, _arena: &Arena) -> Self { self.clone() } - pub fn is_compatible(&self, browsers: &css::targets::Browsers) -> bool { + pub(crate) fn is_compatible(&self, browsers: &css::targets::Browsers) -> bool { match self { BorderImageSideWidth::LengthPercentage(l) => l.is_compatible(browsers), _ => true, @@ -368,7 +368,7 @@ pub enum BorderImageRepeatKeyword { } impl BorderImageRepeatKeyword { - pub fn is_compatible(self, browsers: &css::targets::Browsers) -> bool { + pub(crate) fn is_compatible(self, browsers: &css::targets::Browsers) -> bool { match self { BorderImageRepeatKeyword::Round => { css::compat::Feature::BorderImageRepeatRound.is_compatible(browsers) @@ -390,7 +390,7 @@ pub struct BorderImageSlice { } impl BorderImageSlice { - pub fn parse(input: &mut css::Parser) -> Result { + pub(crate) fn parse(input: &mut css::Parser) -> Result { let mut fill = input .try_parse(|i| i.expect_ident_matching(b"fill")) .is_ok(); @@ -403,7 +403,7 @@ impl BorderImageSlice { Ok(BorderImageSlice { offsets, fill }) } - pub fn to_css(&self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { self.offsets.to_css(dest)?; if self.fill { dest.write_str(" fill")?; @@ -411,15 +411,15 @@ impl BorderImageSlice { Ok(()) } - pub fn is_compatible(&self, _: &css::targets::Browsers) -> bool { + pub(crate) fn is_compatible(&self, _: &css::targets::Browsers) -> bool { true } - pub fn eql(&self, other: &BorderImageSlice) -> bool { + pub(crate) fn eql(&self, other: &BorderImageSlice) -> bool { self.offsets.eql(&other.offsets) && self.fill == other.fill } - pub fn default() -> BorderImageSlice { + pub(crate) fn default() -> BorderImageSlice { BorderImageSlice { offsets: Rect::::all(NumberOrPercentage::Percentage(Percentage { v: 1.0, @@ -428,7 +428,7 @@ impl BorderImageSlice { } } - pub fn deep_clone(&self, arena: &Arena) -> Self { + pub(crate) fn deep_clone(&self, arena: &Arena) -> Self { BorderImageSlice { offsets: self.offsets.deep_clone(arena), fill: self.fill, @@ -438,7 +438,7 @@ impl BorderImageSlice { bitflags::bitflags! { #[derive(Clone, Copy, PartialEq, Eq, Default)] - pub struct BorderImageProperty: u8 { + pub(crate) struct BorderImageProperty: u8 { const SOURCE = 1 << 0; const SLICE = 1 << 1; const WIDTH = 1 << 2; @@ -448,17 +448,17 @@ bitflags::bitflags! { } impl BorderImageProperty { - pub const BORDER_IMAGE_SOURCE: BorderImageProperty = BorderImageProperty::SOURCE; - pub const BORDER_IMAGE_SLICE: BorderImageProperty = BorderImageProperty::SLICE; - pub const BORDER_IMAGE_WIDTH: BorderImageProperty = BorderImageProperty::WIDTH; - pub const BORDER_IMAGE_OUTSET: BorderImageProperty = BorderImageProperty::OUTSET; - pub const BORDER_IMAGE_REPEAT: BorderImageProperty = BorderImageProperty::REPEAT; + pub(crate) const BORDER_IMAGE_SOURCE: BorderImageProperty = BorderImageProperty::SOURCE; + pub(crate) const BORDER_IMAGE_SLICE: BorderImageProperty = BorderImageProperty::SLICE; + pub(crate) const BORDER_IMAGE_WIDTH: BorderImageProperty = BorderImageProperty::WIDTH; + pub(crate) const BORDER_IMAGE_OUTSET: BorderImageProperty = BorderImageProperty::OUTSET; + pub(crate) const BORDER_IMAGE_REPEAT: BorderImageProperty = BorderImageProperty::REPEAT; - pub const BORDER_IMAGE: BorderImageProperty = BorderImageProperty::all(); + pub(crate) const BORDER_IMAGE: BorderImageProperty = BorderImageProperty::all(); // PORT NOTE: bitflags provides `is_empty()` already; Zig `isEmpty` maps to it. - pub fn try_from_property_id(property_id: PropertyIdTag) -> Option { + pub(crate) fn try_from_property_id(property_id: PropertyIdTag) -> Option { // PORT NOTE: Zig used `inline for` over struct fields + @field to match // "border-image-" ++ field.name. Unrolled explicitly here. match property_id { @@ -474,7 +474,7 @@ impl BorderImageProperty { } #[derive(Default)] -pub struct BorderImageHandler { +pub(crate) struct BorderImageHandler { pub source: Option, pub slice: Option, pub width: Option>, @@ -486,7 +486,7 @@ pub struct BorderImageHandler { } impl BorderImageHandler { - pub fn handle_property( + pub(crate) fn handle_property( &mut self, property: &Property, dest: &mut css::DeclarationList, @@ -586,7 +586,7 @@ impl BorderImageHandler { true } - pub fn finalize( + pub(crate) fn finalize( &mut self, dest: &mut css::DeclarationList, context: &mut css::PropertyHandlerContext, @@ -595,7 +595,7 @@ impl BorderImageHandler { self.flushed_properties = BorderImageProperty::empty(); } - pub fn reset(&mut self) { + pub(crate) fn reset(&mut self) { self.source = None; self.slice = None; self.width = None; @@ -603,7 +603,7 @@ impl BorderImageHandler { self.repeat = None; } - pub fn will_flush(&self, property: &Property) -> bool { + pub(crate) fn will_flush(&self, property: &Property) -> bool { match property { Property::BorderImageSource(_) | Property::BorderImageSlice(_) @@ -724,7 +724,7 @@ impl BorderImageHandler { } } -pub fn is_border_image_property(property_id: PropertyIdTag) -> bool { +pub(crate) fn is_border_image_property(property_id: PropertyIdTag) -> bool { matches!( property_id, PropertyIdTag::BorderImageSource diff --git a/src/css/properties/box_shadow.rs b/src/css/properties/box_shadow.rs index 6382f19ee70..f2bdad7ee88 100644 --- a/src/css/properties/box_shadow.rs +++ b/src/css/properties/box_shadow.rs @@ -52,7 +52,7 @@ impl css::generic::IsCompatible for BoxShadow { } impl BoxShadow { - pub fn parse(input: &mut css::Parser) -> css::Result { + pub(crate) fn parse(input: &mut css::Parser) -> css::Result { let mut color: Option = None; struct Lengths { x: Length, @@ -118,7 +118,7 @@ impl BoxShadow { }) } - pub fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { if self.inset { dest.write_str("inset ")?; } @@ -145,7 +145,7 @@ impl BoxShadow { Ok(()) } - pub fn deep_clone(&self, arena: &Arena) -> Self { + pub(crate) fn deep_clone(&self, arena: &Arena) -> Self { // PORT NOTE: Zig css.implementDeepClone iterated @typeInfo fields. Expanded // explicitly here — keep in sync with the BoxShadow field list. `Length` // has no `DeepClone` trait impl yet but is `Clone` (Box deep-clones). @@ -159,7 +159,7 @@ impl BoxShadow { } } - pub fn eql(&self, rhs: &Self) -> bool { + pub(crate) fn eql(&self, rhs: &Self) -> bool { // PORT NOTE: Zig css.implementEql iterated @typeInfo fields. Expanded // explicitly. `Length` Zig `eql` → Rust `PartialEq` (values/length.rs). self.color.eql(&rhs.color) @@ -170,7 +170,7 @@ impl BoxShadow { && self.inset == rhs.inset } - pub fn is_compatible(&self, browsers: &css::targets::Browsers) -> bool { + pub(crate) fn is_compatible(&self, browsers: &css::targets::Browsers) -> bool { self.color.is_compatible(browsers) && self.x_offset.is_compatible(browsers) && self.y_offset.is_compatible(browsers) @@ -186,7 +186,7 @@ pub struct BoxShadowHandler { } impl BoxShadowHandler { - pub fn handle_property( + pub(crate) fn handle_property( &mut self, property: &Property, dest: &mut css::DeclarationList, @@ -246,7 +246,7 @@ impl BoxShadowHandler { true } - pub fn finalize( + pub(crate) fn finalize( &mut self, dest: &mut css::DeclarationList, context: &mut css::PropertyHandlerContext, @@ -255,7 +255,7 @@ impl BoxShadowHandler { self.flushed = false; } - pub fn flush( + pub(crate) fn flush( &mut self, dest: &mut css::DeclarationList, context: &mut css::PropertyHandlerContext, diff --git a/src/css/properties/contain.rs b/src/css/properties/contain.rs deleted file mode 100644 index c71c0a0d097..00000000000 --- a/src/css/properties/contain.rs +++ /dev/null @@ -1,23 +0,0 @@ -use crate::SmallList; -use crate::css_rules::container::ContainerName; - -type ContainerIdent = ContainerName; - -/// A value for the [container-type](https://drafts.csswg.org/css-contain-3/#container-type) property. -/// Establishes the element as a query container for the purpose of container queries. -// TODO(port): css.DefineEnumProperty(@compileError(css.todo_stuff.depth)) — unimplemented placeholder in Zig source -pub struct ContainerType; - -/// A value for the [container-name](https://drafts.csswg.org/css-contain-3/#container-name) property. -pub enum ContainerNameList { - /// The `none` keyword. - None, - /// A list of container names. - Names(SmallList), -} - -/// A value for the [container](https://drafts.csswg.org/css-contain-3/#container-shorthand) shorthand property. -// TODO(port): css.DefineEnumProperty(@compileError(css.todo_stuff.depth)) — unimplemented placeholder in Zig source -pub struct Container; - -// ported from: src/css/properties/contain.zig diff --git a/src/css/properties/custom.rs b/src/css/properties/custom.rs index c183431a4b5..c75e77d7b6d 100644 --- a/src/css/properties/custom.rs +++ b/src/css/properties/custom.rs @@ -826,7 +826,7 @@ impl TokenList { pub type TokenListFns = TokenList; -pub type Fallbacks = (SupportsCondition, TokenList); +pub(crate) type Fallbacks = (SupportsCondition, TokenList); /// A color value with an unresolved alpha value (e.g. a variable). /// These can be converted from the modern slash syntax to older comma syntax. @@ -870,7 +870,7 @@ impl UnresolvedColor { // deinit(): body only freed owned `TokenList` fields — handled by `Drop`. - pub fn to_css(&self, dest: &mut Printer, is_custom_property: bool) -> PrintResult<()> { + pub(crate) fn to_css(&self, dest: &mut Printer, is_custom_property: bool) -> PrintResult<()> { fn conv(c: f32) -> i32 { css_values::color::clamp_unit_f32(c) as i32 } @@ -951,7 +951,7 @@ impl UnresolvedColor { } } - pub fn parse( + pub(crate) fn parse( input: &mut Parser, f: &[u8], options: &ParserOptions, @@ -999,7 +999,10 @@ impl UnresolvedColor { Err(input.new_custom_error(ParserError::invalid_value)) } - pub fn light_dark_owned(light: UnresolvedColor, dark: UnresolvedColor) -> UnresolvedColor { + pub(crate) fn light_dark_owned( + light: UnresolvedColor, + dark: UnresolvedColor, + ) -> UnresolvedColor { UnresolvedColor::LightDark { light: TokenList { v: vec![TokenOrValue::UnresolvedColor(light)], @@ -1035,7 +1038,7 @@ pub struct Variable { impl Variable { // deinit(): body only freed owned `TokenList` field — handled by `Drop`. - pub fn parse(input: &mut Parser, options: &ParserOptions, depth: usize) -> Result { + pub(crate) fn parse(input: &mut Parser, options: &ParserOptions, depth: usize) -> Result { let name = ext::dashed_ident_ref_parse(input, options)?; let fallback = if input.try_parse(|i| i.expect_comma()).is_ok() { @@ -1047,7 +1050,7 @@ impl Variable { Ok(Variable { name, fallback }) } - pub fn to_css(&self, dest: &mut Printer, is_custom_property: bool) -> PrintResult<()> { + pub(crate) fn to_css(&self, dest: &mut Printer, is_custom_property: bool) -> PrintResult<()> { dest.write_str("var(")?; ext::dashed_ident_ref_to_css(&self.name, dest)?; if let Some(fallback) = &self.fallback { @@ -1057,7 +1060,7 @@ impl Variable { dest.write_char(b')') } - pub fn get_fallback(&self, bump: &Arena, kind: ColorFallbackKind) -> Self { + pub(crate) fn get_fallback(&self, bump: &Arena, kind: ColorFallbackKind) -> Self { Variable { name: self.name, fallback: self @@ -1085,7 +1088,7 @@ pub struct EnvironmentVariable { impl EnvironmentVariable { // deinit(): body only freed owned `Vec`/`TokenList` fields — handled by `Drop`. - pub fn parse( + pub(crate) fn parse( input: &mut Parser, options: &ParserOptions, depth: usize, @@ -1094,7 +1097,7 @@ impl EnvironmentVariable { input.parse_nested_block(|i| EnvironmentVariable::parse_nested(i, options, depth)) } - pub fn parse_nested( + pub(crate) fn parse_nested( input: &mut Parser, options: &ParserOptions, depth: usize, @@ -1118,7 +1121,7 @@ impl EnvironmentVariable { }) } - pub fn to_css(&self, dest: &mut Printer, is_custom_property: bool) -> PrintResult<()> { + pub(crate) fn to_css(&self, dest: &mut Printer, is_custom_property: bool) -> PrintResult<()> { dest.write_str("env(")?; self.name.to_css(dest)?; @@ -1135,7 +1138,7 @@ impl EnvironmentVariable { dest.write_char(b')') } - pub fn get_fallback(&self, bump: &Arena, kind: ColorFallbackKind) -> Self { + pub(crate) fn get_fallback(&self, bump: &Arena, kind: ColorFallbackKind) -> Self { EnvironmentVariable { name: self.name, indices: self.indices.clone(), @@ -1163,7 +1166,7 @@ pub enum EnvironmentVariableName { impl EnvironmentVariableName { // eql / hash — provided by `#[derive(CssEql, CssHash)]`. - pub fn parse(input: &mut Parser) -> Result { + pub(crate) fn parse(input: &mut Parser) -> Result { if let Ok(ua) = input.try_parse(UAEnvironmentVariable::parse) { return Ok(EnvironmentVariableName::Ua(ua)); } @@ -1178,7 +1181,7 @@ impl EnvironmentVariableName { Ok(EnvironmentVariableName::Unknown(ident)) } - pub fn to_css(&self, dest: &mut Printer) -> PrintResult<()> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> PrintResult<()> { match self { EnvironmentVariableName::Ua(ua) => ua.to_css(dest), EnvironmentVariableName::Custom(custom) => ext::dashed_ident_ref_to_css(custom, dest), @@ -1228,13 +1231,9 @@ pub enum UAEnvironmentVariable { // hash — via `#[derive(CssHash)]` (the derive emits UFCS, so no inherent shim needed). impl UAEnvironmentVariable { #[inline] - pub fn eql(self, other: Self) -> bool { + pub(crate) fn eql(self, other: Self) -> bool { self == other } - #[inline] - pub fn deep_clone(self, _bump: &Arena) -> Self { - self - } } impl EnumProperty for UAEnvironmentVariable { @@ -1274,7 +1273,7 @@ pub struct Function { impl Function { // deinit(): body only freed owned `TokenList` field — handled by `Drop`. - pub fn to_css(&self, dest: &mut Printer, is_custom_property: bool) -> PrintResult<()> { + pub(crate) fn to_css(&self, dest: &mut Printer, is_custom_property: bool) -> PrintResult<()> { IdentFns::to_css(&self.name, dest)?; dest.write_char(b'(')?; self.arguments.to_css(dest, is_custom_property)?; @@ -1283,7 +1282,7 @@ impl Function { // eql / hash / deep_clone — provided by `#[derive(CssEql, CssHash, DeepClone)]`. - pub fn get_fallback(&self, bump: &Arena, kind: ColorFallbackKind) -> Self { + pub(crate) fn get_fallback(&self, bump: &Arena, kind: ColorFallbackKind) -> Self { Function { name: self.name, arguments: self.arguments.get_fallback(bump, kind), @@ -1327,7 +1326,7 @@ impl TokenOrValue { // deinit(): all arms only freed owned fields — handled by `Drop`. - pub fn is_whitespace(&self) -> bool { + pub(crate) fn is_whitespace(&self) -> bool { matches!(self, TokenOrValue::Token(Token::Whitespace(_))) } } @@ -1444,7 +1443,7 @@ pub struct UnparsedProperty { } impl UnparsedProperty { - pub fn parse( + pub(crate) fn parse( property_id: css::properties::PropertyId, input: &mut Parser, options: &ParserOptions, @@ -1456,7 +1455,7 @@ impl UnparsedProperty { Ok(UnparsedProperty { property_id, value }) } - pub fn get_prefixed( + pub(crate) fn get_prefixed( &self, bump: &Arena, targets: &css::targets::Targets, @@ -1471,7 +1470,7 @@ impl UnparsedProperty { } /// Returns a new UnparsedProperty with the same value and the given property id. - pub fn with_property_id( + pub(crate) fn with_property_id( &self, bump: &Arena, property_id: css::properties::PropertyId, @@ -1482,14 +1481,14 @@ impl UnparsedProperty { } } - pub fn deep_clone(&self, bump: &Arena) -> Self { + pub(crate) fn deep_clone(&self, bump: &Arena) -> Self { UnparsedProperty { property_id: self.property_id.deep_clone(bump), value: self.value.deep_clone(bump), } } - pub fn eql(&self, rhs: &Self) -> bool { + pub(crate) fn eql(&self, rhs: &Self) -> bool { // `PropertyId` is `Copy` (tag + optional `VendorPrefix`/`CustomPropertyName`) // and derives `PartialEq` in `properties_generated.rs` — use `==` directly. self.property_id == rhs.property_id && self.value.eql(&rhs.value) @@ -1505,7 +1504,7 @@ pub struct CustomProperty { } impl CustomProperty { - pub fn parse( + pub(crate) fn parse( name: CustomPropertyName, input: &mut Parser, options: &ParserOptions, @@ -1518,14 +1517,14 @@ impl CustomProperty { Ok(CustomProperty { name, value }) } - pub fn deep_clone(&self, bump: &Arena) -> Self { + pub(crate) fn deep_clone(&self, bump: &Arena) -> Self { CustomProperty { name: self.name.deep_clone(bump), value: self.value.deep_clone(bump), } } - pub fn eql(&self, rhs: &Self) -> bool { + pub(crate) fn eql(&self, rhs: &Self) -> bool { self.name.eql(&rhs.name) && self.value.eql(&rhs.value) } } @@ -1596,7 +1595,7 @@ impl CustomPropertyName { // deep_clone / eql — provided by `#[derive(DeepClone, CssEql)]`. } -pub fn try_parse_color_token( +pub(crate) fn try_parse_color_token( f: &[u8], state: &ParserState, input: &mut Parser, diff --git a/src/css/properties/display.rs b/src/css/properties/display.rs index 0342bd7e1f6..676843912d5 100644 --- a/src/css/properties/display.rs +++ b/src/css/properties/display.rs @@ -14,24 +14,19 @@ pub enum Display { // PORT NOTE: Zig `DeriveParse`/`DeriveToCss` for a 2-payload union(enum) tries each // payload's `parse` in declaration order; `toCss` dispatches to the active payload. impl Display { - pub fn parse(input: &mut Parser) -> css::Result { + pub(crate) fn parse(input: &mut Parser) -> css::Result { if let Ok(kw) = input.try_parse(DisplayKeyword::parse) { return Ok(Display::Keyword(kw)); } DisplayPair::parse(input).map(Display::Pair) } - pub fn to_css(self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(self, dest: &mut Printer) -> Result<(), PrintErr> { match self { Display::Keyword(kw) => kw.to_css(dest), Display::Pair(p) => p.to_css(dest), } } - - pub fn deep_clone(self, _bump: &bun_alloc::Arena) -> Self { - // All payloads are Copy. - self - } } /// A value for the [visibility](https://drafts.csswg.org/css-display-3/#visibility) property. @@ -80,7 +75,7 @@ pub struct DisplayPair { } impl DisplayPair { - pub fn parse(input: &mut Parser) -> css::Result { + pub(crate) fn parse(input: &mut Parser) -> css::Result { let mut list_item = false; let mut outside: Option = None; let mut inside: Option = None; @@ -165,7 +160,7 @@ impl DisplayPair { }) } - pub fn to_css(self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(self, dest: &mut Printer) -> Result<(), PrintErr> { // PORT NOTE: reshaped Zig if-else chain into match for tagged-union payload extraction. match (self.outside, &self.inside, self.is_list_item) { (DisplayOutside::Inline, DisplayInside::FlowRoot, false) => { @@ -244,7 +239,7 @@ pub enum DisplayInside { } impl DisplayInside { - pub fn parse(input: &mut Parser) -> css::Result { + pub(crate) fn parse(input: &mut Parser) -> css::Result { let location = input.current_source_location(); let ident = input.expect_ident_cloned()?; @@ -276,7 +271,7 @@ impl DisplayInside { }) } - pub fn to_css(self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(self, dest: &mut Printer) -> Result<(), PrintErr> { match self { DisplayInside::Flow => dest.write_str("flow"), DisplayInside::FlowRoot => dest.write_str("flow-root"), diff --git a/src/css/properties/effects.rs b/src/css/properties/effects.rs index 95ce779d710..c3d71c41cec 100644 --- a/src/css/properties/effects.rs +++ b/src/css/properties/effects.rs @@ -1,58 +1 @@ -use crate::css_parser as css; - -use css::SmallList; - -use css::css_values::angle::Angle; -use css::css_values::color::CssColor; -use css::css_values::length::LengthValue as Length; -use css::css_values::percentage::NumberOrPercentage; -use css::css_values::url::Url; - -/// A value for the [filter](https://drafts.fxtf.org/filter-effects-1/#FilterProperty) and -/// [backdrop-filter](https://drafts.fxtf.org/filter-effects-2/#BackdropFilterProperty) properties. -pub enum FilterList { - /// The `none` keyword. - None, - /// A list of filter functions. - Filters(SmallList), -} - -/// A [filter](https://drafts.fxtf.org/filter-effects-1/#filter-functions) function. -pub enum Filter { - /// A `blur()` filter. - Blur(Length), - /// A `brightness()` filter. - Brightness(NumberOrPercentage), - /// A `contrast()` filter. - Contrast(NumberOrPercentage), - /// A `grayscale()` filter. - Grayscale(NumberOrPercentage), - /// A `hue-rotate()` filter. - HueRotate(Angle), - /// An `invert()` filter. - Invert(NumberOrPercentage), - /// An `opacity()` filter. - Opacity(NumberOrPercentage), - /// A `saturate()` filter. - Saturate(NumberOrPercentage), - /// A `sepia()` filter. - Sepia(NumberOrPercentage), - /// A `drop-shadow()` filter. - DropShadow(DropShadow), - /// A `url()` reference to an SVG filter. - Url(Url), -} - -/// A [`drop-shadow()`](https://drafts.fxtf.org/filter-effects-1/#funcdef-filter-drop-shadow) filter function. -pub struct DropShadow { - /// The color of the drop shadow. - pub color: CssColor, - /// The x offset of the drop shadow. - pub x_offset: Length, - /// The y offset of the drop shadow. - pub y_offset: Length, - /// The blur radius of the drop shadow. - pub blur: Length, -} - // ported from: src/css/properties/effects.zig diff --git a/src/css/properties/flex.rs b/src/css/properties/flex.rs index ab89c53c52a..3f7a4408a13 100644 --- a/src/css/properties/flex.rs +++ b/src/css/properties/flex.rs @@ -28,7 +28,7 @@ pub enum FlexDirection { } impl FlexDirection { - pub fn to_2009(self) -> (BoxOrient, BoxDirection) { + pub(crate) fn to_2009(self) -> (BoxOrient, BoxDirection) { match self { FlexDirection::Row => (BoxOrient::Horizontal, BoxDirection::Normal), FlexDirection::Column => (BoxOrient::Vertical, BoxDirection::Normal), @@ -51,12 +51,6 @@ pub enum FlexWrap { WrapReverse, } -impl FlexWrap { - pub fn from_standard(self) -> Option { - Some(self) - } -} - /// A value for the [flex-flow](https://www.w3.org/TR/2018/CR-css-flexbox-1-20181119/#flex-flow-property) shorthand property. #[derive(Clone, PartialEq, Eq)] pub struct FlexFlow { @@ -73,7 +67,7 @@ pub struct FlexFlow { // VendorPrefixMap = { direction: true, wrap: true } impl FlexFlow { - pub fn parse(input: &mut css::Parser) -> css::Result { + pub(crate) fn parse(input: &mut css::Parser) -> css::Result { let mut direction: Option = None; let mut wrap: Option = None; @@ -99,7 +93,7 @@ impl FlexFlow { }) } - pub fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { let mut needs_space = false; if self.direction != FlexDirection::default() || self.wrap == FlexWrap::default() { self.direction.to_css(dest)?; @@ -135,7 +129,7 @@ pub struct Flex { // VendorPrefixMap = { grow: true, shrink: true, basis: true } impl Flex { - pub fn parse(input: &mut css::Parser) -> css::Result { + pub(crate) fn parse(input: &mut css::Parser) -> css::Result { if input .try_parse(|i| i.expect_ident_matching(b"none")) .is_ok() @@ -179,7 +173,7 @@ impl Flex { }) } - pub fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { if self.grow == 0.0 && self.shrink == 0.0 && matches!(self.basis, LengthPercentageOrAuto::Auto) @@ -259,7 +253,7 @@ pub enum BoxDirection { Reverse, } -pub type FlexAlign = BoxAlign; +pub(crate) type FlexAlign = BoxAlign; /// A value for the legacy (prefixed) [box-align](https://www.w3.org/TR/2009/WD-css3-flexbox-20090723/#alignment) property. /// Equivalent to the `align-items` property in the standard syntax. @@ -280,7 +274,7 @@ pub enum BoxAlign { } impl BoxAlign { - pub fn from_standard(align: &AlignItems) -> Option { + pub(crate) fn from_standard(align: &AlignItems) -> Option { use css::css_properties::align::SelfPosition; match align { AlignItems::SelfPosition(sp) => { @@ -318,7 +312,7 @@ pub enum BoxPack { } impl BoxPack { - pub fn from_standard(justify: &JustifyContent) -> Option { + pub(crate) fn from_standard(justify: &JustifyContent) -> Option { use css::css_properties::align::{ContentDistribution, ContentPosition}; match justify { JustifyContent::ContentDistribution(cd) => match cd { @@ -354,7 +348,7 @@ pub enum BoxLines { } impl BoxLines { - pub fn from_standard(wrap: FlexWrap) -> Option { + pub(crate) fn from_standard(wrap: FlexWrap) -> Option { match wrap { FlexWrap::Nowrap => Some(BoxLines::Single), FlexWrap::Wrap => Some(BoxLines::Multiple), @@ -383,7 +377,7 @@ pub enum FlexPack { } impl FlexPack { - pub fn from_standard(justify: &JustifyContent) -> Option { + pub(crate) fn from_standard(justify: &JustifyContent) -> Option { use css::css_properties::align::{ContentDistribution, ContentPosition}; match justify { JustifyContent::ContentDistribution(cd) => match cd { @@ -430,7 +424,7 @@ pub enum FlexItemAlign { } impl FlexItemAlign { - pub fn from_standard(justify: &AlignSelf) -> Option { + pub(crate) fn from_standard(justify: &AlignSelf) -> Option { use css::css_properties::align::SelfPosition; match justify { AlignSelf::Auto => Some(FlexItemAlign::Auto), @@ -473,7 +467,7 @@ pub enum FlexLinePack { } impl FlexLinePack { - pub fn from_standard(justify: &AlignContent) -> Option { + pub(crate) fn from_standard(justify: &AlignContent) -> Option { use css::css_properties::align::{ContentDistribution, ContentPosition}; match justify { AlignContent::ContentDistribution(cd) => match cd { @@ -500,7 +494,7 @@ impl FlexLinePack { } } -pub type BoxOrdinalGroup = CSSInteger; +pub(crate) type BoxOrdinalGroup = CSSInteger; // A handler for flex-related properties that manages both standard and legacy vendor prefixed values. #[derive(Default)] @@ -540,7 +534,7 @@ pub struct FlexHandler { } impl FlexHandler { - pub fn handle_property( + pub(crate) fn handle_property( &mut self, property: &Property, dest: &mut css::DeclarationList, @@ -666,7 +660,7 @@ impl FlexHandler { true } - pub fn finalize( + pub(crate) fn finalize( &mut self, dest: &mut css::DeclarationList, context: &mut css::PropertyHandlerContext, diff --git a/src/css/properties/font.rs b/src/css/properties/font.rs index c4e764e310c..125b7ccead1 100644 --- a/src/css/properties/font.rs +++ b/src/css/properties/font.rs @@ -53,7 +53,7 @@ impl FontWeight { // PORT NOTE: Zig `css.DeriveParse(@This()).parse` for a union(enum) with one // payload variant + 2 keyword variants tries the payload first, then matches // the remaining keywords against `expect_ident`. - pub fn parse(input: &mut css::Parser) -> CssResult { + pub(crate) fn parse(input: &mut css::Parser) -> CssResult { if let Ok(v) = input.try_parse(AbsoluteFontWeight::parse) { return Ok(FontWeight::Absolute(v)); } @@ -66,7 +66,7 @@ impl FontWeight { }} } - pub fn to_css(&self, dest: &mut Printer) -> PrintResult<()> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> PrintResult<()> { match self { FontWeight::Absolute(a) => a.to_css(dest), FontWeight::Bolder => dest.write_str("bolder"), @@ -75,11 +75,11 @@ impl FontWeight { } #[inline] - pub fn default() -> FontWeight { + pub(crate) fn default() -> FontWeight { FontWeight::Absolute(AbsoluteFontWeight::default()) } - pub fn is_compatible(&self, browsers: &crate::targets::Browsers) -> bool { + pub(crate) fn is_compatible(&self, browsers: &crate::targets::Browsers) -> bool { match self { FontWeight::Absolute(a) => a.is_compatible(browsers), FontWeight::Bolder | FontWeight::Lighter => true, @@ -107,7 +107,7 @@ pub enum AbsoluteFontWeight { impl AbsoluteFontWeight { // PORT NOTE: Zig `css.DeriveParse(@This()).parse` — payload (`CSSNumber`) first, // then keyword variants. - pub fn parse(input: &mut css::Parser) -> CssResult { + pub(crate) fn parse(input: &mut css::Parser) -> CssResult { if let Ok(n) = input.try_parse(CSSNumberFns::parse) { return Ok(AbsoluteFontWeight::Weight(n)); } @@ -120,7 +120,7 @@ impl AbsoluteFontWeight { }} } - pub fn to_css(&self, dest: &mut Printer) -> PrintResult<()> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> PrintResult<()> { match self { AbsoluteFontWeight::Weight(weight) => CSSNumberFns::to_css(*weight, dest), AbsoluteFontWeight::Normal => { @@ -130,7 +130,7 @@ impl AbsoluteFontWeight { } } - pub fn is_compatible(&self, browsers: &crate::targets::Browsers) -> bool { + pub(crate) fn is_compatible(&self, browsers: &crate::targets::Browsers) -> bool { match self { // Older browsers only supported 100, 200, 300, ...900 rather than arbitrary values. AbsoluteFontWeight::Weight(val) => { @@ -145,7 +145,7 @@ impl AbsoluteFontWeight { } #[inline] - pub fn default() -> AbsoluteFontWeight { + pub(crate) fn default() -> AbsoluteFontWeight { AbsoluteFontWeight::Normal } @@ -167,7 +167,7 @@ impl FontSize { // parse + to_css — provided by #[derive(css::Parse, css::ToCss)]. // is_compatible KEPT (custom Rem branch). - pub fn is_compatible(&self, browsers: &crate::targets::Browsers) -> bool { + pub(crate) fn is_compatible(&self, browsers: &crate::targets::Browsers) -> bool { match self { FontSize::Length(l) => match l { DimensionPercentage::Dimension(LengthValue::Rem(_)) => { @@ -209,7 +209,7 @@ pub enum AbsoluteFontSize { } impl AbsoluteFontSize { - pub fn is_compatible(self, browsers: &crate::targets::Browsers) -> bool { + pub(crate) fn is_compatible(self, browsers: &crate::targets::Browsers) -> bool { match self { AbsoluteFontSize::XxxLarge => Feature::FontSizeXXXLarge.is_compatible(browsers), _ => true, @@ -239,14 +239,14 @@ pub enum FontStretch { impl FontStretch { // PORT NOTE: Zig `css.DeriveParse(@This()).parse` — two payload variants // tried in declaration order. - pub fn parse(input: &mut css::Parser) -> CssResult { + pub(crate) fn parse(input: &mut css::Parser) -> CssResult { if let Ok(kw) = input.try_parse(FontStretchKeyword::parse) { return Ok(FontStretch::Keyword(kw)); } Percentage::parse(input).map(FontStretch::Percentage) } - pub fn to_css(self, dest: &mut Printer) -> PrintResult<()> { + pub(crate) fn to_css(self, dest: &mut Printer) -> PrintResult<()> { if dest.minify { let percentage: Percentage = self.into_percentage(); return percentage.to_css(dest); @@ -258,14 +258,14 @@ impl FontStretch { } } - pub fn into_percentage(self) -> Percentage { + pub(crate) fn into_percentage(self) -> Percentage { match self { FontStretch::Percentage(val) => val, FontStretch::Keyword(kw) => kw.into_percentage(), } } - pub fn is_compatible(self, browsers: &crate::targets::Browsers) -> bool { + pub(crate) fn is_compatible(self, browsers: &crate::targets::Browsers) -> bool { match self { FontStretch::Percentage(_) => Feature::FontStretchPercentage.is_compatible(browsers), FontStretch::Keyword(_) => true, @@ -276,7 +276,7 @@ impl FontStretch { // deepClone → derived Clone #[inline] - pub fn default() -> FontStretch { + pub(crate) fn default() -> FontStretch { FontStretch::Keyword(FontStretchKeyword::default()) } } @@ -309,11 +309,11 @@ pub enum FontStretchKeyword { impl FontStretchKeyword { #[inline] - pub fn default() -> FontStretchKeyword { + pub(crate) fn default() -> FontStretchKeyword { FontStretchKeyword::Normal } - pub fn into_percentage(self) -> Percentage { + pub(crate) fn into_percentage(self) -> Percentage { let val: f32 = match self { FontStretchKeyword::UltraCondensed => 0.5, FontStretchKeyword::ExtraCondensed => 0.625, @@ -343,10 +343,10 @@ pub enum FontFamily { // TODO(port): Zig defined `pub fn HashMap(comptime V: type) type` wrapping std.ArrayHashMapUnmanaged // with a custom Wyhash hasher over the family-name bytes. Module-level alias (inherent assoc types are nightly-only). // blocked_on: ArrayHashMap key trait bounds for FontFamily -pub type FontFamilyHashMap = bun_collections::ArrayHashMap; +pub(crate) type FontFamilyHashMap = bun_collections::ArrayHashMap; impl FontFamily { - pub fn parse(input: &mut css::Parser) -> CssResult { + pub(crate) fn parse(input: &mut css::Parser) -> CssResult { if let Ok(value) = input.try_parse(|p| p.expect_string().map(std::ptr::from_ref::<[u8]>)) { // arena-owned: parser slice lives for 'bump return Ok(FontFamily::FamilyName(value)); @@ -386,7 +386,7 @@ impl FontFamily { Ok(FontFamily::FamilyName(final_value)) } - pub fn to_css(&self, dest: &mut Printer) -> PrintResult<()> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> PrintResult<()> { match self { FontFamily::Generic(val) => val.to_css(dest), FontFamily::FamilyName(val_ptr) => { @@ -425,7 +425,7 @@ impl FontFamily { } } - pub fn is_compatible(&self, browsers: &crate::targets::Browsers) -> bool { + pub(crate) fn is_compatible(&self, browsers: &crate::targets::Browsers) -> bool { match self { FontFamily::Generic(g) => g.is_compatible(browsers), FontFamily::FamilyName(_) => true, @@ -517,7 +517,7 @@ pub enum GenericFontFamily { } impl GenericFontFamily { - pub fn is_compatible(self, browsers: &crate::targets::Browsers) -> bool { + pub(crate) fn is_compatible(self, browsers: &crate::targets::Browsers) -> bool { match self { GenericFontFamily::SystemUi => Feature::FontFamilySystemUi.is_compatible(browsers), GenericFontFamily::UiSerif @@ -541,11 +541,11 @@ pub enum FontStyle { } impl FontStyle { - pub fn default() -> FontStyle { + pub(crate) fn default() -> FontStyle { FontStyle::Normal } - pub fn parse(input: &mut css::Parser) -> CssResult { + pub(crate) fn parse(input: &mut css::Parser) -> CssResult { let location = input.current_source_location(); let ident = input.expect_ident_cloned()?; crate::match_ignore_ascii_case! { ident, { @@ -561,7 +561,7 @@ impl FontStyle { }} } - pub fn to_css(self, dest: &mut Printer) -> PrintResult<()> { + pub(crate) fn to_css(self, dest: &mut Printer) -> PrintResult<()> { match self { FontStyle::Normal => dest.write_str("normal"), FontStyle::Italic => dest.write_str("italic"), @@ -576,7 +576,7 @@ impl FontStyle { } } - pub fn is_compatible(self, browsers: &crate::targets::Browsers) -> bool { + pub(crate) fn is_compatible(self, browsers: &crate::targets::Browsers) -> bool { match self { FontStyle::Oblique(angle) => { if angle != FontStyle::default_oblique_angle() { @@ -589,7 +589,7 @@ impl FontStyle { } } - pub fn default_oblique_angle() -> Angle { + pub(crate) fn default_oblique_angle() -> Angle { Angle::Deg(14.0) } @@ -617,7 +617,7 @@ pub enum FontVariantCaps { } impl FontVariantCaps { - pub fn default() -> FontVariantCaps { + pub(crate) fn default() -> FontVariantCaps { FontVariantCaps::Normal } @@ -625,7 +625,7 @@ impl FontVariantCaps { matches!(self, FontVariantCaps::Normal | FontVariantCaps::SmallCaps) } - pub fn parse_css2(input: &mut css::Parser) -> CssResult { + pub(crate) fn parse_css2(input: &mut css::Parser) -> CssResult { let value = FontVariantCaps::parse(input)?; if !value.is_css2() { return Err(input.new_custom_error(ParserError::invalid_value)); @@ -633,7 +633,7 @@ impl FontVariantCaps { Ok(value) } - pub fn is_compatible(self, _: &crate::targets::Browsers) -> bool { + pub(crate) fn is_compatible(self, _: &crate::targets::Browsers) -> bool { true } } @@ -652,7 +652,7 @@ pub enum LineHeight { impl LineHeight { // PORT NOTE: Zig `css.DeriveParse(@This()).parse` — keyword variant first // (`normal`), then payload variants in declaration order. - pub fn parse(input: &mut css::Parser) -> CssResult { + pub(crate) fn parse(input: &mut css::Parser) -> CssResult { if input .try_parse(|p| p.expect_ident_matching(b"normal")) .is_ok() @@ -665,7 +665,7 @@ impl LineHeight { LengthPercentage::parse(input).map(LineHeight::Length) } - pub fn to_css(&self, dest: &mut Printer) -> PrintResult<()> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> PrintResult<()> { match self { LineHeight::Normal => dest.write_str("normal"), LineHeight::Number(n) => CSSNumberFns::to_css(*n, dest), @@ -673,7 +673,7 @@ impl LineHeight { } } - pub fn is_compatible(&self, browsers: &crate::targets::Browsers) -> bool { + pub(crate) fn is_compatible(&self, browsers: &crate::targets::Browsers) -> bool { match self { LineHeight::Length(l) => l.is_compatible(browsers), LineHeight::Normal | LineHeight::Number(_) => true, @@ -683,7 +683,7 @@ impl LineHeight { // eql → derived PartialEq // deepClone → derived Clone - pub fn default() -> LineHeight { + pub(crate) fn default() -> LineHeight { LineHeight::Normal } } @@ -714,22 +714,7 @@ pub struct Font { impl Font { // (old using name space) css.DefineShorthand(@This(), css.PropertyIdTag.font, PropertyFieldMap); - // PORT NOTE: PropertyFieldMap was a comptime anon-struct mapping field names → PropertyIdTag, - // consumed by DefineShorthand reflection. Represented here as a const array. - pub const PROPERTY_FIELD_MAP: &'static [(&'static str, crate::properties::PropertyIdTag)] = &[ - ("family", crate::properties::PropertyIdTag::FontFamily), - ("size", crate::properties::PropertyIdTag::FontSize), - ("style", crate::properties::PropertyIdTag::FontStyle), - ("weight", crate::properties::PropertyIdTag::FontWeight), - ("stretch", crate::properties::PropertyIdTag::FontStretch), - ("line_height", crate::properties::PropertyIdTag::LineHeight), - ( - "variant_caps", - crate::properties::PropertyIdTag::FontVariantCaps, - ), - ]; - - pub fn parse(input: &mut css::Parser) -> CssResult { + pub(crate) fn parse(input: &mut css::Parser) -> CssResult { let mut style: Option = None; let mut weight: Option = None; let mut stretch: Option = None; @@ -811,7 +796,7 @@ impl Font { }) } - pub fn to_css(&self, dest: &mut Printer) -> PrintResult<()> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> PrintResult<()> { if self.style != FontStyle::default() { self.style.to_css(dest)?; dest.write_char(b' ')?; @@ -855,19 +840,9 @@ impl Font { // deepClone → css::implementDeepClone (generics blanket impl) } -/// A value for the [vertical align](https://drafts.csswg.org/css2/#propdef-vertical-align) property. -// TODO: there is a more extensive spec in CSS3 but it doesn't seem any browser implements it? https://www.w3.org/TR/css-inline-3/#transverse-alignment -#[derive(Clone, PartialEq)] -pub enum VerticalAlign { - /// A vertical align keyword. - Keyword(VerticalAlignKeyword), - /// An explicit length. - Length(LengthPercentage), -} - /// A keyword for the [vertical align](https://drafts.csswg.org/css2/#propdef-vertical-align) property. #[derive(Clone, Copy, PartialEq, Eq, Hash, css::DefineEnumProperty)] -pub enum VerticalAlignKeyword { +pub(crate) enum VerticalAlignKeyword { /// Align the baseline of the box with the baseline of the parent box. Baseline, /// Lower the baseline of the box to the proper position for subscripts of the parent's box. @@ -888,7 +863,7 @@ pub enum VerticalAlignKeyword { bitflags::bitflags! { #[derive(Default, Clone, Copy, PartialEq, Eq)] - pub struct FontProperty: u8 { + pub(crate) struct FontProperty: u8 { const FONT_FAMILY = 1 << 0; const FONT_SIZE = 1 << 1; const FONT_STYLE = 1 << 2; @@ -903,7 +878,7 @@ bitflags::bitflags! { impl FontProperty { const FONT: FontProperty = FontProperty::all(); - pub fn try_from_property_id( + pub(crate) fn try_from_property_id( property_id: crate::properties::PropertyIdTag, ) -> Option { // TODO(port): Zig used `inline for` over std.meta.fields + @field; expanded by hand @@ -939,7 +914,7 @@ impl FontHandler { // blocked_on: generics::is_compatible/eql/deepClone blankets, // PropertyHandlerContext::arena(), DeclarationList::push, // Property::Font*/Unparsed payloads, FontFamilyHashMap. - pub fn handle_property( + pub(crate) fn handle_property( &mut self, property: &crate::properties::Property, dest: &mut crate::DeclarationList<'_>, @@ -1019,7 +994,7 @@ impl FontHandler { true } - pub fn finalize( + pub(crate) fn finalize( &mut self, decls: &mut crate::DeclarationList<'_>, context: &mut crate::PropertyHandlerContext<'_>, diff --git a/src/css/properties/list.rs b/src/css/properties/list.rs index 09cdbd45723..bbc9f7cc9f0 100644 --- a/src/css/properties/list.rs +++ b/src/css/properties/list.rs @@ -1,66 +1 @@ -use crate::css_values::ident::CustomIdent; -use crate::css_values::image::Image; -use crate::css_values::string::CssString; - -/// A value for the [list-style-type](https://www.w3.org/TR/2020/WD-css-lists-3-20201117/#text-markers) property. -pub enum ListStyleType<'bump> { - /// No marker. - None, - /// An explicit marker string. - String(CssString), - /// A named counter style. - CounterStyle(CounterStyle<'bump>), -} - -/// A [counter-style](https://www.w3.org/TR/css-counter-styles-3/#typedef-counter-style) name. -pub enum CounterStyle<'bump> { - /// A predefined counter style name. - Predefined(PredefinedCounterStyle), - /// A custom counter style name. - Name(CustomIdent), - /// An inline `symbols()` definition. - Symbols(Symbols<'bump>), -} - -pub struct Symbols<'bump> { - /// The counter system. - pub system: SymbolsType, - /// The symbols. - pub symbols: bun_alloc::ArenaVec<'bump, Symbol>, -} - -/// A single [symbol](https://www.w3.org/TR/css-counter-styles-3/#funcdef-symbols) as used in the -/// `symbols()` function. -/// -/// See [CounterStyle](CounterStyle). -pub enum Symbol { - /// A string. - String(CssString), - /// An image. - Image(Image), -} - -/// A [predefined counter](https://www.w3.org/TR/css-counter-styles-3/#predefined-counters) style. -// TODO(port): Zig source is `@compileError(css.todo_stuff.depth)` — unimplemented upstream -pub enum PredefinedCounterStyle {} - -/// A [``](https://www.w3.org/TR/css-counter-styles-3/#typedef-symbols-type) value, -/// as used in the `symbols()` function. -/// -/// See [CounterStyle](CounterStyle). -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(css.todo_stuff.depth))` — unimplemented upstream -pub enum SymbolsType {} - -/// A value for the [list-style-position](https://www.w3.org/TR/2020/WD-css-lists-3-20201117/#list-style-position-property) property. -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(css.todo_stuff.depth))` — unimplemented upstream -pub enum ListStylePosition {} - -/// A value for the [list-style](https://www.w3.org/TR/2020/WD-css-lists-3-20201117/#list-style-property) shorthand property. -// TODO(port): Zig source is `@compileError(css.todo_stuff.depth)` — unimplemented upstream -pub struct ListStyle; - -/// A value for the [marker-side](https://www.w3.org/TR/2020/WD-css-lists-3-20201117/#marker-side) property. -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(css.todo_stuff.depth))` — unimplemented upstream -pub enum MarkerSide {} - // ported from: src/css/properties/list.zig diff --git a/src/css/properties/mod.rs b/src/css/properties/mod.rs index 4d7e5c7d397..85ee46adb5f 100644 --- a/src/css/properties/mod.rs +++ b/src/css/properties/mod.rs @@ -162,7 +162,6 @@ pub mod border_radius; // `box_shadow`: un-gated — real BoxShadow + BoxShadowHandler live in // `box_shadow.rs`. pub mod box_shadow; -pub mod contain; pub mod display; pub mod effects; pub mod flex; @@ -405,7 +404,7 @@ mod generic_registrations { /// Indirection so the `generic::{Parse,ToCss}` impls above don't have to /// repeat `GenericBorder`'s `S`-bounds (which name the same protocol /// traits and would otherwise create a coherence cycle). - pub trait GenericBorderImpl: Sized { + pub(crate) trait GenericBorderImpl: Sized { fn parse(input: &mut crate::css_parser::Parser) -> crate::css_parser::CssResult; fn to_css( &self, diff --git a/src/css/properties/outline.rs b/src/css/properties/outline.rs index c540ae448e7..9f42cdc663a 100644 --- a/src/css/properties/outline.rs +++ b/src/css/properties/outline.rs @@ -1,7 +1,7 @@ use super::border::{GenericBorder, LineStyle}; /// A value for the [outline](https://drafts.csswg.org/css-ui/#outline) shorthand property. -pub type Outline = GenericBorder; +pub(crate) type Outline = GenericBorder; /// A value for the [outline-style](https://drafts.csswg.org/css-ui/#outline-style) property. // `DeriveParse`/`DeriveToCss` in Zig are comptime-reflection helpers that iterate variants @@ -21,15 +21,4 @@ impl Default for OutlineStyle { } } -impl OutlineStyle { - pub fn eql(lhs: &Self, rhs: &Self) -> bool { - lhs == rhs - } - - pub fn deep_clone(&self, _bump: &bun_alloc::Arena) -> Self { - // PERF(port): was arena-aware implementDeepClone — variants are POD so Clone suffices - self.clone() - } -} - // ported from: src/css/properties/outline.zig diff --git a/src/css/properties/overflow.rs b/src/css/properties/overflow.rs index fc4904073de..f6613e7c245 100644 --- a/src/css/properties/overflow.rs +++ b/src/css/properties/overflow.rs @@ -11,13 +11,13 @@ pub struct Overflow { } impl Overflow { - pub fn parse(input: &mut Parser) -> css::Result { + pub(crate) fn parse(input: &mut Parser) -> css::Result { let x = OverflowKeyword::parse(input)?; let y = input.try_parse(OverflowKeyword::parse).unwrap_or(x); Ok(Overflow { x, y }) } - pub fn to_css(self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(self, dest: &mut Printer) -> Result<(), PrintErr> { self.x.to_css(dest)?; if self.y != self.x { dest.write_char(b' ')?; diff --git a/src/css/properties/position.rs b/src/css/properties/position.rs index 18c8c7ec677..944b2bc6d9e 100644 --- a/src/css/properties/position.rs +++ b/src/css/properties/position.rs @@ -49,7 +49,7 @@ fn lookup_keyword(ident: &[u8]) -> Option { } impl Position { - pub fn parse(input: &mut Parser) -> css::Result { + pub(crate) fn parse(input: &mut Parser) -> css::Result { let location = input.current_source_location(); let ident = input.expect_ident_cloned()?; @@ -67,7 +67,7 @@ impl Position { }) } - pub fn to_css(self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(self, dest: &mut Printer) -> Result<(), PrintErr> { match self { Position::Static => dest.write_str("static"), Position::Relative => dest.write_str("relative"), @@ -79,18 +79,6 @@ impl Position { } } } - - pub fn eql(self, rhs: Self) -> bool { - // Zig: css.implementEql(@This(), lhs, rhs) — comptime-reflection structural eq. - // Rust: covered by #[derive(PartialEq)]. - self == rhs - } - - pub fn deep_clone(self) -> Self { - // Zig: css.implementDeepClone(@This(), this, arena) — comptime-reflection deep copy. - // Rust: covered by #[derive(Clone)]; arena param dropped (global mimalloc). - self - } } // ported from: src/css/properties/position.zig diff --git a/src/css/properties/prefix_handler.rs b/src/css/properties/prefix_handler.rs index aad73e913e1..e3bebada314 100644 --- a/src/css/properties/prefix_handler.rs +++ b/src/css/properties/prefix_handler.rs @@ -19,7 +19,7 @@ pub struct FallbackHandler { } impl FallbackHandler { - pub fn handle_property( + pub(crate) fn handle_property( &mut self, property: &Property, dest: &mut css::DeclarationList, @@ -156,7 +156,7 @@ impl FallbackHandler { false } - pub fn finalize( + pub(crate) fn finalize( &mut self, _dest: &mut css::DeclarationList, _context: &mut css::PropertyHandlerContext, diff --git a/src/css/properties/properties_impl.rs b/src/css/properties/properties_impl.rs index 199b2062b99..aa1295dd1a5 100644 --- a/src/css/properties/properties_impl.rs +++ b/src/css/properties/properties_impl.rs @@ -44,10 +44,10 @@ pub(super) const PREFIX_FLAGS: [VendorPrefix; 5] = [ VendorPrefix::NONE, ]; -pub mod property_id_mixin { +pub(super) mod property_id_mixin { use super::*; - pub fn to_css(this: &PropertyId, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(this: &PropertyId, dest: &mut Printer) -> Result<(), PrintErr> { let name = this.name(); let prefix_value = this.prefix().or_none(); @@ -66,25 +66,29 @@ pub mod property_id_mixin { ) } - pub fn parse(input: &mut css::Parser) -> css::Result { + pub(crate) fn parse(input: &mut css::Parser) -> css::Result { // PORT NOTE: `css::Result` is assumed to alias `Result`; // the Zig `.result`/`.err` switch collapses to `?`. let name = input.expect_ident()?; Ok(from_string(name)) } - pub fn from_string(name_: &[u8]) -> PropertyId { + pub(crate) fn from_string(name_: &[u8]) -> PropertyId { let (prefix, trimmed_name) = VendorPrefix::strip_from(name_); PropertyId::from_name_and_prefix(trimmed_name, prefix) .unwrap_or_else(|| PropertyId::Custom(CustomPropertyName::from_str(name_))) } } -pub mod property_mixin { +pub(super) mod property_mixin { use super::*; /// Serializes the CSS property, with an optional `!important` flag. - pub fn to_css(this: &Property, dest: &mut Printer, important: bool) -> Result<(), PrintErr> { + pub(crate) fn to_css( + this: &Property, + dest: &mut Printer, + important: bool, + ) -> Result<(), PrintErr> { if let Property::Custom(custom) = this { custom.name.to_css(dest)?; dest.delim(b':', false)?; diff --git a/src/css/properties/size.rs b/src/css/properties/size.rs index 57883366b40..70fa24529e1 100644 --- a/src/css/properties/size.rs +++ b/src/css/properties/size.rs @@ -29,7 +29,7 @@ pub enum BoxSizing { // comptime reflection over @tagName. Hand-written here (only two variants) so the inherent // `parse`/`to_css` participate in `impl_parse_tocss_via_inherent!` without a derive-coherence clash. impl BoxSizing { - pub fn parse(input: &mut css::Parser) -> css::Result { + pub(crate) fn parse(input: &mut css::Parser) -> css::Result { let location = input.current_source_location(); let ident = input.expect_ident_cloned()?; if bun_core::eql_case_insensitive_ascii(ident, b"content-box", true) { @@ -41,17 +41,12 @@ impl BoxSizing { } } - pub fn to_css(self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(self, dest: &mut Printer) -> Result<(), PrintErr> { dest.write_str(match self { BoxSizing::ContentBox => "content-box", BoxSizing::BorderBox => "border-box", }) } - - #[inline] - pub fn deep_clone(self, _bump: &Bump) -> Self { - self - } } #[derive(Clone, PartialEq)] @@ -88,7 +83,7 @@ macro_rules! size_ident_match { } impl Size { - pub fn parse(input: &mut css::Parser) -> css::Result { + pub(crate) fn parse(input: &mut css::Parser) -> css::Result { let res = input.try_parse(|i: &mut css::Parser| -> css::Result { let ident = i.expect_ident()?; size_ident_match!(ident, { @@ -121,7 +116,7 @@ impl Size { Ok(Size::LengthPercentage(lp)) } - pub fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { match self { Size::Auto => dest.write_str("auto"), Size::Contain => dest.write_str("contain"), @@ -161,7 +156,7 @@ impl Size { // PORT NOTE: split out of `impl Size` above — these don't depend on // `parse`/`to_css` surface and are needed by `SizeHandler`. impl Size { - pub fn is_compatible(&self, browsers: &css::targets::Browsers) -> bool { + pub(crate) fn is_compatible(&self, browsers: &css::targets::Browsers) -> bool { use css::compat::Feature as F; match self { Size::LengthPercentage(l) => l.is_compatible(browsers), @@ -188,13 +183,13 @@ impl Size { } } - pub fn deep_clone(&self, _bump: &Bump) -> Self { + pub(crate) fn deep_clone(&self, _bump: &Bump) -> Self { // TODO(port): css.implementDeepClone — comptime field-walk; `Size` carries // only `LengthPercentage`/`VendorPrefix` payloads, both `Clone`-via-derive. self.clone() } - pub fn eql(lhs: &Self, rhs: &Self) -> bool { + pub(crate) fn eql(lhs: &Self, rhs: &Self) -> bool { // TODO(port): css.implementEql — comptime field-walk; #[derive(PartialEq)] above covers it. lhs == rhs } @@ -224,7 +219,7 @@ pub enum MaxSize { } impl MaxSize { - pub fn parse(input: &mut css::Parser) -> css::Result { + pub(crate) fn parse(input: &mut css::Parser) -> css::Result { let res = input.try_parse(|i: &mut css::Parser| -> css::Result { let ident = i.expect_ident()?; size_ident_match!(ident, { @@ -259,7 +254,7 @@ impl MaxSize { } } - pub fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { match self { MaxSize::None => dest.write_str("none"), MaxSize::Contain => dest.write_str("contain"), @@ -299,7 +294,7 @@ impl MaxSize { // PORT NOTE: split out of `impl MaxSize` above — these don't depend on // `parse`/`to_css` surface and are needed by `SizeHandler`. impl MaxSize { - pub fn is_compatible(&self, browsers: &css::targets::Browsers) -> bool { + pub(crate) fn is_compatible(&self, browsers: &css::targets::Browsers) -> bool { use css::compat::Feature as F; match self { MaxSize::LengthPercentage(l) => l.is_compatible(browsers), @@ -326,13 +321,13 @@ impl MaxSize { } } - pub fn deep_clone(&self, _bump: &Bump) -> Self { + pub(crate) fn deep_clone(&self, _bump: &Bump) -> Self { // TODO(port): css.implementDeepClone — comptime field-walk; `MaxSize` carries // only `LengthPercentage`/`VendorPrefix` payloads, both `Clone`-via-derive. self.clone() } - pub fn eql(lhs: &Self, rhs: &Self) -> bool { + pub(crate) fn eql(lhs: &Self, rhs: &Self) -> bool { lhs == rhs } } @@ -347,7 +342,7 @@ pub struct AspectRatio { } impl AspectRatio { - pub fn parse(input: &mut css::Parser) -> css::Result { + pub(crate) fn parse(input: &mut css::Parser) -> css::Result { let location = input.current_source_location(); let mut auto = input.try_parse(|i| i.expect_ident_matching(b"auto")); @@ -365,7 +360,7 @@ impl AspectRatio { }) } - pub fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { if self.auto { dest.write_str("auto")?; } @@ -379,12 +374,12 @@ impl AspectRatio { Ok(()) } - pub fn deep_clone(&self, _bump: &Bump) -> Self { + pub(crate) fn deep_clone(&self, _bump: &Bump) -> Self { // PORT NOTE: css.implementDeepClone — `Ratio` is two `f32`s; #[derive(Clone)] is exact. *self } - pub fn eql(lhs: &Self, rhs: &Self) -> bool { + pub(crate) fn eql(lhs: &Self, rhs: &Self) -> bool { lhs == rhs } } @@ -414,7 +409,7 @@ bitflags::bitflags! { } impl SizeProperty { - pub fn try_from_property_id_tag(property_id: PropertyIdTag) -> Option { + pub(crate) fn try_from_property_id_tag(property_id: PropertyIdTag) -> Option { // TODO(port): Zig used `inline for (std.meta.fields(@This()))` to compare each // bitfield name against PropertyIdTag's @tagName. Expanded explicitly here. match property_id { @@ -614,7 +609,7 @@ macro_rules! flush_logical_helper { } impl SizeHandler { - pub fn handle_property( + pub(crate) fn handle_property( &mut self, property: &Property, dest: &mut DeclarationList, @@ -830,7 +825,11 @@ impl SizeHandler { true } - pub fn flush(&mut self, dest: &mut DeclarationList, context: &mut PropertyHandlerContext) { + pub(crate) fn flush( + &mut self, + dest: &mut DeclarationList, + context: &mut PropertyHandlerContext, + ) { if !self.has_any { return; } @@ -958,7 +957,11 @@ impl SizeHandler { ); } - pub fn finalize(&mut self, dest: &mut DeclarationList, context: &mut PropertyHandlerContext) { + pub(crate) fn finalize( + &mut self, + dest: &mut DeclarationList, + context: &mut PropertyHandlerContext, + ) { self.flush(dest, context); self.flushed_properties = SizeProperty::empty(); } diff --git a/src/css/properties/svg.rs b/src/css/properties/svg.rs index 63036e276e5..ad3c0402af0 100644 --- a/src/css/properties/svg.rs +++ b/src/css/properties/svg.rs @@ -1,30 +1 @@ -/// A value for the [stroke-linecap](https://www.w3.org/TR/SVG2/painting.html#LineCaps) property. -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(css.todo_stuff.depth))` — -// a lazy compile error placeholder (never instantiated). Define the real enum if needed. -pub enum StrokeLinecap {} - -/// A value for the [stroke-linejoin](https://www.w3.org/TR/SVG2/painting.html#LineJoin) property. -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(css.todo_stuff.depth))`. -pub enum StrokeLinejoin {} - -/// A value for the [color-interpolation](https://www.w3.org/TR/SVG2/painting.html#ColorInterpolation) property. -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(css.todo_stuff.depth))`. -pub enum ColorInterpolation {} - -/// A value for the [color-rendering](https://www.w3.org/TR/SVG2/painting.html#ColorRendering) property. -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(css.todo_stuff.depth))`. -pub enum ColorRendering {} - -/// A value for the [shape-rendering](https://www.w3.org/TR/SVG2/painting.html#ShapeRendering) property. -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(css.todo_stuff.depth))`. -pub enum ShapeRendering {} - -/// A value for the [text-rendering](https://www.w3.org/TR/SVG2/painting.html#TextRendering) property. -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(css.todo_stuff.depth))`. -pub enum TextRendering {} - -/// A value for the [image-rendering](https://www.w3.org/TR/SVG2/painting.html#ImageRendering) property. -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(css.todo_stuff.depth))`. -pub enum ImageRendering {} - // ported from: src/css/properties/svg.zig diff --git a/src/css/properties/text.rs b/src/css/properties/text.rs index d37ba91bcba..0e737247e74 100644 --- a/src/css/properties/text.rs +++ b/src/css/properties/text.rs @@ -3,21 +3,11 @@ use crate as css; use crate::PrintErr; use crate::Printer; use crate::css_values::color::CssColor; -use crate::css_values::length::LengthPercentage; use crate::css_values::length::LengthValue as Length; -use crate::css_values::percentage::Percentage; - -/// A value for the [text-transform](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#text-transform-property) property. -pub struct TextTransform { - /// How case should be transformed. - pub case: TextTransformCase, - /// How ideographic characters should be transformed. - pub other: TextTransformOther, -} bitflags::bitflags! { #[derive(Clone, Copy, PartialEq, Eq, Default)] - pub struct TextTransformOther: u8 { + pub(crate) struct TextTransformOther: u8 { /// Puts all typographic character units in full-width form. const FULL_WIDTH = 1 << 0; /// Converts all small Kana characters to the equivalent full-size Kana. @@ -25,68 +15,12 @@ bitflags::bitflags! { } } -/// Defines how text case should be transformed in the -/// [text-transform](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#text-transform-property) property. -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(css.todo_stuff.depth))` — unimplemented placeholder. -pub struct TextTransformCase; - -/// A value for the [white-space](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#white-space-property) property. -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(...))` — unimplemented placeholder. -pub struct WhiteSpace; - -/// A value for the [word-break](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#word-break-property) property. -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(...))` — unimplemented placeholder. -pub struct WordBreak; - -/// A value for the [line-break](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#line-break-property) property. -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(...))` — unimplemented placeholder. -pub struct LineBreak; - -/// A value for the [hyphens](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#hyphenation) property. -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(...))` — unimplemented placeholder. -pub struct Hyphens; - -/// A value for the [overflow-wrap](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#overflow-wrap-property) property. -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(...))` — unimplemented placeholder. -pub struct OverflowWrap; - -/// A value for the [text-align](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#text-align-property) property. -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(...))` — unimplemented placeholder. -pub struct TextAlign; - -/// A value for the [text-align-last](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#text-align-last-property) property. -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(...))` — unimplemented placeholder. -pub struct TextAlignLast; - -/// A value for the [text-justify](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#text-justify-property) property. -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(...))` — unimplemented placeholder. -pub struct TextJustify; - -/// A value for the [word-spacing](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#word-spacing-property) -/// and [letter-spacing](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#letter-spacing-property) properties. -pub enum Spacing { - /// No additional spacing is applied. - Normal, - /// Additional spacing between each word or letter. - Length(Length), -} - -/// A value for the [text-indent](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#text-indent-property) property. -pub struct TextIndent { - /// The amount to indent. - pub value: LengthPercentage, - /// Inverts which lines are affected. - pub hanging: bool, - /// Affects the first line after each hard break. - pub each_line: bool, -} - bitflags::bitflags! { /// A value for the [text-decoration-line](https://www.w3.org/TR/2020/WD-css-text-decor-4-20200506/#text-decoration-line-property) property. /// /// Multiple lines may be specified by combining the flags. #[derive(Clone, Copy, PartialEq, Eq, Default)] - pub struct TextDecorationLine: u8 { + pub(crate) struct TextDecorationLine: u8 { /// Each line of text is underlined. const UNDERLINE = 1 << 0; /// Each line of text has a line over it. @@ -102,58 +36,6 @@ bitflags::bitflags! { } } -/// A value for the [text-decoration-style](https://www.w3.org/TR/2020/WD-css-text-decor-4-20200506/#text-decoration-style-property) property. -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(...))` — unimplemented placeholder. -pub struct TextDecorationStyle; - -/// A value for the [text-decoration-thickness](https://www.w3.org/TR/2020/WD-css-text-decor-4-20200506/#text-decoration-width-property) property. -pub enum TextDecorationThickness { - /// The UA chooses an appropriate thickness for text decoration lines. - Auto, - /// Use the thickness defined in the current font. - FromFont, - /// An explicit length. - LengthPercentage(LengthPercentage), -} - -/// A value for the [text-decoration](https://www.w3.org/TR/2020/WD-css-text-decor-4-20200506/#text-decoration-property) shorthand property. -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(...))` — unimplemented placeholder. -pub struct TextDecoration; - -/// A value for the [text-decoration-skip-ink](https://www.w3.org/TR/2020/WD-css-text-decor-4-20200506/#text-decoration-skip-ink-property) property. -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(...))` — unimplemented placeholder. -pub struct TextDecorationSkipInk; - -/// A text emphasis shape for the [text-emphasis-style](https://www.w3.org/TR/2020/WD-css-text-decor-4-20200506/#text-emphasis-style-property) property. -/// -/// See [TextEmphasisStyle](TextEmphasisStyle). -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(...))` — unimplemented placeholder. -pub struct TextEmphasisStyle; - -/// A value for the [text-emphasis](https://www.w3.org/TR/2020/WD-css-text-decor-4-20200506/#text-emphasis-property) shorthand property. -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(...))` — unimplemented placeholder. -pub struct TextEmphasis; - -/// A value for the [text-emphasis-position](https://www.w3.org/TR/2020/WD-css-text-decor-4-20200506/#text-emphasis-position-property) property. -pub struct TextEmphasisPosition { - /// The vertical position. - pub vertical: TextEmphasisPositionVertical, - /// The horizontal position. - pub horizontal: TextEmphasisPositionHorizontal, -} - -/// A vertical position keyword for the [text-emphasis-position](https://www.w3.org/TR/2020/WD-css-text-decor-4-20200506/#text-emphasis-position-property) property. -/// -/// See [TextEmphasisPosition](TextEmphasisPosition). -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(...))` — unimplemented placeholder. -pub struct TextEmphasisPositionVertical; - -/// A horizontal position keyword for the [text-emphasis-position](https://www.w3.org/TR/2020/WD-css-text-decor-4-20200506/#text-emphasis-position-property) property. -/// -/// See [TextEmphasisPosition](TextEmphasisPosition). -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(...))` — unimplemented placeholder. -pub struct TextEmphasisPositionHorizontal; - /// A value for the [text-shadow](https://www.w3.org/TR/2020/WD-css-text-decor-4-20200506/#text-shadow-property) property. #[derive(Clone, PartialEq)] pub struct TextShadow { @@ -170,7 +52,7 @@ pub struct TextShadow { } impl TextShadow { - pub fn parse(input: &mut css::Parser) -> css::Result { + pub(crate) fn parse(input: &mut css::Parser) -> css::Result { let mut color: Option = None; type Lengths = (Length, Length, Length, Length); let mut lengths: Option = None; @@ -213,7 +95,7 @@ impl TextShadow { }) } - pub fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> Result<(), PrintErr> { self.x_offset.to_css(dest)?; dest.write_char(b' ')?; self.y_offset.to_css(dest)?; @@ -236,7 +118,7 @@ impl TextShadow { Ok(()) } - pub fn is_compatible(&self, browsers: &css::targets::Browsers) -> bool { + pub(crate) fn is_compatible(&self, browsers: &css::targets::Browsers) -> bool { self.color.is_compatible(browsers) && self.x_offset.is_compatible(browsers) && self.y_offset.is_compatible(browsers) @@ -247,7 +129,7 @@ impl TextShadow { // Zig: `pub fn eql` via `css.implementEql(@This(), ...)` — field-wise equality. // Ported as `#[derive(PartialEq)]` above; callers use `==`. - pub fn deep_clone(&self, alloc: &bun_alloc::Arena) -> Self { + pub(crate) fn deep_clone(&self, alloc: &bun_alloc::Arena) -> Self { // TODO(port): Zig used reflection-based `css.implementDeepClone`. Fields here // are value types, so a plain Clone is equivalent; arena param retained for // signature compatibility with the CSS deep_clone protocol. @@ -266,16 +148,6 @@ impl css::generics::IsCompatible for TextShadow { } } -/// A value for the [text-size-adjust](https://w3c.github.io/csswg-drafts/css-size-adjust/#adjustment-control) property. -pub enum TextSizeAdjust { - /// Use the default size adjustment when displaying on a small device. - Auto, - /// No size adjustment when displaying on a small device. - None, - /// When displaying on a small device, the font size is multiplied by this percentage. - Percentage(Percentage), -} - /// A value for the [direction](https://drafts.csswg.org/css-writing-modes-3/#direction) property. // Zig wires eql/hash/parse/toCss/deepClone via `css.DefineEnumProperty(@This())`. #[derive( @@ -288,12 +160,4 @@ pub enum Direction { Rtl, } -/// A value for the [unicode-bidi](https://drafts.csswg.org/css-writing-modes-3/#unicode-bidi) property. -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(...))` — unimplemented placeholder. -pub struct UnicodeBidi; - -/// A value for the [box-decoration-break](https://www.w3.org/TR/css-break-3/#break-decoration) property. -// TODO(port): Zig source is `css.DefineEnumProperty(@compileError(...))` — unimplemented placeholder. -pub struct BoxDecorationBreak; - // ported from: src/css/properties/text.zig diff --git a/src/css/properties/transform.rs b/src/css/properties/transform.rs index f5c236500ae..0ddb169af13 100644 --- a/src/css/properties/transform.rs +++ b/src/css/properties/transform.rs @@ -24,7 +24,7 @@ pub struct TransformList { // PORT NOTE: split out of the parse/to_css `impl TransformList` below — // `TransformHandler` only needs deep_clone/eql. impl TransformList { - pub fn deep_clone(&self, _bump: &Bump) -> Self { + pub(crate) fn deep_clone(&self, _bump: &Bump) -> Self { // TODO(port): css.implementDeepClone reflection — `Transform`/`TransformList` // are `Clone`-via-derive (Vec + POD payloads); an arena-aware DeepClone // trait should land crate-wide. @@ -33,7 +33,7 @@ impl TransformList { } impl TransformList { - pub fn parse(input: &mut Parser<'_>) -> Result { + pub(crate) fn parse(input: &mut Parser<'_>) -> Result { if input .try_parse(|i| i.expect_ident_matching(b"none")) .is_ok() @@ -56,7 +56,7 @@ impl TransformList { } } - pub fn to_css(&self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { if self.v.is_empty() { return dest.write_str("none"); } @@ -145,7 +145,7 @@ pub enum Transform { } impl Transform { - pub fn parse(input: &mut Parser) -> Result { + pub(crate) fn parse(input: &mut Parser) -> Result { let function = input.expect_function_cloned()?; // PORT NOTE: Zig used a Closure struct + nested anon-struct fn passed to @@ -319,7 +319,7 @@ impl Transform { }) } - pub fn to_css(&self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { match self { Transform::Translate { x, y } => { if dest.minify && x.is_zero() && !y.is_zero() { @@ -573,7 +573,7 @@ impl Transform { Ok(()) } - pub fn deep_clone(&self, _bump: &Bump) -> Self { + pub(crate) fn deep_clone(&self, _bump: &Bump) -> Self { // TODO(port): css.implementDeepClone reflection — payload types may need bump-aware clone self.clone() } @@ -590,19 +590,6 @@ pub struct Matrix { pub f: T, } -impl Matrix { - pub fn deep_clone(&self, _bump: &Bump) -> Self { - self.clone() - } - - pub fn eql(&self, rhs: &Self) -> bool - where - T: PartialEq, - { - self == rhs - } -} - /// A 3D matrix. #[derive(Clone, Copy, PartialEq, Eq)] pub struct Matrix3d { @@ -624,12 +611,6 @@ pub struct Matrix3d { pub m44: T, } -impl Matrix3d { - pub fn eql(&self, rhs: &Self) -> bool { - self == rhs - } -} - /// A value for the [transform-style](https://drafts.csswg.org/css-transforms-2/#transform-style-property) property. // TODO(port): css.DefineEnumProperty reflection → crate-wide #[derive(EnumProperty)] providing // parse/to_css/eql/hash/deep_clone from kebab-case variant names. @@ -680,7 +661,7 @@ pub enum Perspective { } impl Perspective { - pub fn deep_clone(&self, _bump: &Bump) -> Self { + pub(crate) fn deep_clone(&self, _bump: &Bump) -> Self { self.clone() } } @@ -703,7 +684,7 @@ pub enum Translate { } impl Translate { - pub fn parse(input: &mut Parser) -> Result { + pub(crate) fn parse(input: &mut Parser) -> Result { if input .try_parse(|i| i.expect_ident_matching(b"none")) .is_ok() @@ -726,7 +707,7 @@ impl Translate { }) } - pub fn to_css(&self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { match self { Translate::None => dest.write_str("none")?, Translate::Xyz { x, y, z } => { @@ -748,7 +729,7 @@ impl Translate { // PORT NOTE: split out of the parse/to_css `impl Translate` above — these // don't depend on Parser/Printer surface and are needed by `TransformHandler`. impl Translate { - pub fn to_transform(&self, _bump: &Bump) -> Transform { + pub(crate) fn to_transform(&self, _bump: &Bump) -> Transform { match self { Translate::None => Transform::Translate3d { x: LengthPercentage::zero(), @@ -763,7 +744,7 @@ impl Translate { } } - pub fn deep_clone(&self, _bump: &Bump) -> Self { + pub(crate) fn deep_clone(&self, _bump: &Bump) -> Self { // TODO(port): css.implementDeepClone — arena-aware clone for LengthPercentage self.clone() } @@ -783,7 +764,7 @@ pub struct Rotate { } impl Rotate { - pub fn parse(input: &mut Parser) -> Result { + pub(crate) fn parse(input: &mut Parser) -> Result { if input .try_parse(|i| i.expect_ident_matching(b"none")) .is_ok() @@ -842,7 +823,7 @@ impl Rotate { }) } - pub fn to_css(&self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { if self.x == 0.0 && self.y == 0.0 && self.z == 1.0 && self.angle.is_zero() { dest.write_str("none")?; return Ok(()); @@ -869,7 +850,7 @@ impl Rotate { // `TransformHandler`. impl Rotate { /// Converts the rotation to a transform function. - pub fn to_transform(&self, _bump: &Bump) -> Transform { + pub(crate) fn to_transform(&self, _bump: &Bump) -> Transform { Transform::Rotate3d { x: self.x, y: self.y, @@ -878,7 +859,7 @@ impl Rotate { } } - pub fn deep_clone(&self, _bump: &Bump) -> Self { + pub(crate) fn deep_clone(&self, _bump: &Bump) -> Self { *self } } @@ -901,7 +882,7 @@ pub enum Scale { } impl Scale { - pub fn parse(input: &mut Parser) -> Result { + pub(crate) fn parse(input: &mut Parser) -> Result { if input .try_parse(|i| i.expect_ident_matching(b"none")) .is_ok() @@ -929,7 +910,7 @@ impl Scale { }) } - pub fn to_css(&self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { + pub(crate) fn to_css(&self, dest: &mut Printer) -> core::result::Result<(), PrintErr> { match self { Scale::None => dest.write_str("none")?, Scale::Xyz { x, y, z } => { @@ -952,7 +933,7 @@ impl Scale { // PORT NOTE: split out of the parse/to_css `impl Scale` above — needed by // `TransformHandler`. impl Scale { - pub fn to_transform(&self, _bump: &Bump) -> Transform { + pub(crate) fn to_transform(&self, _bump: &Bump) -> Transform { match self { Scale::None => Transform::Scale3d { x: NumberOrPercentage::Number(1.0), @@ -967,7 +948,7 @@ impl Scale { } } - pub fn deep_clone(&self, _bump: &Bump) -> Self { + pub(crate) fn deep_clone(&self, _bump: &Bump) -> Self { self.clone() } } @@ -996,7 +977,7 @@ pub struct TransformHandler { // PORT NOTE: `context.arena` was dropped from PropertyHandlerContext, so the // arena is recovered via `dest.bump()` (DeclarationList = bumpalo::Vec). impl TransformHandler { - pub fn handle_property( + pub(crate) fn handle_property( &mut self, property: &Property, dest: &mut DeclarationList, @@ -1080,7 +1061,11 @@ impl TransformHandler { true } - pub fn finalize(&mut self, dest: &mut DeclarationList, context: &mut PropertyHandlerContext) { + pub(crate) fn finalize( + &mut self, + dest: &mut DeclarationList, + context: &mut PropertyHandlerContext, + ) { self.flush(dest, context); } diff --git a/src/css/properties/transition.rs b/src/css/properties/transition.rs index 199cdb744fb..10e61d8d012 100644 --- a/src/css/properties/transition.rs +++ b/src/css/properties/transition.rs @@ -6,7 +6,6 @@ use crate::Printer; use crate::PropertyHandlerContext; use crate::Result as CssResult; use crate::SmallList; -use crate::properties::PropertyIdTag; use bun_alloc::ArenaVecExt as _; use crate::css_properties::Property; @@ -33,29 +32,19 @@ pub struct Transition { } impl Transition { - // TODO(port): PropertyFieldMap was a Zig comptime anonymous struct mapping - // field names → PropertyIdTag, consumed by reflection-based shorthand helpers. - // Replace with a trait impl or const table once the shorthand machinery is ported. - pub const PROPERTY_FIELD_MAP: &'static [(&'static str, PropertyIdTag)] = &[ - ("property", PropertyIdTag::TransitionProperty), - ("duration", PropertyIdTag::TransitionDuration), - ("delay", PropertyIdTag::TransitionDelay), - ("timing_function", PropertyIdTag::TransitionTimingFunction), - ]; - - pub fn eql(&self, rhs: &Self) -> bool { + pub(crate) fn eql(&self, rhs: &Self) -> bool { // Zig: css.implementEql(@This(), lhs, rhs) — field-by-field reflection. self == rhs } - pub fn deep_clone(&self, _bump: &bun_alloc::Arena) -> Self { + pub(crate) fn deep_clone(&self, _bump: &bun_alloc::Arena) -> Self { // Zig: css.implementDeepClone(@This(), this, arena) — field-by-field // reflection. All four fields are POD/Copy or `Clone`-via-derive with no // arena indirections; #[derive(Clone)] is exact. self.clone() } - pub fn parse(parser: &mut Parser) -> CssResult { + pub(crate) fn parse(parser: &mut Parser) -> CssResult { let mut property: Option = None; let mut duration: Option