diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index b201cf9..6cdb0d6 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -1,8 +1,8 @@
name: release
# release-please keeps a "chore: release" PR up to date from conventional commits on main.
-# Merging that PR tags js-vX.Y.Z / spec-vX.Y.Z / python-vX.Y.Z, creates the GitHub Releases, and
-# publishes to npm and PyPI.
+# Merging that PR tags js-vX.Y.Z / spec-vX.Y.Z / python-vX.Y.Z / rust-vX.Y.Z, creates the GitHub
+# Releases, and publishes to npm, PyPI and (once enabled) crates.io.
on:
push:
@@ -13,6 +13,10 @@ on:
description: "Re-publish an existing python release tag to PyPI (e.g. python-v0.2.0). Leave empty for a normal release-please run."
required: false
default: ""
+ rust_tag:
+ description: "Re-publish an existing rust release tag to crates.io (e.g. rust-v0.5.0). Leave empty for a normal release-please run."
+ required: false
+ default: ""
permissions: {}
@@ -33,6 +37,9 @@ jobs:
python_release_created: ${{ steps.release.outputs['python--release_created'] }}
python_tag_name: ${{ steps.release.outputs['python--tag_name'] }}
python_version: ${{ steps.release.outputs['python--version'] }}
+ rust_release_created: ${{ steps.release.outputs['rust--release_created'] }}
+ rust_tag_name: ${{ steps.release.outputs['rust--tag_name'] }}
+ rust_version: ${{ steps.release.outputs['rust--version'] }}
steps:
- uses: googleapis/release-please-action@v4
id: release
@@ -233,3 +240,88 @@ jobs:
EOF
# The npm release (js-vX.Y.Z) stays "Latest"; don't touch that flag here.
gh release edit "$TAG" --notes-file notes.md
+
+ # crates.io trusted publishing (OIDC, no stored token). It can only be configured for a crate
+ # that already exists, so the very first `cargo publish` is done by the maintainer by hand.
+ # After that: on crates.io add a trusted publisher for 4matic/trackparse, workflow release.yml,
+ # environment "crates", then set the repository variable CRATES_PUBLISH to "true".
+ publish-crates:
+ needs: release-please
+ if: vars.CRATES_PUBLISH == 'true' && (needs.release-please.outputs.rust_release_created == 'true' || (github.event_name == 'workflow_dispatch' && inputs.rust_tag != ''))
+ runs-on: ubuntu-latest
+ environment:
+ name: crates
+ url: https://crates.io/crates/trackparse
+ permissions:
+ contents: write # attach the .crate file to the GitHub Release
+ id-token: write # crates.io trusted publishing (OIDC)
+ steps:
+ - name: Resolve the release tag
+ id: tag
+ env:
+ RELEASED_TAG: ${{ steps.tag.outputs.tag }}
+ RELEASED_VERSION: ${{ steps.tag.outputs.version }}
+ INPUT_TAG: ${{ inputs.rust_tag }}
+ run: |
+ if [ -n "$INPUT_TAG" ]; then
+ if ! printf '%s' "$INPUT_TAG" | grep -Eq '^rust-v[0-9]+\.[0-9]+\.[0-9]+$'; then
+ echo "rust_tag must look like rust-vX.Y.Z" >&2
+ exit 1
+ fi
+ tag="$INPUT_TAG"
+ version="${INPUT_TAG#rust-v}"
+ else
+ tag="$RELEASED_TAG"
+ version="$RELEASED_VERSION"
+ fi
+ echo "tag=$tag" >> "$GITHUB_OUTPUT"
+ echo "version=$version" >> "$GITHUB_OUTPUT"
+ - uses: actions/checkout@v4
+ with:
+ ref: ${{ steps.tag.outputs.tag }}
+ # The runner image ships stable Rust; no third-party toolchain action in the publishing job.
+ - run: rustup update stable --no-self-update && rustup default stable
+ - name: Verify versions are in sync
+ env:
+ TAG_VERSION: ${{ steps.tag.outputs.version }}
+ run: |
+ rs_version=$(python3 -c 'import tomllib; print(tomllib.load(open("rust/Cargo.toml", "rb"))["package"]["version"])')
+ spec_version=$(cat spec/VERSION)
+ echo "rust=$rs_version spec=$spec_version tag=$TAG_VERSION"
+ test "$rs_version" = "$TAG_VERSION"
+ test "$spec_version" = "$TAG_VERSION"
+ - name: Test
+ working-directory: rust
+ run: cargo test --all-features
+ - name: Package
+ working-directory: rust
+ run: cargo package
+ - uses: rust-lang/crates-io-auth-action@3268eb413133e2960fa4ae0e963ca76380c54cd9 # v1.0.6
+ id: auth
+ - name: Publish to crates.io
+ working-directory: rust
+ env:
+ CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }}
+ run: cargo publish
+ - name: Attach the crate file and install notes to the GitHub Release
+ working-directory: rust
+ env:
+ GH_TOKEN: ${{ github.token }}
+ TAG: ${{ steps.tag.outputs.tag }}
+ VERSION: ${{ steps.tag.outputs.version }}
+ run: |
+ gh release upload "$TAG" target/package/*.crate --clobber
+ highlights="../.github/release-notes/${VERSION}.md"
+ {
+ if [ -f "$highlights" ]; then cat "$highlights"; echo; fi
+ gh release view "$TAG" --json body --jq .body
+ echo
+ echo "### Install"
+ echo
+ echo '```sh'
+ echo "cargo add trackparse@${VERSION}"
+ echo '```'
+ echo
+ echo "crates.io: https://crates.io/crates/trackparse/${VERSION} · docs: https://docs.rs/trackparse/${VERSION}"
+ } > notes.md
+ gh release edit "$TAG" --notes-file notes.md
diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml
new file mode 100644
index 0000000..b503f08
--- /dev/null
+++ b/.github/workflows/rust.yml
@@ -0,0 +1,74 @@
+name: rust
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ paths:
+ - "rust/**"
+ - "spec/**"
+ # The compare job diffs the crate against the built JS package.
+ - "js/src/**"
+ - "scripts/compare-ports.mjs"
+ - ".github/workflows/rust.yml"
+
+permissions:
+ contents: read
+
+env:
+ CARGO_TERM_COLOR: always
+
+jobs:
+ test:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ # stable, and the minimum supported Rust version from rust/Cargo.toml (rust-version).
+ toolchain: [stable, "1.74.0"]
+ defaults:
+ run:
+ working-directory: rust
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@master
+ with:
+ toolchain: ${{ matrix.toolchain }}
+ components: rustfmt, clippy
+ - uses: Swatinem/rust-cache@v2
+ with:
+ workspaces: rust
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 24
+ - name: Data codegen is up to date
+ run: node scripts/gen_data.mjs --check
+ - if: matrix.toolchain == 'stable'
+ run: cargo fmt --check
+ - if: matrix.toolchain == 'stable'
+ run: cargo clippy --all-targets --all-features -- -D warnings
+ # Every shared fixture, the invariants and the API tests.
+ - run: cargo test --locked
+ - if: matrix.toolchain == 'stable'
+ run: cargo test --all-features
+ - if: matrix.toolchain == 'stable'
+ name: The crate packages cleanly
+ run: cargo publish --dry-run
+
+ # Every fixture input through the built JS package and the Rust crate: full outputs must match.
+ compare:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@stable
+ - uses: Swatinem/rust-cache@v2
+ with:
+ workspaces: rust
+ - uses: pnpm/action-setup@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 24
+ cache: pnpm
+ - run: pnpm install --frozen-lockfile
+ - run: pnpm --filter trackparse build
+ - run: node scripts/compare-ports.mjs --only=rust
diff --git a/.github/workflows/spec.yml b/.github/workflows/spec.yml
index 4216ec2..4d4e045 100644
--- a/.github/workflows/spec.yml
+++ b/.github/workflows/spec.yml
@@ -34,11 +34,13 @@ jobs:
run: pnpm --filter @trackparse/fixture-gen test
- name: Port data codegen is up to date
run: pnpm --filter trackparse gen:data:check
- - name: js, python and spec versions are linked
+ - name: js, python, rust and spec versions are linked
run: |
js_version=$(node -p "require('./js/package.json').version")
py_version=$(python3 -c 'import tomllib; print(tomllib.load(open("python/pyproject.toml", "rb"))["project"]["version"])')
+ rs_version=$(python3 -c 'import tomllib; print(tomllib.load(open("rust/Cargo.toml", "rb"))["package"]["version"])')
spec_version=$(cat spec/VERSION)
- echo "js=$js_version python=$py_version spec=$spec_version"
+ echo "js=$js_version python=$py_version rust=$rs_version spec=$spec_version"
test "$js_version" = "$spec_version"
test "$py_version" = "$spec_version"
+ test "$rs_version" = "$spec_version"
diff --git a/.gitignore b/.gitignore
index d8877ba..d816ccf 100644
--- a/.gitignore
+++ b/.gitignore
@@ -18,7 +18,6 @@ python/dist/
# Rust
target/
-rust/Cargo.lock
# Editors / OS
.DS_Store
diff --git a/.release-please-manifest.json b/.release-please-manifest.json
index 5c30d36..8e281b2 100644
--- a/.release-please-manifest.json
+++ b/.release-please-manifest.json
@@ -1,5 +1,6 @@
{
"js": "0.4.0",
"spec": "0.4.0",
- "python": "0.4.0"
+ "python": "0.4.0",
+ "rust": "0.4.0"
}
diff --git a/AGENTS.md b/AGENTS.md
index 59bae05..808cd2d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -78,23 +78,52 @@ python/ PyPI package `trackparse` (Python 3.9+, zero deps, uv
tests/ runner.py, match.py, test_fixtures.py, test_properties.py (Hypothesis),
test_api.py, test_match.py, test_tracklist_api.py,
test_tracklist_properties.py, skip.json (only ever shrinks)
-rust/ planned crates.io port (README stub only)
+rust/ crates.io package `trackparse` (Rust 1.74+, one dependency, no unsafe;
+ a release-please component, first crates.io publish still to do)
+ src/lib.rs public API: parse, parse_with, parse_artists(_with), format_track(_with),
+ normalize, all_artists, Parser, SPEC_VERSION; re-exports every type and
+ option at the crate root (`types` and `options` are private modules)
+ src/types.rs public structs and enums (mirror the schemas): to_json(), and
+ as_str() / from_name() / ALL / Display / FromStr on the enums
+ src/options.rs ParseOptions, FormatOptions, KeywordOptions (#[non_exhaustive], chained
+ setters from ::new()) + resolved forms
+ src/*.rs one module per js/src file, same rule IDs in comments: parser, normalize,
+ mode, scanner, prefix, classify, separator, artists, credits, title,
+ assemble, format, words, digits, tables, context
+ src/tracklist/ public `trackparse::tracklist` (parse_tracklist(_with), apply_edits(_with)),
+ one module per js/src/tracklist file (mod.rs is index.ts)
+ src/json.rs hand-written JSON value, parser and writer with JS number formatting
+ src/wire.rs the JSON door (doc-hidden): every function with loose JSON arguments,
+ for the fixtures and the cross-port diff
+ src/serde_support.rs serde impls behind the `serde` feature
+ src/data.rs GENERATED from spec/data + spec/VERSION (never edit)
+ src/unicode_tables.rs GENERATED: categories L and Lu, the lowercase mapping (never edit)
+ src/value.rs the static value type data.rs is written in
+ scripts/gen_data.mjs codegen for data.rs and unicode_tables.rs (--check for CI)
+ scripts/dump_primitives.mjs expected R0 primitive values from JS, into tests/data/
+ examples/dump.rs Rust side of compare-ports (JSONL in, JSON out, through wire)
+ tests/ fixtures.rs (every shared fixture + the conformance report), api.rs,
+ tracklist_api.rs, tracklist_properties.rs (R13.11 invariants), serde.rs,
+ data/primitives.json (from dump_primitives.mjs), skip.json (only ever shrinks)
site/ documentation site + playground (Astro + Starlight, GitHub Pages)
astro.config.mjs base /trackparse, sidebar
- src/content/docs/ the pages (Markdown/MDX, JS + Python tabs on every example);
+ src/content/docs/ the pages (Markdown/MDX, JS + Python + Rust tabs on every example);
reference/spec.md is generated from spec/SPEC.md
src/components/ HeroDemo, Playground (runs js/ in the browser), Feature, Stats
src/lib/ trackview.ts (highlight + field rendering), icons.ts (Lucide SVG strings)
scripts/sync-spec.mjs copies spec/SPEC.md into the docs at build time
-scripts/compare-ports.mjs every fixture through js/dist and the Python port, diffs the full outputs
- (parseTracklist and applyEdits included)
+scripts/compare-ports.mjs every fixture through js/dist, the Python port and the Rust crate, diffs
+ the full outputs (parseTracklist and applyEdits included);
+ --only=python or --only=rust for one port
scripts/corpus-check.mjs R13 against a private tracklist corpus (JSONL in spec/corpus/), via js/dist
scripts/dump_py.py Python side of compare-ports (JSONL in, to_dict() JSON out)
.github/workflows/ js.yml (full suite on Node 22/24; compat: fixtures vs built dist on Node 18/20),
python.yml (lint, mypy, pytest on 3.9–3.14; build: fixtures vs installed wheel),
+ rust.yml (codegen drift, fmt, clippy, cargo test on stable and 1.74,
+ publish dry run; compare: Rust vs built JS on every fixture),
spec.yml (fixture validation, generated/codegen drift, generator tests,
- js/python/spec version link), release.yml (release-please + npm and PyPI
- publish), pages.yml (build site/, deploy to GitHub Pages),
+ js/python/rust/spec version link), release.yml (release-please + npm, PyPI
+ and crates.io publish), pages.yml (build site/, deploy to GitHub Pages),
pr-title.yml (conventional PR titles)
.github/release-notes/ optional hand-written highlights prepended to a GitHub Release
release-please-config.json, .release-please-manifest.json release automation (never hand-edit the manifest)
@@ -107,8 +136,9 @@ js/CHANGELOG.md, spec/CHANGELOG.md, python/CHANGELOG.md generated by release-p
- Never change a port's behaviour without a fixture that pins the new behaviour. If a fix needs no
fixture change, it is a bug fix; if an existing `expected` changes, it is a behaviour change.
-- Never hand-edit `spec/fixtures/generated/**`, `js/src/data.generated.ts` or
- `python/src/trackparse/_data.py`. Regenerate them.
+- Never hand-edit `spec/fixtures/generated/**`, `js/src/data.generated.ts`,
+ `python/src/trackparse/_data.py`, `rust/src/data.rs` or `rust/src/unicode_tables.rs`. Regenerate
+ them.
- Word lists live **only** in `spec/data/`. Ports compile them into source with codegen; never copy
a list into port code by hand, never hard-code a keyword in a scanner.
- The fixtures, not any one implementation, are the source of truth. When SPEC.md and a fixture
@@ -133,16 +163,16 @@ js/CHANGELOG.md, spec/CHANGELOG.md, python/CHANGELOG.md generated by release-p
expected output must come from the atoms, never from running a parser. If a combination becomes
ambiguous, reject it in `model.ts` (`problem()`) instead of guessing. Then
`pnpm gen:fixtures` and commit the output.
-4. **Codegen.** If `spec/data` or `spec/VERSION` changed: `pnpm gen:data` and, in `python/`,
- `uv run python scripts/gen_data.py`.
-5. **Implementation.** Change every port (JS and Python today). Cite rule IDs in comments.
+4. **Codegen.** If `spec/data` or `spec/VERSION` changed: `pnpm gen:data`, in `python/`
+ `uv run python scripts/gen_data.py`, and in `rust/` `node scripts/gen_data.mjs`.
+5. **Implementation.** Change every port (JS, Python and Rust today). Cite rule IDs in comments.
6. **Conformance.** `pnpm test` and `pnpm conformance` must be green: 100% of fixtures, schema-valid
output, property tests passing, `pnpm gen:check` clean. Same for Python (`uv run pytest`,
- `uv run python scripts/conformance.py`), then `node scripts/compare-ports.mjs` must report 0
- differences.
+ `uv run python scripts/conformance.py`) and Rust (`cargo test`, and the report with
+ `TRACKPARSE_REPORT=1`), then `node scripts/compare-ports.mjs` must report 0 differences.
7. **Docs.** Update the site pages and README sections that describe the rule (see
- [Documentation site and READMEs](#documentation-site-and-readmes)), with JavaScript and Python
- examples whose outputs you ran, and `pnpm docs:build` green.
+ [Documentation site and READMEs](#documentation-site-and-readmes)), with JavaScript, Python and
+ Rust examples whose outputs you ran, and `pnpm docs:build` green.
8. **Commit message.** Conventional commits; the message *is* the changelog entry (see
[Versioning and release](#versioning-and-release)). Any change to an existing `expected` value is
a behaviour change and must be a `feat` (or carry `!`), never a `fix`/`chore`. Don't touch
@@ -206,10 +236,21 @@ Python (run inside `python/`; uv picks up `.python-version` and `uv.lock`):
| `uv run python scripts/conformance.py` | Pass rate per fixture file and per rule ID |
| `uv build` | Build the sdist and wheel into `dist/` |
-Cross-port check, from the repo root (needs `uv`):
+Rust (run inside `rust/`; Rust 1.74 or newer, Node for the codegen):
+
+| Command | What it does |
+|---|---|
+| `cargo test` | Every fixture, the R13.11 invariants, API tests, doc tests (CI also runs `--all-features`) |
+| `TRACKPARSE_REPORT=1 cargo test --test fixtures -- --nocapture` | Pass rate per fixture file and per rule ID |
+| `node scripts/gen_data.mjs` | Regenerate `src/data.rs` and `src/unicode_tables.rs`; `--check` fails if stale |
+| `cargo fmt --check` · `cargo clippy --all-targets --all-features -- -D warnings` | Format check and lint (the panic lints are in `Cargo.toml`) |
+| `cargo publish --dry-run` | The crate packages cleanly |
+
+Cross-port check, from the repo root (needs `uv` and `cargo`):
```sh
pnpm --filter trackparse build && node scripts/compare-ports.mjs # must print "differences: 0"
+node scripts/compare-ports.mjs --only=rust # one port against JS
```
Corpus check for R13 changes, when you have the private corpus (JSONL, one object per tracklist
@@ -235,7 +276,9 @@ Before pushing, mirror CI: `pnpm lint && pnpm --filter trackparse typecheck && p
pnpm build && pnpm --filter trackparse size && pnpm --filter trackparse check:package &&
pnpm --filter trackparse compat && pnpm gen:check && pnpm --filter @trackparse/fixture-gen validate`, and in `python/`
`uv run python scripts/gen_data.py --check && uv run ruff check . && uv run ruff format --check . &&
-uv run mypy --strict src && uv run pytest && uv build`.
+uv run mypy --strict src && uv run pytest && uv build`, and in `rust/`
+`node scripts/gen_data.mjs --check && cargo fmt --check &&
+cargo clippy --all-targets --all-features -- -D warnings && cargo test && cargo test --all-features`.
## Fixture authoring
@@ -271,14 +314,14 @@ PR:
|---|---|
| a rule's behaviour (R1–R12) | the guide for that area (`guides/what-it-understands`, `artists`, `versions`, `junk-and-flags`, `modes`, `formatting`), the root README tables |
| tracklists (R13) | `guides/tracklists`, `guides/editing-tracklists`, `reference/tracklist`, `reference/warnings` |
-| a function, option, field or type | `reference/parse`, `reference/options`, `reference/functions` or `reference/tracklist`; the API sections of `js/README.md` and `python/README.md` |
+| a function, option, field or type | `reference/parse`, `reference/options`, `reference/functions` or `reference/tracklist`; the API sections of `js/README.md`, `python/README.md` and `rust/README.md` |
| a warning code | `reference/warnings` |
| fixture counts, file counts, the size budget | `components/Stats.astro`, `index.mdx`, `start/introduction`, `project/testing`, `project/ports`, the root README "At a glance" and "How it's tested" |
| a port, a command, CI or the release flow | `project/ports`, `project/contributing`, `project/testing` ("Run it yourself") |
| `spec/SPEC.md` | nothing by hand: `reference/spec` is generated from it at build time |
-**Every code example is bilingual.** There are no per-language pages. Each example on the site is a
-pair of synced tabs, with the JavaScript example first:
+**Every code example is trilingual.** There are no per-language pages. Each example on the site is
+three synced tabs, in the order JavaScript, Python, Rust:
````mdx
@@ -295,6 +338,13 @@ parse("Noisia - Stigma (2015)").year; // 2015
parse("Noisia - Stigma (2015)").year # 2015
```
+
+
+
+```rust
+parse("Noisia - Stigma (2015)").year; // Some(2015)
+```
+
````
@@ -304,10 +354,17 @@ parse("Noisia - Stigma (2015)").year # 2015
- Write the Python version in Python terms: snake_case functions, options and attributes
(`format_track`, `known_artists=`, `full_title`), tuples, `None`/`True`, and results as the
dataclass `repr` (`Junk(raw='HD', kind='quality')`).
-- Run every example and paste the real output; never write an output by hand. Language-specific
+- Write the Rust version in Rust terms: `use trackparse::…;`, the `_with` functions with option
+ builders (`parse_with(s, &ParseOptions::new().known_artists([…]))`), snake_case fields
+ (`version_type`, `full_title`), `Option` and `Vec`, and results as their `Debug` output
+ (`Junk { raw: "HD", kind: Quality }`, `Some(2015)`).
+- Run every example and paste the real output; never write an output by hand. For Rust, a scratch
+ cargo project that depends on the crate by path (`trackparse = { path = "…/rust" }`) is enough. Language-specific
notes (typing, `to_dict()`, `TypeError`) go on the page they concern, not on a separate page.
- The playground and the landing demo import `js/` directly, so they follow the code automatically;
- check them in a browser when the output shape changes.
+ check them in a browser when the output shape changes. The playground's code panels generate
+ JS, Python and Rust (`code()` and `listCode()` in `Playground.astro`): when an option or an edit
+ changes, update all three generators and compile a generated Rust snippet.
**READMEs link to the site.** Each README section opens with a `**Docs:**` line that links the
matching site pages (`README.md`, `js/README.md`, `python/README.md`, `rust/README.md`,
@@ -330,8 +387,8 @@ trigger a release; changes under `js/`, `python/` or `spec/` do, even `docs:` on
## Porting guide (Rust, others)
-A port is done when it passes every fixture and every invariant. The Python port is done and is a
-good second reference next to JS: its modules map one to one onto `js/src`. Checklist:
+A port is done when it passes every fixture and every invariant. The Python and Rust ports are done
+and are good second references next to JS: their modules map one to one onto `js/src`. Checklist:
1. **Codegen from `spec/data` and `spec/VERSION`** into a source file (like
`js/scripts/gen-data.ts`), with a `--check` mode wired into CI. Expose `SPEC_VERSION`.
@@ -348,7 +405,7 @@ good second reference next to JS: its modules map one to one onto `js/src`. Chec
file against the fixture schema, each output against `parsed-track.schema.json` (or
`tracklist.schema.json` for `fn: "parseTracklist"`; `applyEdits` cases also check `text`), honour
`status` (pass / xfail / ambiguous), and keep a port-local skip list that can only shrink.
-6. **Property tests** for the SPEC invariants (Hypothesis for Python, proptest for Rust).
+6. **Property tests** for the SPEC invariants (Hypothesis for Python; the Rust crate uses a small seeded generator of its own, to stay free of dev dependencies).
7. **API** idiomatic for the language but equivalent: Python `parse`, `parse_artists`,
`format_track`, `normalize` (snake_case fields are fine only if the JSON output keeps the spec's
keys); Rust with `serde` behind a feature flag and `unicode-normalization` as the only required
@@ -372,6 +429,28 @@ Hazards the Python port ran into. Fixtures alone did not catch all of them; comp
- **Python 3.9 at runtime.** `X | None` in annotations evaluated at runtime (dataclasses,
`get_type_hints`) breaks on 3.9; use `Optional[X]`. Ruff's UP007/UP045 are disabled for this.
+Hazards the Rust port ran into. Again the fixtures passed first; compare-ports and random
+differential runs against JS (about 500,000 single-track inputs, 290,000 tracklists with edits)
+found these:
+
+- **Letter and uppercase need generated tables.** R0.6 is general category L and Lu.
+ `char::is_alphabetic()` and `char::is_uppercase()` test the wider `Alphabetic` and `Uppercase`
+ properties (Nl, some marks, Other_Uppercase). The crate generates range tables
+ (`unicode_tables.rs`).
+- **`str::to_lowercase` follows the compiler's Unicode version**, not Node's. The dedup key (R0.4)
+ uses a generated lowercase mapping instead, with JS's final-sigma rule.
+- **The normalisation crate has its own Unicode version.** `unicode-normalization` ships Unicode 18
+ while Node 24 has 17, so 32 new combining marks are ordered differently in NFC. Any port that
+ takes NFC from a library inherits that library's Unicode version.
+- **Keyword option values are arbitrary strings.** JS passes any string given as a version type or
+ junk kind in `options.keywords` through to the output. Typed enums cannot hold them, so the
+ pipeline keeps types and kinds as strings (`RawTrack`), `wire` writes that form, and the typed
+ API maps unknown names to `VersionType::Version` / `JunkKind::Other`.
+- **JS number-to-string rules reach the output.** Edit warnings echo the `line` an edit named, so
+ the JSON writer must format numbers as JS does (`1e+21`, no `.0` on whole values, `-0` as `0`).
+- **Lone surrogates.** A Rust `str` cannot hold them; the crate's JSON reader (`json.rs`) turns an
+ unpaired `\uD800` escape into U+FFFD.
+
R13 (tracklists) notes for a new port:
- **Two passes per text.** First a cheap *probe* per line: the R13.2 time scan, then R1, R2 and R4
@@ -397,7 +476,7 @@ R13 (tracklists) notes for a new port:
hazard above does not apply here.
- **Time ceilings.** R13.11 asks for linear time; each port's suite picks its own 10,000-line
ceilings: `parseTracklist` JS 3 s, Python 15 s; `applyEdits` (shift + sort, 2,000 edits) JS 1 s,
- Python 2 s / 5 s.
+ Python 2 s / 5 s. The Rust ceilings are in `rust/tests/tracklist_properties.rs`.
## Versioning and release
@@ -406,16 +485,17 @@ Releases are automated with [release-please](https://github.com/googleapis/relea
1. Feature PRs are **rebase-merged**, so every commit lands on `main` and becomes its own
changelog line: each commit message must be a conventional commit, and so must the PR title
(`pr-title.yml` enforces the title). Release PRs (`chore: release main`) are squash-merged. Types: `feat`, `fix`, `perf`, `revert`, `docs` (shown in the changelog) and `refactor`,
- `test`, `build`, `ci`, `chore` (hidden). Scopes: `js`, `python`, `spec`, `generator`, `fixtures`, `site`, `ci`, `deps`…
+ `test`, `build`, `ci`, `chore` (hidden). Scopes: `js`, `python`, `rust`, `spec`, `generator`, `fixtures`, `site`, `ci`, `deps`…
2. On every push to `main`, `release.yml` updates a **release PR** (`chore: release main`) that
bumps `js/package.json`, `spec/VERSION`, `SPEC_VERSION` in `js/src/data.generated.ts`, the
- Python version files (below), and writes `js/CHANGELOG.md` / `spec/CHANGELOG.md` /
- `python/CHANGELOG.md`.
-3. **Merging the release PR** creates tags `js-vX.Y.Z`, `spec-vX.Y.Z` and `python-vX.Y.Z`, GitHub
- Releases with the changelog as notes, then publishes `trackparse` to npm and to PyPI via trusted
- publishing (OIDC, no stored token), attaches the tarball / wheel + sdist and appends install
- instructions to each release. For a bigger release, add
- `.github/release-notes/X.Y.Z.md` beforehand: it is prepended to the notes.
+ Python and Rust version files (below), and writes `js/CHANGELOG.md` / `spec/CHANGELOG.md` /
+ `python/CHANGELOG.md` / `rust/CHANGELOG.md`.
+3. **Merging the release PR** creates tags `js-vX.Y.Z`, `spec-vX.Y.Z`, `python-vX.Y.Z` and
+ `rust-vX.Y.Z`, GitHub Releases with the changelog as notes, then publishes `trackparse` to npm
+ and to PyPI via trusted publishing (OIDC, no stored token), attaches the tarball / wheel + sdist
+ and appends install instructions to each release. The crates.io job (`publish-crates`) runs
+ only when the repository variable `CRATES_PUBLISH` is `true` (see below). For a bigger release,
+ add `.github/release-notes/X.Y.Z.md` beforehand: it is prepended to the notes.
Version rules:
@@ -428,12 +508,32 @@ Version rules:
`python/pyproject.toml`, `__version__` in `python/src/trackparse/__init__.py` and `SPEC_VERSION`
in `python/src/trackparse/_data.py`, and writes `python/CHANGELOG.md`. Merging it tags
`python-vX.Y.Z` and publishes to PyPI via trusted publishing (environment `pypi`), with the wheel
- and sdist attached to the release. `spec.yml` checks that all three versions match.
-- A future Rust port (`rs-vX.Y.Z`) will be added the same way.
+ and sdist attached to the release. `spec.yml` checks that all four versions match.
+- `rust` is **linked** as well: a release-please component (`release-type: rust`) in the same
+ `linked-versions` group. The release PR bumps `rust/Cargo.toml` (the line marked
+ `x-release-please-version`) and `SPEC_VERSION` in `rust/src/data.rs`, and writes
+ `rust/CHANGELOG.md`. Merging it tags `rust-vX.Y.Z` and creates the GitHub Release. `Cargo.lock`
+ is git-ignored, so there is no lock file to bump.
+- **crates.io publishing is gated.** The `publish-crates` job in `release.yml` (environment
+ `crates`: version check, `cargo test --all-features`, `cargo package`, `cargo publish` with a
+ token from crates.io trusted publishing, the `.crate` file attached to the release) runs only
+ when the repository variable `CRATES_PUBLISH` is `true`. crates.io can only configure trusted
+ publishing for a crate that already exists, so the first publish is the maintainer's, by hand:
+ 1. from the `rust-vX.Y.Z` tag, `cd rust && cargo publish` with a personal crates.io token;
+ 2. on crates.io, add a trusted publisher for `4matic/trackparse`, workflow `release.yml`,
+ environment `crates`;
+ 3. set the repository variable `CRATES_PUBLISH` to `true`
+ (`gh variable set CRATES_PUBLISH --body true`).
+
+ Until then a release still tags `rust-vX.Y.Z` but skips the crates.io job, and the crate is
+ installed from git (`cargo add trackparse --git https://github.com/4matic/trackparse`; cargo
+ finds the package in `rust/` by name). After step 3, drop the "not on crates.io yet" notes from
+ the READMEs and the site.
- **A publish job failed after the tags were created?** Fix the cause on `main` with a hidden commit
type (`ci`/`chore`, so no new release), then re-run publishing for the existing tag:
`gh workflow run release.yml -f python_tag=python-vX.Y.Z` (PyPI). The npm job always republishes
- from a fresh release; a failed npm publish needs the same treatment by hand.
+ from a fresh release; a failed npm publish needs the same treatment by hand, and so does a failed
+ crates.io publish (`cargo publish` from the `rust-vX.Y.Z` tag; there is no re-run input for it).
- **Agents never merge release PRs, publish, push tags or bump versions on their own initiative.**
Merging the release PR is the maintainer's publish decision.
@@ -445,8 +545,11 @@ Version rules:
- JS: TypeScript strict, Biome formatting (2 spaces, double quotes, 100 columns), no runtime
dependencies, ES2020 target, ESM + CJS via tsup.
- Python: ruff (100 columns), `mypy --strict`, no runtime dependencies, Python 3.9 syntax.
-- Public types in `js/src/types.ts` and `python/src/trackparse/types.py` mirror the schemas;
- change them together.
+- Rust: rustfmt (100 columns), clippy with `-D warnings`, MSRV 1.74, `unicode-normalization` as
+ the only required dependency, no `unsafe`. `unwrap`, `expect`, `panic!` and indexing are denied
+ in `src/` (R0.8): use `get`, iterators and `Option`.
+- Public types in `js/src/types.ts`, `python/src/trackparse/types.py` and `rust/src/types.rs`
+ mirror the schemas; change them together.
- No `throw` on any input path. Bad options fall back to defaults.
## Definition of done
@@ -458,10 +561,12 @@ Version rules:
- [ ] `pnpm gen:check` and `pnpm --filter @trackparse/fixture-gen validate` pass
- [ ] Python: `gen_data.py --check`, ruff, `mypy --strict src` and `pytest` pass; conformance is
100%; `python/tests/skip.json` did not grow
-- [ ] `node scripts/compare-ports.mjs` reports 0 differences
+- [ ] Rust: `gen_data.mjs --check`, `cargo fmt --check`, clippy and `cargo test` pass; the
+ `TRACKPARSE_REPORT=1` report is 100%; `rust/tests/skip.json` did not grow
+- [ ] `node scripts/compare-ports.mjs` reports 0 differences (all three ports)
- [ ] `pnpm --filter trackparse size` and `check:package` pass
- [ ] R13 changes: `node scripts/corpus-check.mjs` passes when you have the corpus
- [ ] Conventional commits and PR title; `feat` if any fixture expectation changed
-- [ ] Site pages (`site/src/content/docs`) and READMEs updated in the same PR, examples in both
- JavaScript and Python tabs with real output, `**Docs:**` links still pointing at existing
+- [ ] Site pages (`site/src/content/docs`) and READMEs updated in the same PR, examples in
+ JavaScript, Python and Rust tabs with real output, `**Docs:**` links still pointing at existing
pages, `pnpm docs:build` passes
diff --git a/README.md b/README.md
index 7eed57c..1386c23 100644
--- a/README.md
+++ b/README.md
@@ -99,15 +99,16 @@ Every key is always present. When a guess was involved, `warnings` says which on
| Number | What it means |
|---|---|
-| **13,124** shared fixtures | 1,197 written by hand, 11,927 generated from combinations. 100% pass in JS and Python, nothing skipped. |
-| **1,233** of them on tracklists | 297 handwritten, 936 generated. Line splitting, times, bullets and Markdown, warnings, edits |
-| **1,346** JS tests | every fixture, a schema check on every output, property-based tests of the spec invariants, API tests |
+| **13,130** shared fixtures | 1,203 written by hand, 11,927 generated from combinations. 100% pass in JS, Python and Rust, nothing skipped. |
+| **1,239** of them on tracklists | 303 handwritten, 936 generated. Line splitting, times, bullets and Markdown, warnings, edits |
+| **1,352** JS tests | every fixture, a schema check on every output, property-based tests of the spec invariants, API tests |
| **27** version types | remix, VIP, bootleg, extended, radio, original, live, remaster, sped up, … |
| **0** dependencies | ESM + CJS + TypeScript types, about 17 kB gzipped. `trackparse/tracklist` adds about 8.3 KiB, only if you import it |
| **Node 18+** | CI runs the full suite on 22 and 24, and every fixture against the built package on 18 and 20 |
-| **Python 3.9+** | 1,336 pytest tests on 3.9 to 3.14, plus every fixture against the built wheel. Output is byte-identical to JS |
+| **Python 3.9+** | 1,342 pytest tests on 3.9 to 3.14, plus every fixture against the built wheel. Output is byte-identical to JS |
+| **Rust 1.74+** | every fixture, the tracklist invariants and the typed API tests on stable and on 1.74. Output is byte-identical to JS on every fixture and on about 790,000 random inputs |
| **5,031** real tracklist lines | 117 podcast tracklists the tracklist rules were checked against. Every line round-trips byte for byte |
-| **1 spec** | [`spec/SPEC.md`](spec/SPEC.md) defines the behaviour; the Python port passes the same fixtures, and so will Rust |
+| **1 spec** | [`spec/SPEC.md`](spec/SPEC.md) defines the behaviour; the Python and Rust ports pass the same fixtures |
## Install
@@ -121,7 +122,14 @@ Works in Node 18+ and any runtime with ES2020.
pip install trackparse # or: uv add trackparse
```
-Python 3.9+, no dependencies. A Rust port is [on the way](#ports).
+Python 3.9+, no dependencies.
+
+```sh
+cargo add trackparse
+```
+
+Rust 1.74+, one dependency (`unicode-normalization`), `serde` as an optional feature. The crate is not on crates.io yet; until it
+is, use `cargo add trackparse --git https://github.com/4matic/trackparse`. See [Ports](#ports).
## Quick start
@@ -175,10 +183,45 @@ track.to_dict()["artists"][1]
Options are keyword arguments: `parse(s, mode="youtube", known_artists=["Chase & Status"])`. The
full Python API is in [`python/README.md`](python/README.md).
+### Rust
+
+The same parser again. Functions are snake_case, results are structs with public fields and enums
+for roles, types and kinds, and `to_json()` writes the spec's JSON, identical to the JS output.
+
+```rust
+use trackparse::{format_track_with, parse, parse_artists, FeatPlacement, FormatOptions, JoinerStyle};
+
+let track = parse("Noisia feat. Foreign Beggars - Shellshock");
+track.artists;
+// [Artist { name: "Noisia", role: Primary, joiner: None, source: Artist },
+// Artist { name: "Foreign Beggars", role: Featured, joiner: Some("feat."), source: Artist }]
+
+parse("Queen - Bohemian Rhapsody (Live at Wembley 1986)").versions[0];
+// Version { version_type: Live, raw: "Live at Wembley 1986", artists: [], modifiers: [],
+// descriptor: Some("at Wembley"), year: Some(1986), unknown_artist: false, delimiter: Paren }
+
+parse_artists("Sub Focus, Wilkinson & Dimension feat. Kojo")
+ .iter().map(|a| format!("{}:{}", a.name, a.role)).collect::>();
+// ["Sub Focus:primary", "Wilkinson:primary", "Dimension:primary", "Kojo:featured"]
+
+let options = FormatOptions::new().feat(FeatPlacement::Title).joiners(JoinerStyle::Canonical);
+format_track_with(&parse("Wilkinson ft. Becky Hill - Afterglow (Sub Focus Remix)"), &options);
+// "Wilkinson - Afterglow (feat. Becky Hill) (Sub Focus Remix)"
+
+track.artists[1].to_json();
+// {"name":"Foreign Beggars","role":"featured","joiner":"feat.","source":"artist"}
+```
+
+Options are builders passed to the `_with` form of a function:
+`parse_with(s, &ParseOptions::new().known_artists(["Chase & Status"]))`. Tracklists are in
+`trackparse::tracklist`. Every example on the [documentation site](https://4matic.github.io/trackparse/)
+has a Rust tab.
+
> [!TIP]
> `&` is a joiner, so `Chase & Status` comes out as two artists. There's no built-in artist
> database. Pass the names you know instead: `parse(s, { knownArtists: ["Chase & Status"] })` in
-> JS, `parse(s, known_artists=["Chase & Status"])` in Python.
+> JS, `parse(s, known_artists=["Chase & Status"])` in Python,
+> `parse_with(s, &ParseOptions::new().known_artists(["Chase & Status"]))` in Rust.
## What it understands
@@ -353,14 +396,15 @@ of the list uses spaced dashes.
The fixtures in [`spec/fixtures`](spec/fixtures) are the source of truth. The spec says what should
happen, the fixtures pin it down, and every port has to pass all of them. The JS and Python
-packages both do: **13,124 of 13,124**, with empty skip lists, in CI on every push.
+packages and the Rust crate all do: **13,130 of 13,130**, with empty skip lists, in CI on every push.
Passing a fixture only checks the fields the case asserts, so
-[`scripts/compare-ports.mjs`](scripts/compare-ports.mjs) also runs every fixture input through both
-ports and diffs the complete outputs, tracklists and edits included. Result: 0 differences, byte
-for byte.
+[`scripts/compare-ports.mjs`](scripts/compare-ports.mjs) also runs every fixture input through all
+three ports and diffs the complete outputs, tracklists and edits included. Result: 0 differences,
+byte for byte. The Rust crate was also compared with JS on about 500,000 random single-track cases
+and 290,000 random tracklists with edits: 0 differences.
-### Handwritten: 1,197 cases in 27 files
+### Handwritten: 1,203 cases in 27 files
Each case cites the spec rules it exercises. 62 of them spell out the complete output field by
field, so nothing can drift unnoticed.
@@ -376,7 +420,7 @@ field, so nothing can drift unnoticed.
| Modes | 65 | YouTube pipes, `"Title" by Artist`, uploader fallback, filenames |
| Unicode and normalization | 71 | NFC, zero-width characters, fullwidth brackets, Cyrillic, CJK, Turkish İ |
| `format`, `parseArtists`, unknown IDs | 94 | Round-trips, canonical joiners, `ID - ID` |
-| Tracklist mode | 61 | All 17 real podcast lines that single-line `parse()` gets wrong, the 6 real lines with no separator at all, `parse(s, { mode: "tracklist" })`, Markdown emphasis around names, and names that keep their `*` and `_` |
+| Tracklist mode | 67 | All 17 real podcast lines that single-line `parse()` gets wrong, the 6 real lines with no separator at all, `parse(s, { mode: "tracklist" })`, Markdown emphasis around names, and names that keep their `*` and `_` |
| Tracklist lines and times | 104 | LF/CRLF/CR, trailing spaces, line kinds, every time form, brackets, gap separators, `=>` arrows, invalid times, list bullets, Markdown around times, `w/` lines |
| Tracklist positions | 15 | The real 81-line list numbered `1 ` to `81 ` without dots, and the `2 Unlimited` guard, with a `w/` line in between |
| Tracklist warnings | 38 | Each code with its near-miss, and the 10 real out-of-order lists with their suggestions |
@@ -452,6 +496,7 @@ pnpm conformance # pass rate per fixture file and per spec rule
pnpm --filter trackparse build && node scripts/corpus-check.mjs spec/corpus/.jsonl
cd python && uv run pytest # the same fixtures and invariants in Python
+cd rust && cargo test # and in Rust
```
## API
@@ -557,7 +602,7 @@ parser.parse("Chase & Status x Camo & Krooked - Track (Alix Perez Rerub)").versi
**Docs:** [Tracklist API](https://4matic.github.io/trackparse/reference/tracklist/) · [Warnings](https://4matic.github.io/trackparse/reference/warnings/)
-Import from `trackparse/tracklist` (Python: `trackparse.tracklist`). It's a separate entry, so code
+Import from `trackparse/tracklist` (Python: `trackparse.tracklist`, Rust: `trackparse::tracklist`). It's a separate entry, so code
that only parses single tracks never loads it.
#### `parseTracklist(text, options?)` → `Tracklist`
@@ -677,9 +722,9 @@ spaced dashes. The checks run last, over the finished entries.
| Language | Package | Status |
|---|---|---|
-| JavaScript / TypeScript | [`trackparse`](https://www.npmjs.com/package/trackparse) on npm | reference implementation, 13,124 / 13,124 fixtures, tracklists as `trackparse/tracklist` |
-| Python | [`trackparse`](https://pypi.org/project/trackparse/) on PyPI | 13,124 / 13,124 fixtures, output identical to JS, tracklists as `trackparse.tracklist` |
-| Rust | `trackparse` on crates.io | planned, same fixtures |
+| JavaScript / TypeScript | [`trackparse`](https://www.npmjs.com/package/trackparse) on npm | reference implementation, 13,130 / 13,130 fixtures, tracklists as `trackparse/tracklist` |
+| Python | [`trackparse`](https://pypi.org/project/trackparse/) on PyPI | 13,130 / 13,130 fixtures, output identical to JS, tracklists as `trackparse.tracklist` |
+| Rust | `trackparse` on crates.io | passes 13,130 / 13,130, output identical to JS, tracklists as `trackparse::tracklist`; publishing to crates.io pending |
Want another language? The porting checklist is in [AGENTS.md](AGENTS.md).
@@ -718,7 +763,7 @@ Not there yet:
doesn't yet learn names from its other lines.
- Warnings for gaps or overlaps between consecutive tracklist times.
-Planned next: the Rust port. The browser playground is already live at
+Planned next: publishing the Rust crate to crates.io. The browser playground is already live at
[4matic.github.io/trackparse/playground](https://4matic.github.io/trackparse/playground/).
## Contributing
diff --git a/js/README.md b/js/README.md
index 3f63022..69ca8ea 100644
--- a/js/README.md
+++ b/js/README.md
@@ -11,7 +11,7 @@ Parse music track names into structured metadata: artists, featured artists, rem
This is the JavaScript/TypeScript reference implementation of the
[trackparse spec](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md). It passes all
-13,124 shared fixtures. Zero dependencies, ESM and CommonJS, TypeScript types included, never
+13,130 shared fixtures. Zero dependencies, ESM and CommonJS, TypeScript types included, never
throws.
The principle is **extract, don't delete**: everything recognised lands in a field (artists with
diff --git a/python/README.md b/python/README.md
index d648579..c0fbb7e 100644
--- a/python/README.md
+++ b/python/README.md
@@ -21,7 +21,7 @@ doesn't recognise stays in the title, word for word.
This is the Python port of [trackparse](https://github.com/4matic/trackparse). Its behaviour is
defined by a [shared spec](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md) and pinned
-by 13,124 fixtures. It passes all of them, and for every fixture input its output is byte-identical
+by 13,130 fixtures. It passes all of them, and for every fixture input its output is byte-identical
to the JavaScript package.
- Python 3.9 to 3.14
diff --git a/release-please-config.json b/release-please-config.json
index f291168..7c4137d 100644
--- a/release-please-config.json
+++ b/release-please-config.json
@@ -4,7 +4,7 @@
"tag-separator": "-",
"bump-minor-pre-major": true,
"bump-patch-for-minor-pre-major": false,
- "pull-request-header": ":robot: Merging this PR tags the release, publishes a GitHub Release with these notes and publishes to npm and PyPI.",
+ "pull-request-header": ":robot: Merging this PR tags the release, publishes a GitHub Release with these notes and publishes to npm, PyPI and crates.io.",
"changelog-sections": [
{
"type": "feat",
@@ -94,6 +94,19 @@
}
],
"initial-version": "0.1.0"
+ },
+ "rust": {
+ "release-type": "rust",
+ "component": "rust",
+ "package-name": "trackparse",
+ "changelog-path": "CHANGELOG.md",
+ "extra-files": [
+ {
+ "type": "generic",
+ "path": "src/data.rs"
+ }
+ ],
+ "initial-version": "0.1.0"
}
},
"plugins": [
@@ -103,7 +116,8 @@
"components": [
"js",
"spec",
- "python"
+ "python",
+ "rust"
]
}
]
diff --git a/rust/.gitignore b/rust/.gitignore
new file mode 100644
index 0000000..ea8c4bf
--- /dev/null
+++ b/rust/.gitignore
@@ -0,0 +1 @@
+/target
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
new file mode 100644
index 0000000..2e41b81
--- /dev/null
+++ b/rust/Cargo.lock
@@ -0,0 +1,123 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 3
+
+[[package]]
+name = "itoa"
+version = "1.0.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.154"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "syn"
+version = "3.0.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "tinyvec"
+version = "1.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
+
+[[package]]
+name = "trackparse"
+version = "0.4.0"
+dependencies = [
+ "serde",
+ "serde_json",
+ "unicode-normalization",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
+
+[[package]]
+name = "unicode-normalization"
+version = "0.1.26"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d"
+dependencies = [
+ "tinyvec",
+]
+
+[[package]]
+name = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
new file mode 100644
index 0000000..d825451
--- /dev/null
+++ b/rust/Cargo.toml
@@ -0,0 +1,41 @@
+[package]
+name = "trackparse"
+version = "0.4.0" # x-release-please-version
+edition = "2021"
+rust-version = "1.74"
+description = "Turn messy track names into structured data: artists with roles, remixes and versions, junk, and whole tracklists. One spec, same output as the JavaScript and Python packages."
+license = "MIT"
+repository = "https://github.com/4matic/trackparse"
+homepage = "https://4matic.github.io/trackparse/"
+documentation = "https://docs.rs/trackparse"
+readme = "README.md"
+keywords = ["music", "parser", "tracklist", "artist", "remix"]
+categories = ["parser-implementations", "multimedia::audio", "text-processing"]
+include = ["src/**", "README.md", "LICENSE"]
+
+[dependencies]
+# NFC / NFD follow this crate's Unicode tables (Unicode 18 in 0.1.26). Older releases have older
+# tables and normalize some strings differently, so they are not accepted.
+unicode-normalization = "0.1.26"
+serde = { version = "1", features = ["derive"], optional = true }
+
+[dev-dependencies]
+serde_json = "1"
+
+[features]
+default = []
+# Serialize / Deserialize on the result types, the options and tracklist::Edit.
+serde = ["dep:serde"]
+
+[package.metadata.docs.rs]
+all-features = true
+rustdoc-args = ["--cfg", "docsrs"]
+
+[lints.rust]
+unsafe_code = "forbid"
+
+[lints.clippy]
+unwrap_used = "deny"
+expect_used = "deny"
+panic = "deny"
+indexing_slicing = "deny"
diff --git a/rust/LICENSE b/rust/LICENSE
new file mode 100644
index 0000000..4384c06
--- /dev/null
+++ b/rust/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Maksim Maksimov
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/rust/README.md b/rust/README.md
index bf6f146..fc15a4a 100644
--- a/rust/README.md
+++ b/rust/README.md
@@ -1,9 +1,660 @@
-# trackparse (Rust)
+# trackparse
-**Status: planned.** The Rust crate will be published to crates.io as `trackparse`. It will depend
-only on `unicode-normalization`, with `serde` behind a feature flag, and it will pass the same shared
-fixtures in [`../spec/fixtures`](../spec/fixtures).
+[](https://crates.io/crates/trackparse)
+[](https://docs.rs/trackparse)
+[](https://github.com/4matic/trackparse/actions/workflows/rust.yml)
+[](https://github.com/4matic/trackparse/blob/main/LICENSE)
-Until then, see the [spec](../spec/SPEC.md) and the [JS package](../js).
+**[Documentation](https://4matic.github.io/trackparse/)** · **[Getting started](https://4matic.github.io/trackparse/start/getting-started/)** · **[Playground](https://4matic.github.io/trackparse/playground/)** · **[API on docs.rs](https://docs.rs/trackparse)**
-**Docs:** [Ports](https://4matic.github.io/trackparse/project/ports/) · [Adding a language](https://4matic.github.io/trackparse/project/ports/#adding-a-language)
+**Turn messy track names into structured data: who made it, who's featured, who remixed it, and
+what's just noise.**
+
+```text
+01. Wilkinson ft. Becky Hill & Tom Cane - Afterglow (Sub Focus VIP Remix) [Official Video]
+```
+
+Most title parsers split that into `"Wilkinson ft. Becky Hill & Tom Cane"` and
+`"Afterglow (Sub Focus VIP Remix)"` and stop. Others "clean" it and throw the feat and the remix
+away. trackparse keeps all of it. Everything it recognises goes into a field, and anything it
+doesn't recognise stays in the title, word for word.
+
+This is the Rust port of [trackparse](https://github.com/4matic/trackparse). Its behaviour is
+defined by a [shared spec](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md) and pinned
+by 13,130 fixtures. It passes all of them, and for every fixture input its output is byte-identical
+to the JavaScript and Python packages.
+
+- Rust 1.74 or later
+- One dependency (`unicode-normalization`); `serde` is optional
+- No `unsafe`, no regular expressions
+- Never panics and never returns an error: any `&str` gives a result
+
+## Install
+
+```sh
+cargo add trackparse
+# with Serialize / Deserialize on the types
+cargo add trackparse --features serde
+```
+
+## Quick start
+
+**Docs:** [Getting started](https://4matic.github.io/trackparse/start/getting-started/)
+
+```rust
+use trackparse::{format_track_with, parse, FormatOptions, JoinerStyle, JunkKind, Mode, VersionType};
+
+let track = parse(
+ "01. Wilkinson ft. Becky Hill & Tom Cane - Afterglow (Sub Focus VIP Remix) [Official Video]",
+);
+
+let credits: Vec = track.artists.iter().map(|a| format!("{} ({})", a.name, a.role)).collect();
+assert_eq!(credits, ["Wilkinson (primary)", "Becky Hill (featured)", "Tom Cane (featured)"]);
+assert_eq!(track.title, "Afterglow");
+assert_eq!(track.full_title, "Afterglow (Sub Focus VIP Remix)");
+assert_eq!(track.versions[0].version_type, VersionType::Remix);
+assert_eq!(track.versions[0].artists[0].name, "Sub Focus");
+assert_eq!(track.versions[0].modifiers, ["vip"]);
+assert_eq!(track.junk[0].raw, "Official Video");
+assert_eq!(track.junk[0].kind, JunkKind::Video);
+assert_eq!(track.position.as_ref().map(|p| p.number), Some(1));
+assert_eq!(track.mode, Mode::Youtube);
+
+let options = FormatOptions::new().joiners(JoinerStyle::Canonical);
+assert_eq!(
+ format_track_with(&track, &options),
+ "Wilkinson feat. Becky Hill & Tom Cane - Afterglow (Sub Focus VIP Remix)"
+);
+```
+
+`to_json()` returns the spec's JSON form as compact text, with the same camelCase keys the
+JavaScript package uses:
+
+```rust
+let track = trackparse::parse("Wilkinson ft. Becky Hill - Afterglow (Sub Focus VIP Remix) [HD]");
+println!("{}", track.to_json());
+```
+
+
+Output
+
+```json
+{
+ "input": "Wilkinson ft. Becky Hill - Afterglow (Sub Focus VIP Remix) [HD]",
+ "mode": "youtube",
+ "position": null,
+ "timestamp": null,
+ "artists": [
+ { "name": "Wilkinson", "role": "primary", "joiner": null, "source": "artist" },
+ { "name": "Becky Hill", "role": "featured", "joiner": "ft.", "source": "artist" }
+ ],
+ "title": "Afterglow",
+ "fullTitle": "Afterglow (Sub Focus VIP Remix)",
+ "versions": [
+ {
+ "type": "remix",
+ "raw": "Sub Focus VIP Remix",
+ "artists": [{ "name": "Sub Focus", "role": "remixer", "joiner": null, "source": "version" }],
+ "modifiers": ["vip"],
+ "descriptor": null,
+ "year": null,
+ "unknownArtist": false,
+ "delimiter": "("
+ }
+ ],
+ "year": null,
+ "flags": { "explicit": false, "clean": false, "unknownArtist": false, "unknownTitle": false },
+ "junk": [{ "raw": "HD", "kind": "quality" }],
+ "warnings": []
+}
+```
+
+(Reformatted for width; the keys and values are exactly what `to_json()` returns.)
+
+
+
+## API
+
+**Docs:** [Other functions](https://4matic.github.io/trackparse/reference/functions/)
+
+```text
+parse(input: &str) -> ParsedTrack
+parse_with(input: &str, options: &ParseOptions) -> ParsedTrack
+parse_artists(input: &str) -> Vec
+parse_artists_with(input: &str, options: &ParseOptions) -> Vec
+format_track(track: &ParsedTrack) -> String
+format_track_with(track: &ParsedTrack, options: &FormatOptions) -> String
+normalize(input: &str) -> String
+all_artists(track: &ParsedTrack) -> Vec
+Parser::new(options: &ParseOptions) -> Parser // parser.parse(..), parser.parse_artists(..)
+SPEC_VERSION: &str
+
+tracklist::parse_tracklist(text: &str) -> Tracklist
+tracklist::parse_tracklist_with(text: &str, options: &TracklistOptions) -> Tracklist
+tracklist::apply_edits(text: &str, edits: &[Edit]) -> EditResult
+tracklist::apply_edits_with(text: &str, edits: &[Edit], options: &TracklistOptions) -> EditResult
+```
+
+Every function has a plain form with the default options and a `_with` form that takes them.
+
+### `parse` and `ParseOptions`
+
+**Docs:** [parse and ParsedTrack](https://4matic.github.io/trackparse/reference/parse/) · [Options](https://4matic.github.io/trackparse/reference/options/)
+
+| Option | Default | |
+|---|---|---|
+| `mode` | `ModeOption::Auto` | `Clean`, `Youtube`, `Filename`, `Tracklist`, or `Auto` to detect from the string |
+| `uploader` | `None` | YouTube channel name, used as the artist when there's no separator (`- Topic` and `VEVO` are dropped) |
+| `known_artists` | empty | Names that are never split. There is no built-in list |
+| `split_and` | `SplitAnd::Auto` | `Auto` splits on `and` only after a comma (`A, B and C`), so `Simon and Garfunkel` stays whole. Also `Always`, `Never` |
+| `keywords` | `None` | Extra vocabulary, added to the built-in lists (see below) |
+
+Options are built with chained setters. The structs are `#[non_exhaustive]`, so start from
+`ParseOptions::new()` (or `default()`); the fields are public and can also be assigned.
+
+```rust
+use trackparse::{parse, parse_with, ParseOptions, SplitAnd};
+
+let names = |track: &trackparse::ParsedTrack| -> Vec {
+ track.artists.iter().map(|a| a.name.clone()).collect()
+};
+
+assert_eq!(names(&parse("Chase & Status - Baddadan")), ["Chase", "Status"]);
+let options = ParseOptions::new().known_artists(["Chase & Status"]);
+assert_eq!(names(&parse_with("Chase & Status - Baddadan", &options)), ["Chase & Status"]);
+
+let options = ParseOptions::new().split_and(SplitAnd::Always);
+assert_eq!(
+ names(&parse_with("Simon and Garfunkel - Mrs. Robinson", &options)),
+ ["Simon", "Garfunkel"]
+);
+```
+
+`KeywordOptions` adds words to the built-in lists:
+
+| Setter | Field | |
+|---|---|---|
+| `version_head(word, VersionType)` | `version_heads` | Word that sets a version type (`"rerub"` as `VersionType::Rework`) |
+| `descriptor(word)` | `descriptors` | Words kept as a version's `descriptor` |
+| `genre(word)` | `genres` | Genre words |
+| `junk(phrase, JunkKind)` | `junk` | Phrase to junk kind (`"some label rip"` as `JunkKind::Label`) |
+| `feat_marker(marker)` | `feat_markers` | Extra feat markers |
+
+```rust
+use trackparse::{parse, parse_with, JunkKind, KeywordOptions, ParseOptions};
+
+assert_eq!(parse("Artist - Song [Some Label Rip]").title, "Song [Some Label Rip]");
+
+let keywords = KeywordOptions::new().junk("some label rip", JunkKind::Label);
+let track = parse_with("Artist - Song [Some Label Rip]", &ParseOptions::new().keywords(keywords));
+assert_eq!(track.title, "Song");
+assert_eq!(track.junk[0].raw, "Some Label Rip");
+assert_eq!(track.junk[0].kind, JunkKind::Label);
+```
+
+Parsing is total: any `&str` gives a `ParsedTrack`, including `""`.
+
+### `ParsedTrack`
+
+**Docs:** [ParsedTrack fields](https://4matic.github.io/trackparse/reference/parse/#parsedtrack)
+
+| Field | Type | |
+|---|---|---|
+| `input` | `String` | The original string, untouched |
+| `mode` | `Mode` | Resolved mode: `Clean`, `Youtube`, `Filename` or `Tracklist` |
+| `position` | `Option` | Track number: `Position { raw: "01", number: 1 }` |
+| `timestamp` | `Option` | Leading cue time: `[12:34]` gives `Timestamp { raw: "12:34", seconds: 754 }` |
+| `artists` | `Vec` | Primary, featured and producer credits. Remixers live in `versions` |
+| `title` | `String` | Clean title. Brackets it doesn't recognise stay in |
+| `full_title` | `String` | `title` with the versions re-attached |
+| `versions` | `Vec` | Remixes and other versions, left to right |
+| `year` | `Option` | From `(2015)` or `- 2015` |
+| `flags` | `Flags` | `explicit`, `clean`, `unknown_artist`, `unknown_title` |
+| `junk` | `Vec` | What was taken out, each with a `kind` |
+| `warnings` | `Vec` | Heuristics that fired |
+
+`Artist { name, role, joiner, source }`:
+
+- `role` is `ArtistRole::Primary`, `Featured`, `Remixer` or `Producer`.
+- `joiner` is the text before the name as written (`"&"`, `","`, `"ft."`, `"prod. by"`), or `None`
+ for the first name in a list.
+- `source` is where the credit came from: `ArtistSource::Artist` (left of the dash), `Title`
+ (right of it) or `Version`.
+
+`Version { version_type, raw, artists, modifiers, descriptor, year, unknown_artist, delimiter }`
+(`version_type` is `type` in JSON):
+
+```rust
+use trackparse::{parse, VersionDelimiter, VersionType};
+
+let track = parse("Pendulum - Watercolour (Extended VIP Mix)");
+let version = &track.versions[0];
+assert_eq!(version.version_type, VersionType::Vip);
+assert_eq!(version.raw, "Extended VIP Mix");
+assert_eq!(version.modifiers, ["extended"]);
+assert_eq!(version.delimiter, VersionDelimiter::Paren);
+
+let track = parse("Queen - Bohemian Rhapsody (Live at Wembley 1986)");
+let version = &track.versions[0];
+assert_eq!(version.version_type, VersionType::Live);
+assert_eq!(version.descriptor.as_deref(), Some("at Wembley"));
+assert_eq!(version.year, Some(1986));
+```
+
+Version types, junk kinds, warnings, roles and modes are enums (`VersionType`, `JunkKind`,
+`Warning`, `ArtistRole`, `ArtistSource`, `Mode`, `ModeOption`, `VersionDelimiter`), listed in the
+[API reference](https://4matic.github.io/trackparse/reference/parse/). Each has `as_str()` (the name
+used in the spec and in JSON), `from_name()`, `ALL`, `Display` and `FromStr`:
+
+```rust
+use trackparse::VersionType;
+
+assert_eq!(VersionType::SpedUp.as_str(), "spedUp");
+assert_eq!(VersionType::from_name("remix"), Some(VersionType::Remix));
+assert_eq!("bootleg".parse::(), Ok(VersionType::Bootleg));
+assert_eq!(VersionType::ALL.len(), 27);
+```
+
+Most of these enums are `#[non_exhaustive]`: a later spec version can add a version type or a
+warning, so a `match` on them needs a `_` arm.
+
+### JSON and serde
+
+**Docs:** [JSON and Python objects](https://4matic.github.io/trackparse/reference/parse/#json-and-python-objects)
+
+Every result type has `to_json()`, which writes compact JSON matching
+[`parsed-track.schema.json`](https://github.com/4matic/trackparse/blob/main/spec/schema/parsed-track.schema.json)
+and
+[`tracklist.schema.json`](https://github.com/4matic/trackparse/blob/main/spec/schema/tracklist.schema.json)
+(`fullTitle`, `unknownArtist`, ...). The bytes are the same as `JSON.stringify(parse(s))` in
+JavaScript. It needs no feature and no dependency.
+
+With the `serde` feature, the result types, the options and `Edit` implement `Serialize` and
+`Deserialize` with the same keys, so `serde_json` writes the same text and reads it back:
+
+```rust
+use trackparse::tracklist::Edit;
+use trackparse::{parse, ModeOption, ParseOptions, ParsedTrack};
+
+let track = parse("Noisia - Stigma (2015)");
+let json = serde_json::to_string(&track).unwrap();
+assert_eq!(json, track.to_json());
+assert_eq!(serde_json::from_str::(&json).unwrap(), track);
+
+let options: ParseOptions =
+ serde_json::from_str(r#"{"mode":"youtube","knownArtists":["Chase & Status"]}"#).unwrap();
+assert_eq!(options, ParseOptions::new().mode(ModeOption::Youtube).known_artists(["Chase & Status"]));
+
+let edit: Edit = serde_json::from_str(r#"{"op":"set-time","line":3,"seconds":90}"#).unwrap();
+assert_eq!(edit, Edit::set_time(3, 90.0));
+assert_eq!(serde_json::to_string(&edit).unwrap(), r#"{"op":"set-time","line":3,"seconds":90}"#);
+```
+
+Numbers are written as `to_json()` writes them: whole seconds are integers (`90`, not `90.0`), and
+a value of 2^53 and more has the digits JavaScript prints. For every result the parser can produce
+the two texts are equal. The edge cases, all in an `Edit` or an option you build yourself:
+
+- Seconds from 0.000001 up to 0.00001 are written in `serde_json`'s float notation (`1e-6` where
+ `to_json()` writes `0.000001`), and so are seconds of 1e21 and more by older `serde_json`
+ releases (`1e21` for `1e+21`). The number is the same and reads back the same.
+- Non-finite seconds (NaN, infinity) are written as `null`, as `to_json()` and `JSON.stringify`
+ do, and `null` reads back as NaN. `apply_edits` reports such an edit as `EditInvalid` either way.
+- Line numbers above 2^53 are written as the nearest double, because that is what the edit runs
+ on (`Edit::delete(usize::MAX)` is `{"op":"delete","line":18446744073709552000}`).
+- `KeywordOptions` maps are written as JSON objects without repeated keys: a key added twice
+ keeps its first place and takes the last value, as in a JavaScript object.
+
+Reading options is strict: a missing key is the default, an unknown name such as
+`"mode":"radio"` is an error.
+
+### `parse_artists`
+
+**Docs:** [parseArtists](https://4matic.github.io/trackparse/reference/functions/#parseartistsinput-options)
+
+Splits a bare artist string. `parse_artists_with` takes the same options as `parse_with`.
+
+```rust
+use trackparse::parse_artists;
+
+let credits: Vec = parse_artists("Sub Focus, Wilkinson & Dimension feat. Kojo")
+ .iter()
+ .map(|a| format!("{}:{}", a.name, a.role))
+ .collect();
+assert_eq!(credits, ["Sub Focus:primary", "Wilkinson:primary", "Dimension:primary", "Kojo:featured"]);
+```
+
+### `format_track` and `FormatOptions`
+
+**Docs:** [format](https://4matic.github.io/trackparse/reference/functions/#formattrack-options) · [Formatting](https://4matic.github.io/trackparse/guides/formatting/)
+
+Renders a track back to a string.
+
+| Option | Default | |
+|---|---|---|
+| `feat` | `FeatPlacement::Source` | Where featured artists go: `Source` (where they were), `Artist`, `Title` or `Omit` |
+| `feat_marker` | `None` | Marker for featured artists, such as `"feat."` |
+| `joiners` | `JoinerStyle::Original` | `Original` keeps the joiners as written, `Canonical` uses the standard ones |
+| `versions` | `VersionsOption::All` | `All` or `None` |
+| `producers` | `true` | Include `(prod. ...)` credits |
+| `position` | `false` | Include the track number |
+
+```rust
+use trackparse::{
+ format_track, format_track_with, parse, FeatPlacement, FormatOptions, JoinerStyle, VersionsOption,
+};
+
+let track = parse("01. Wilkinson ft. Becky Hill - Afterglow (Sub Focus Remix)");
+assert_eq!(format_track(&track), "Wilkinson ft. Becky Hill - Afterglow (Sub Focus Remix)");
+
+let options = FormatOptions::new().feat(FeatPlacement::Title).joiners(JoinerStyle::Canonical);
+assert_eq!(
+ format_track_with(&track, &options),
+ "Wilkinson - Afterglow (feat. Becky Hill) (Sub Focus Remix)"
+);
+
+let options = FormatOptions::new().feat(FeatPlacement::Omit).versions(VersionsOption::None);
+assert_eq!(format_track_with(&track, &options), "Wilkinson - Afterglow");
+
+let options = FormatOptions::new().position(true);
+assert_eq!(
+ format_track_with(&track, &options),
+ "01. Wilkinson ft. Becky Hill - Afterglow (Sub Focus Remix)"
+);
+```
+
+### `normalize`
+
+**Docs:** [normalize](https://4matic.github.io/trackparse/reference/functions/#normalizeinput)
+
+The Unicode cleanup every function runs first: NFC, invisible characters, and dash, bracket and
+quote variants.
+
+```rust
+use trackparse::normalize;
+
+assert_eq!(normalize("Noisia\u{200b} – Stigma (VIP)"), "Noisia - Stigma (VIP)");
+```
+
+### `all_artists`
+
+**Docs:** [allArtists](https://4matic.github.io/trackparse/reference/functions/#allartiststrack)
+
+Credits plus every remixer, deduplicated.
+
+```rust
+use trackparse::{all_artists, parse};
+
+let track = parse("Wilkinson ft. Becky Hill - Afterglow (Sub Focus Remix)");
+let credits: Vec =
+ all_artists(&track).iter().map(|a| format!("{}:{}", a.name, a.role)).collect();
+assert_eq!(credits, ["Wilkinson:primary", "Becky Hill:featured", "Sub Focus:remixer"]);
+```
+
+### `Parser`
+
+**Docs:** [createParser](https://4matic.github.io/trackparse/reference/functions/#createparseroptions)
+
+Resolves the options and builds the word tables once, for many calls. It is `Send + Sync`.
+
+```rust
+use trackparse::{KeywordOptions, ParseOptions, Parser, VersionType};
+
+let options = ParseOptions::new()
+ .known_artists(["Chase & Status", "Camo & Krooked"])
+ .keywords(KeywordOptions::new().version_head("rerub", VersionType::Rework));
+let parser = Parser::new(&options);
+
+let track = parser.parse("Chase & Status x Camo & Krooked - Track (Alix Perez Rerub)");
+assert_eq!(track.artists.len(), 2);
+assert_eq!(track.versions[0].version_type, VersionType::Rework);
+```
+
+### `SPEC_VERSION`
+
+The spec version this build implements. The crate, the npm package, the PyPI package and the spec
+are released together and always share one version number.
+
+## Modes
+
+**Docs:** [Modes](https://4matic.github.io/trackparse/guides/modes/)
+
+| Mode | For | Adds |
+|---|---|---|
+| `Clean` | Store metadata, tags | Only a spaced dash separates artist and title |
+| `Youtube` | Video titles, scrobbles | Pipe segments, `"Title" by Artist`, `Artist: "Title"`, unspaced dashes, trailing junk, uploader fallback |
+| `Filename` | Files | Strips the extension, `_` becomes a space, `01-Track` numbering |
+| `Auto` | Anything | `Filename` for known extensions, `Youtube` when it sees junk, pipes or platform suffixes, `Clean` otherwise |
+| `Tracklist` | One line of a tracklist | The first spaced dash always separates; `_-_` too. Never picked by `Auto` |
+
+```rust
+use trackparse::{parse, parse_with, Mode, ModeOption, ParseOptions, Warning};
+
+let youtube = ParseOptions::new().mode(ModeOption::Youtube);
+let track = parse_with("\"Numb\" by Linkin Park", &youtube);
+assert_eq!(track.artists[0].name, "Linkin Park");
+assert_eq!(track.title, "Numb");
+assert_eq!(track.warnings, [Warning::BySplit]);
+
+let track = parse("07_Burial_-_Archangel.mp3");
+assert_eq!(track.mode, Mode::Filename);
+assert_eq!(track.artists[0].name, "Burial");
+assert_eq!(track.title, "Archangel");
+assert_eq!(track.position.as_ref().map(|p| p.number), Some(7));
+
+let track = parse_with("Shelter", &youtube.uploader("Porter Robinson"));
+assert_eq!(track.artists[0].name, "Porter Robinson");
+```
+
+## Tracklists
+
+**Docs:** [Tracklists](https://4matic.github.io/trackparse/guides/tracklists/) · [Editing tracklists](https://4matic.github.io/trackparse/guides/editing-tracklists/) · [Tracklist API](https://4matic.github.io/trackparse/reference/tracklist/) · [Warnings](https://4matic.github.io/trackparse/reference/warnings/)
+
+`trackparse::tracklist` parses a whole tracklist, one entry per line, and checks it. Each entry
+keeps its line exactly as written plus its own line ending, so joining every `raw` and `eol` is
+always the input, CRLF or not.
+
+```rust
+use trackparse::tracklist::{parse_tracklist, EntryKind, Severity, WarningCode};
+use trackparse::VersionType;
+
+let text = [
+ "Hour 2",
+ "48:20 Noisia - Stigma",
+ "52:47 Mefjus & Kasra - Bandwagon (Phace Remix)",
+ "56:05 Black Sun Empire - ID",
+ "59:31 Alix Perez - Fade Away",
+ "01:03:10 Interview with Hybris",
+ "01:07:44 Imanu - Sacrifice",
+ "00:11:02 Current Value feat. Teddy Killerz - Payload", // typo for 01:11:02
+ "01:15:36 Hybris - Spinning Top",
+]
+.join("\r\n");
+
+let list = parse_tracklist(&text);
+
+let joined: String = list.entries.iter().map(|e| format!("{}{}", e.raw, e.eol)).collect();
+assert_eq!(joined, text);
+
+use EntryKind::{Header, Marker, Track};
+let kinds: Vec = list.entries.iter().map(|e| e.kind).collect();
+assert_eq!(kinds, [Header, Track, Track, Track, Track, Marker, Track, Track, Track]);
+
+let entry = &list.entries[2];
+let time = entry.time.as_ref().unwrap();
+assert_eq!((time.raw.as_str(), time.seconds), ("52:47", 3167.0));
+assert_eq!(entry.parts.rest, "Mefjus & Kasra - Bandwagon (Phace Remix)");
+let track = entry.track.as_ref().unwrap();
+assert_eq!(track.artists.len(), 2);
+assert_eq!(track.title, "Bandwagon");
+assert_eq!(track.versions[0].version_type, VersionType::Remix);
+assert!(list.entries[3].track.as_ref().unwrap().flags.unknown_title); // the ID
+
+assert_eq!(list.warnings.len(), 2);
+assert_eq!(list.warnings[0].code, WarningCode::NoStartAtZero);
+assert_eq!(list.warnings[0].severity, Severity::Info);
+let warning = &list.warnings[1];
+assert_eq!((warning.code, warning.line), (WarningCode::TimeOutOfOrder, 8));
+let fix = warning.suggestion.as_ref().unwrap();
+assert_eq!((fix.line, fix.raw.as_str(), fix.seconds), (8, "01:11:02", 4262.0));
+
+let stats = &list.stats;
+assert_eq!((stats.lines, stats.tracks, stats.markers, stats.timed), (9, 7, 1, 8));
+assert_eq!((stats.first_time, stats.last_time), (Some(2900.0), Some(4536.0)));
+```
+
+The suggestion exists because exactly one time, one digit away from `00:11:02`, fits between its
+neighbours. With several candidates or none, `suggestion` is `None`.
+
+`apply_edits` takes a slice of `Edit` values and only rewrites the lines they name:
+
+```rust
+use trackparse::tracklist::{apply_edits, Edit, EditWarningCode};
+
+let text = "48:20 Noisia - Stigma\r\n59:31 Alix Perez - Fade Away\r\n00:03:10 Imanu - Sacrifice\r\n";
+
+let edits = [Edit::set_time(3, 3790.0), Edit::shift_from(45.0, 2)];
+let result = apply_edits(text, &edits);
+
+assert_eq!(
+ result.text,
+ "48:20 Noisia - Stigma\r\n01:00:16 Alix Perez - Fade Away\r\n01:03:55 Imanu - Sacrifice\r\n"
+);
+assert_eq!(result.changed, [2, 3]);
+assert_eq!(result.warnings[0].code, EditWarningCode::StyleUpgraded);
+assert_eq!((result.warnings[0].edit, result.warnings[0].line), (1, Some(2)));
+
+let result = apply_edits(text, &[Edit::shift_lines(-3000.0, [1])]);
+assert_eq!(result.warnings[0].code, EditWarningCode::TimeClamped);
+```
+
+A rewritten time keeps its line's style: `48:20` stays `MM:SS`, and a time that crosses the hour
+gets hours, with a `style-upgraded` warning. A bad edit changes nothing and warns `edit-invalid`.
+Neither function panics.
+
+`TracklistOptions` has `mode` (default `ModeOption::Tracklist`), `known_artists`, `split_and`,
+`keywords`, `audio_seconds` (enables `time-after-audio-end`) and `marker_words`:
+
+```rust
+use trackparse::tracklist::{parse_tracklist_with, TracklistOptions, WarningCode};
+
+let options = TracklistOptions::new().audio_seconds(3600.0);
+let list = parse_tracklist_with("00:00 A - B\n1:02:03 C - D", &options);
+assert_eq!(list.warnings[0].code, WarningCode::TimeAfterAudioEnd);
+assert_eq!(list.warnings[0].line, 2);
+```
+
+| Result | Fields |
+|---|---|
+| `Tracklist` | `spec_version`, `entries`, `warnings`, `stats` |
+| `TracklistEntry` | `line` (1-based), `kind` (`EntryKind`: `Track`, `Marker`, `Header`, `Link`, `Note`, `Blank`), `eol`, `raw`, `parts`, `time`, `track` (`Option`), `layered` (the track text after any time starts with `w/`) |
+| `Parts` | `lead`, `time`, `gap`, `rest`, joined they give `raw` |
+| `TracklistWarning` | `code` (`WarningCode`), `line`, `severity` (`Info` or `Warning`), `suggestion` |
+| `TimeValue` | `raw`, `seconds` (`entry.time`, or `None` on untimed lines) |
+| `Suggestion` | `line`, `raw`, `seconds` (`warning.suggestion`, or `None`) |
+| `Stats` | `lines`, `tracks`, `markers`, `timed`, `first_time`, `last_time` |
+| `EditResult` | `text`, `changed`, `warnings` (`EditWarning { code, edit, line }`) |
+
+Lists pasted with list bullets or Markdown emphasis (`* 14:21 Artist - Title`,
+`**[**14:21**] Artist - Title**`) read like plain lines; the decoration stays in `raw` and `parts`.
+A line whose track text (after any time) starts with `w/` is `layered`: a track played over the
+previous one
+([Markdown](https://4matic.github.io/trackparse/guides/tracklists/#markdown),
+[layered tracks](https://4matic.github.io/trackparse/guides/tracklists/#layered-tracks)).
+
+Warning codes (`WarningCode`): `time-missing`, `time-out-of-order`, `time-duplicate`,
+`no-start-at-zero`, `time-after-audio-end` (needs `audio_seconds`), `invalid-time`, `position-gap`,
+`position-duplicate`, `line-unparsed`. Edits: `Edit::set_time(line, seconds)`,
+`Edit::shift(seconds)` (all timed lines), `Edit::shift_from(seconds, from)`,
+`Edit::shift_lines(seconds, lines)`, `Edit::sort_by_time()`, `Edit::set_rest(line, rest)`,
+`Edit::insert(after, text)` (`after: 0` inserts at the top), `Edit::delete(line)`. The
+[Tracklist API reference](https://4matic.github.io/trackparse/reference/tracklist/) explains each
+one.
+
+Every line is parsed with `ModeOption::Tracklist`, where the first spaced dash always separates
+artist and title. `parse_with` accepts it too:
+
+```rust
+use trackparse::{parse, parse_with, JunkKind, ModeOption, ParseOptions};
+
+let track = parse("Electrosoul System - Liquid Metal");
+assert_eq!(track.junk[0].raw, "Liquid Metal");
+assert_eq!(track.junk[0].kind, JunkKind::Genre);
+
+let options = ParseOptions::new().mode(ModeOption::Tracklist);
+assert_eq!(parse_with("Electrosoul System - Liquid Metal", &options).title, "Liquid Metal");
+```
+
+## How it is tested
+
+**Docs:** [Testing](https://4matic.github.io/trackparse/project/testing/) · [Ports](https://4matic.github.io/trackparse/project/ports/)
+
+- `cargo test` runs all 13,130 shared fixtures (1,203 written by hand, the rest generated from
+ the rules), the spec's invariants for single tracks and for tracklists on generated input (no
+ panic in any mode, `normalize` idempotent, the format round trip, no word lost, timing), and the
+ API tests. The skip list is empty.
+- `scripts/compare-ports.mjs` in the repository runs every fixture input through the JavaScript
+ package and this crate and compares the complete JSON output, every field of it, not only the
+ ones a fixture asserts. The Python package is checked the same way.
+- The Unicode facts the rules need (letters, uppercase letters, lowercase mapping) are tables
+ generated from the reference implementation and compiled into the crate. The output does not
+ depend on the compiler's Unicode version: Rust 1.74 and current stable give the same bytes.
+ NFC and NFD are the exception, see [Unicode version](#unicode-version).
+- With the `serde` feature, a test asserts that `serde_json::to_string` equals `to_json()` for
+ every fixture input.
+- Clippy denies `unwrap`, `expect`, `panic!` and indexing in the library code, and `unsafe` is
+ forbidden.
+
+## Unicode version
+
+Normalization (NFC in `normalize`, NFD in the key that finds duplicate artists) comes from the
+`unicode-normalization` crate and follows its Unicode version. This crate requires 0.1.26 or
+later, which has the Unicode 18 tables; older releases have older tables and give other results
+for some strings, so Cargo will not select them.
+
+The JavaScript package normalizes with its runtime's tables, which are Unicode 17 on Node 24.
+Unicode 18 added 32 combining marks, so a string that contains one of them can come out with its
+marks in another order here than in JavaScript on that runtime. Strings without those marks are
+not affected, and every shared fixture gives the same bytes.
+
+## Performance
+
+There are no regular expressions and no backtracking: each rule makes a bounded number of passes
+over the string. A 10,000-code-point input parses in a few milliseconds in a release build, and
+the test suite checks that hostile repetitions (thousands of duplicate credits, bracket groups or
+junk phrases) take time roughly in proportion to their length, not to its square.
+
+## Minimum Rust version
+
+Rust 1.74. CI runs the test suite on 1.74 and on stable.
+
+## Development
+
+From `rust/` in the [repository](https://github.com/4matic/trackparse) (Node 24 is needed for the
+codegen script only):
+
+```sh
+node scripts/gen_data.mjs --check # spec/data and Unicode codegen is up to date
+cargo fmt --check
+cargo clippy --all-targets --all-features -- -D warnings
+cargo test # every shared fixture, properties, API
+cargo test --all-features # the same with serde, and this README's examples
+TRACKPARSE_REPORT=1 cargo test --test fixtures -- --nocapture # pass rate per fixture file and per rule
+```
+
+Modules mirror the JS reference one to one (`scanner.rs` is `scanner.ts`, and so on) and cite the
+same spec rule IDs. Behaviour changes start in the spec, not here: see
+[AGENTS.md](https://github.com/4matic/trackparse/blob/main/AGENTS.md).
+
+## Links
+
+- [Documentation](https://4matic.github.io/trackparse/), and a
+ [playground](https://4matic.github.io/trackparse/playground/) that runs the parser in your browser
+- [API documentation on docs.rs](https://docs.rs/trackparse)
+- [Spec](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md)
+- [Project README](https://github.com/4matic/trackparse#readme)
+- [GitHub repository](https://github.com/4matic/trackparse)
+- [npm package](https://www.npmjs.com/package/trackparse) · [PyPI package](https://pypi.org/project/trackparse/)
+
+## License
+
+[MIT](https://github.com/4matic/trackparse/blob/main/LICENSE)
diff --git a/rust/examples/dump.rs b/rust/examples/dump.rs
new file mode 100644
index 0000000..3a535dd
--- /dev/null
+++ b/rust/examples/dump.rs
@@ -0,0 +1,36 @@
+//! The Rust side of the cross-port diff: JSONL in, JSON out.
+//!
+//! Each stdin line is an object `{ "fn", "input", "options", "formatOptions", "edits" }` (as in the
+//! shared fixtures); each stdout line is the JSON result of `trackparse::wire::call`. A line that
+//! is not a JSON object gives `null`.
+//!
+//! ```sh
+//! cargo run --release --example dump < cases.jsonl > results.jsonl
+//! ```
+
+use std::io::{BufRead, BufWriter, Write};
+
+use trackparse::json::Json;
+use trackparse::wire;
+
+fn run(line: &str) -> Json {
+ let Some(case) = Json::parse(line) else { return Json::Null };
+ let func = case.get("fn").and_then(Json::as_str).unwrap_or("parse");
+ let input = case.get("input").and_then(Json::as_str).unwrap_or("");
+ let empty = Json::Obj(Vec::new());
+ let options = case.get("options").unwrap_or(&empty);
+ let format_options = case.get("formatOptions").unwrap_or(&empty);
+ let no_edits = Json::Arr(Vec::new());
+ let edits = case.get("edits").unwrap_or(&no_edits);
+ wire::call(func, input, options, format_options, edits)
+}
+
+fn main() -> std::io::Result<()> {
+ let stdin = std::io::stdin();
+ let mut out = BufWriter::new(std::io::stdout().lock());
+ for line in stdin.lock().lines() {
+ let line = line?;
+ writeln!(out, "{}", run(&line).write())?;
+ }
+ out.flush()
+}
diff --git a/rust/rustfmt.toml b/rust/rustfmt.toml
new file mode 100644
index 0000000..c5e6780
--- /dev/null
+++ b/rust/rustfmt.toml
@@ -0,0 +1,3 @@
+# Same line width as the JS (Biome) and Python (ruff) ports.
+max_width = 100
+use_small_heuristics = "Max"
diff --git a/rust/scripts/dump_primitives.mjs b/rust/scripts/dump_primitives.mjs
new file mode 100644
index 0000000..1ab52f2
--- /dev/null
+++ b/rust/scripts/dump_primitives.mjs
@@ -0,0 +1,171 @@
+#!/usr/bin/env node
+// Expected values for the R0 primitive unit tests (src/words.rs), taken from the JS reference:
+// the functions of js/src/words.ts run on tricky code points and strings.
+//
+// node scripts/dump_primitives.mjs # writes tests/data/primitives.json
+// node scripts/dump_primitives.mjs --check # fails if that file is stale
+// node scripts/dump_primitives.mjs --all out.json
+// every Unicode scalar value and 200,000 random strings around Σ (large; for a one-off
+// sweep, not committed):
+// TRACKPARSE_PRIMITIVES=out.json cargo test --lib primitives
+//
+// Needs Node 24+ (it imports the TypeScript source directly). Regenerate when Node's Unicode
+// version changes, together with src/unicode_tables.rs (scripts/gen_data.mjs).
+import { readFileSync, writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const here = dirname(fileURLToPath(import.meta.url));
+const words = await import(pathToFileURL(join(here, "../../js/src/words.ts")).href);
+const args = process.argv.slice(2);
+const all = args[0] === "--all";
+const check = args[0] === "--check";
+const outFile = all ? args[1] : join(here, "../tests/data/primitives.json");
+
+const isScalar = (cp) => cp < 0xd800 || cp > 0xdfff;
+
+// --- code points -----------------------------------------------------------------------------
+const cps = new Set();
+if (all) {
+ for (let cp = 0; cp <= 0x10ffff; cp++) if (isScalar(cp)) cps.add(cp);
+} else {
+ for (let cp = 0; cp < 0x250; cp++) cps.add(cp);
+ const tricky = [
+ 0x2b0, 0x2c6, 0x300, 0x301, 0x345, 0x36f, 0x370, 0x37a, 0x386, 0x3a3, 0x3c2, 0x3c3, 0x3f4, 0x410, 0x430,
+ 0x5d0, 0x621, 0x640, 0x660, 0x903, 0x904, 0xe01, 0xe31, 0x10a0, 0x10d0, 0x13a0, 0x13f8, 0x1680, 0x167f,
+ 0x1681, 0x16ee, 0x180e, 0x1c80, 0x1c90, 0x1d2c, 0x1e9e, 0x1f88, 0x1fbc, 0x1ffc, 0x1fff, 0x2000, 0x200a,
+ 0x200b, 0x200c, 0x200d, 0x2010, 0x2015, 0x2028, 0x2029, 0x202a, 0x202f, 0x2030, 0x205f, 0x2060, 0x2071,
+ 0x2102, 0x2126, 0x212a, 0x212b, 0x2160, 0x2170, 0x2183, 0x2184, 0x24b6, 0x24d0, 0x2c00, 0x2e2f, 0x3000,
+ 0x3001, 0x3005, 0x3006, 0x3007, 0x3021, 0x3031, 0x3041, 0x30a1, 0x3400, 0x4e00, 0x9fff, 0xa000, 0xa640,
+ 0xa78d, 0xa7f2, 0xab70, 0xac00, 0xd7a3, 0xd7ff, 0xe000, 0xf8ff, 0xf900, 0xfb00, 0xfb01, 0xfb13, 0xfe58,
+ 0xfeff, 0xff08, 0xff21, 0xff41, 0xff70, 0xfffd, 0xffff, 0x10000, 0x10140, 0x10400, 0x10428, 0x104b0,
+ 0x10570, 0x10c80, 0x118a0, 0x16e40, 0x16fe0, 0x1d400, 0x1d41a, 0x1d6a8, 0x1e900, 0x1e922, 0x1f130,
+ 0x1f600, 0x1f1eb, 0x20000, 0x2ffff, 0x30000, 0xe0001, 0xe0100, 0x10fffd, 0x10ffff,
+ ];
+ for (const cp of tricky) cps.add(cp);
+ for (let cp = 0x250; cp <= 0x10ffff; cp += 251) if (isScalar(cp)) cps.add(cp);
+}
+const cpList = [...cps].sort((a, b) => a - b);
+const bits = (test) => cpList.map((cp) => (test(cp) ? "1" : "0")).join("");
+const chr = String.fromCodePoint;
+const codePoints = {
+ // Runs of consecutive code points as [first, count], to keep the file small.
+ runs: (() => {
+ const runs = [];
+ for (const cp of cpList) {
+ const last = runs[runs.length - 1];
+ if (last && last[0] + last[1] === cp) last[1]++;
+ else runs.push([cp, 1]);
+ }
+ return runs;
+ })(),
+ whitespace: bits((cp) => words.isWhitespaceCode(cp)),
+ letter: bits((cp) => words.isLetterAt(chr(cp), 0)),
+ upper: bits((cp) => words.isUpperAt(chr(cp), 0)),
+ jsSpace: bits((cp) => chr(cp).trim() === ""),
+};
+
+// --- strings ---------------------------------------------------------------------------------
+const strings = new Set([
+ "", " ", "Noisia", " The Upbeats ", "FEAT.", "Feat", "ft.", "Remix,", "remix!!", "a.", ".", "..", "É.", "İ.",
+ "İstanbul", "ISTANBUL", "ıstanbul", "İ", "STRAẞE", "Straße", "Dž", "dž", "DŽ", "ᾈ", "ᾀ", "ΟΔΥΣΣΕΑΣ",
+ "Σίσυφος", "ΣΊΣΥΦΟΣ", "Σ", "ΑΣ", "ΑΣ ", "ΑΣΑ", "ΑΣ.", "ΑΣ'", "ΑΣ’Α", "ΑΣ́", "ΆΣ", "ΑΣ", "Σ Σ",
+ "aΣ", "aΣb", "1Σ", ":Σ", "ΑΣ-Β", "Α.Σ", "Α Σ", "ΑΣ", "Beyoncé", "Beyoncé", "BEYONCÉ", "Björk",
+ "Björk", "Tiësto", "TIËSTO", "Sigur Rós", "Mötley Crüe", "Кино", "КИНО", "Ёлка", "ёлка", "Й", "й",
+ "한국어", "각", "각", "が", "が", "full", "A", "final", "ʼn", "ǰ", "ΐ", "ᾳ", "ᾼ", "Å", "Å", "Ω",
+ "Ⅷ", "ⅷ", "Ⓐ", "ⓐ", "𝐀𝐁", "𐐀𐐨", "🎵", "👨👩👧", "🇫🇮", "à́b", "ậ", "ậ", "a̴",
+ "a҃", "a᪰", "a⃝", "aͅ", "é́", "ạ̈", "パ", " x ", "\u0085x\u0085",
+ "x", "x", "x", "
x
", " x ", "\tx\n", "\u000bx\u000c",
+ " x ", " x ", " x", "a b c", "a\u0085b", "ab", "ab",
+ "2015", "2015,", "2015.", "2015..", "1899", "1900", "2099", "2100", "02015", "201", "2015", "2015", "2015a",
+ "١٩٩٩", "feat.", "w/", "b2b", "P!nk", "A$AP", "AC/DC", "x", "X", "&", "?", "??", "ID?", "Ä:", "Z;", "[Z]", "Ź.",
+ "ẞ", "ß", "ſ", "K", "Å", "DŽungla", "ΌΣΟΣ", "ὈΔΥΣΣΕΎΣ", "Ꭰ", "ꭰ", "Ა", "ა", "Ⴀ", "Ɥ", "Ꟶ", "𞤀", "𑢠", "Ꙁ", "Ⱥ",
+ // toLowerCase(): special casing, scripts with late case pairs, and Σ in and out of final position.
+ "İΣ", "Σİ", "İΣİ", "İİ", "i̇Σ", "ẞΣ", "ΣẞΣ", "STRAẞΣ ẞΣ", "ᎠΣ", "ᎠᎡᎢ", "ΣᏴ", "ꭰΣ", "ᏸΣ", "ᲐᲑΣ", "ΣᲐ", "ႠΣ", "აΣ",
+ "𞤀Σ", "𞤀𞤁𞤂", "Σ𞤢", "𞤢Σ", "𞥃Σ𞤀", "ΑΣ𞤀", "ΑΣ ᲐΣ", "DžΣ", "ʰΣ", "ΑʰΣ", "ΑΣʰ", "ΑΣʰΑ", "ᾼΣ", "ΑΣͅ", "ΑΣͅΑ", "ⒶΣ",
+ "ⅧΣ", "ΑΣΣ", "ΣΣ", "ΣΣΣ", "ΑΣΣ.", "ΑΣ·Σ", "ΑΣ·", "ΑΣ:Α", "ΑΣ'Α", "ΑΣ1", "1Σ1", "ΑΣ\u200b", "ΑΣ\u200bΑ", "Α\u00adΣ\u00ad",
+ "𝐀Σ", "Σ𝐀", "ΑΣ🎵", "🎵Σ", "aΣ a", "AΣ", "ÅΣ", "ΌΣ ΌΣΟ", "Ꟑ", "", "", "Ꟗ", "Ꞔ", "", "", "",
+]);
+if (!all) {
+ // Sigma in context: a small alphabet, fixed seed.
+ let seed = 7;
+ const rnd = () => {
+ seed = (seed * 1103515245 + 12345) & 0x7fffffff;
+ return seed / 0x7fffffff;
+ };
+ const alphabet = ["Σ", "Α", "α", " ", "'", ".", "́", "", "a", "1", ":", "-", "", "𝐀", "ͅ"];
+ // A second, later alphabet (the first one's strings stay as they were).
+ const wide = [...alphabet, "Σ", "İ", "ẞ", "Ꭰ", "ꭰ", "Ა", "ა", "𞤀", "𞤢", "ʰ", "·", "Dž", "Ⓐ"];
+ const draw = (letters) => {
+ let s = "";
+ const n = 1 + Math.floor(rnd() * 6);
+ for (let k = 0; k < n; k++) s += letters[Math.floor(rnd() * letters.length)];
+ return s;
+ };
+ for (let i = 0; i < 160; i++) {
+ let s = "";
+ const n = 1 + Math.floor(rnd() * 6);
+ for (let k = 0; k < n; k++) s += alphabet[Math.floor(rnd() * alphabet.length)];
+ strings.add(s);
+ }
+ for (let i = 0; i < 400; i++) strings.add(draw(wide));
+}
+if (all) {
+ // Σ between code points drawn from all cased and case-ignorable ones, and a few others.
+ let seed = 11;
+ const rnd = (n) => {
+ // mulberry32
+ seed = (seed + 0x6d2b79f5) | 0;
+ let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return Math.floor((((t ^ (t >>> 14)) >>> 0) / 4294967296) * n);
+ };
+ const pool = [];
+ for (const cp of cpList) if (/^[\p{Cased}\p{Case_Ignorable}]$/u.test(chr(cp))) pool.push(chr(cp));
+ const plain = ["Σ", "Σ", "Σ", "Α", " ", "1", "-", "İ", "ẞ", "가", "🎵"];
+ for (let i = 0; i < 200000; i++) {
+ let s = "";
+ for (let k = 1 + rnd(6); k > 0; k--) s += rnd(2) ? plain[rnd(plain.length)] : pool[rnd(pool.length)];
+ strings.add(s);
+ }
+}
+const record = (s) => ({
+ s,
+ utf16Len: s.length,
+ asciiLower: words.asciiLower(s),
+ lower: s.toLowerCase(),
+ wordKey: words.wordKey(s),
+ dedupKey: words.dedupKey(s),
+ collapse: words.collapseSpaces(s),
+ words: words.splitWords(s),
+ jsTrim: s.trim(),
+ jsTrimEnd: s.trimEnd(),
+ year: words.yearOf(s),
+});
+
+const lines = [
+ `"unicode": ${JSON.stringify(process.versions.unicode)}`,
+ `"codePoints": ${JSON.stringify(codePoints)}`,
+ `"strings": [\n${[...strings].map((s) => JSON.stringify(record(s))).join(",\n")}\n]`,
+];
+// Every scalar value whose toLowerCase() is not itself; all others must map to themselves.
+const lowerSweep = [];
+for (let cp = 0; cp <= 0x10ffff; cp++) {
+ if (isScalar(cp) && chr(cp).toLowerCase() !== chr(cp)) lowerSweep.push([cp, chr(cp).toLowerCase()]);
+}
+lines.push(`"lowerSweep": ${JSON.stringify(lowerSweep)}`);
+if (all) {
+ // Every scalar value whose dedup key is not itself; all others must map to themselves.
+ const sweep = cpList.filter((cp) => words.dedupKey(chr(cp)) !== chr(cp)).map((cp) => [cp, words.dedupKey(chr(cp))]);
+ lines.push(`"dedupSweep": ${JSON.stringify(sweep)}`);
+}
+const text = `{\n${lines.join(",\n")}\n}\n`;
+if (check) {
+ if (readFileSync(outFile, "utf8") !== text) {
+ console.error("tests/data/primitives.json is stale: run `node scripts/dump_primitives.mjs`");
+ process.exit(1);
+ }
+} else {
+ writeFileSync(outFile, text);
+ console.log(`wrote ${outFile}: ${cpList.length} code points, ${strings.size} strings`);
+}
diff --git a/rust/scripts/gen_data.mjs b/rust/scripts/gen_data.mjs
new file mode 100644
index 0000000..05fda0d
--- /dev/null
+++ b/rust/scripts/gen_data.mjs
@@ -0,0 +1,159 @@
+#!/usr/bin/env node
+// Compiles spec/data/*.json and spec/VERSION into src/data.rs, and the Unicode tables into
+// src/unicode_tables.rs: the categories L and Lu (SPEC R0.6) and the lowercase mapping of
+// `String.prototype.toLowerCase()` with the two properties its final-sigma rule reads (R0.4).
+//
+// node scripts/gen_data.mjs write the files
+// node scripts/gen_data.mjs --check exit 1 if a committed file is stale
+import { readdirSync, readFileSync, writeFileSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const here = dirname(fileURLToPath(import.meta.url));
+const specDir = resolve(here, "../../spec");
+const dataDir = join(specDir, "data");
+
+/** A Rust string literal. */
+function str(s) {
+ let out = '"';
+ for (const ch of s) {
+ const cp = ch.codePointAt(0);
+ if (ch === '"' || ch === "\\") out += `\\${ch}`;
+ else if (cp >= 0x20 && cp < 0x7f) out += ch;
+ else out += `\\u{${cp.toString(16)}}`;
+ }
+ return `${out}"`;
+}
+
+function value(v, indent) {
+ const pad = " ".repeat(indent);
+ if (v === null) return "V::Null";
+ if (typeof v === "boolean") return `V::Bool(${v})`;
+ if (typeof v === "number") return `V::Num(${Number.isInteger(v) ? `${v}.0` : v})`;
+ if (typeof v === "string") return `V::Str(${str(v)})`;
+ if (Array.isArray(v)) {
+ if (v.length === 0) return "V::Arr(&[])";
+ return `V::Arr(&[\n${v.map((x) => `${pad} ${value(x, indent + 1)},\n`).join("")}${pad}])`;
+ }
+ const entries = Object.entries(v).filter(([k]) => k !== "$comment");
+ if (entries.length === 0) return "V::Obj(&[])";
+ return `V::Obj(&[\n${entries.map(([k, x]) => `${pad} (${str(k)}, ${value(x, indent + 1)}),\n`).join("")}${pad}])`;
+}
+
+function renderData() {
+ const version = readFileSync(join(specDir, "VERSION"), "utf8").trim();
+ const lines = [
+ "// GENERATED from spec/data — do not edit. Run `node scripts/gen_data.mjs` to regenerate.",
+ "#![allow(clippy::all)]",
+ "",
+ "use crate::value::V;",
+ "",
+ "/// The version of the spec this crate implements.",
+ `pub const SPEC_VERSION: &str = ${str(version)}; // x-release-please-version`,
+ "",
+ ];
+ for (const file of readdirSync(dataDir).filter((f) => f.endsWith(".json")).sort()) {
+ const name = `${file.slice(0, -5).replace(/-/g, "_").toUpperCase()}_DATA`;
+ lines.push(`/// spec/data/${file}`);
+ lines.push(`pub static ${name}: V = ${value(JSON.parse(readFileSync(join(dataDir, file), "utf8")), 0)};`);
+ lines.push("");
+ }
+ return lines.join("\n");
+}
+
+/** Inclusive code point ranges matching `re`. */
+function ranges(re) {
+ const out = [];
+ let start = -1;
+ for (let cp = 0; cp <= 0x110000; cp++) {
+ const hit = cp < 0x110000 && !(cp >= 0xd800 && cp <= 0xdfff) && re.test(String.fromCodePoint(cp));
+ if (hit && start < 0) start = cp;
+ if (!hit && start >= 0) {
+ out.push([start, cp - 1]);
+ start = -1;
+ }
+ }
+ return out;
+}
+
+/**
+ * `toLowerCase()` of every scalar value that does not map to itself, as two tables: runs of code
+ * points `first, first + step, …, last` that all map to themselves plus `delta`, and the few that
+ * map to several code points. Runs never overlap.
+ */
+function lowercase() {
+ const runs = [];
+ const multi = [];
+ let run = null;
+ for (let cp = 0; cp < 0x110000; cp++) {
+ if (cp >= 0xd800 && cp <= 0xdfff) continue;
+ const lower = [...String.fromCodePoint(cp).toLowerCase()].map((c) => c.codePointAt(0));
+ if (lower.length === 1 && lower[0] === cp) continue;
+ if (lower.length !== 1) {
+ multi.push([cp, lower]);
+ run = null; // a run must not step over a code point of the other table
+ continue;
+ }
+ const delta = lower[0] - cp;
+ if (run && run.delta === delta && (run.step === 0 ? cp - run.last <= 2 : cp - run.last === run.step)) {
+ run.step = cp - run.last;
+ run.last = cp;
+ } else {
+ run = { first: cp, last: cp, step: 0, delta };
+ runs.push(run);
+ }
+ }
+ for (const r of runs) if (r.step === 0) r.step = 1;
+ return { runs, multi };
+}
+
+const UNICODE_HEADER = `// Unicode ${process.versions.unicode}`;
+function renderUnicode() {
+ const table = (name, doc, rs) =>
+ `/// ${doc}\npub static ${name}: &[(u32, u32)] = &[\n${rs.map(([a, b]) => ` (0x${a.toString(16)}, 0x${b.toString(16)}),\n`).join("")}];\n`;
+ const hex = (n) => `0x${n.toString(16)}`;
+ const { runs, multi } = lowercase();
+ return [
+ "// GENERATED — do not edit. Run `node scripts/gen_data.mjs` to regenerate.",
+ "// General category tables for SPEC R0.6, taken from the JS reference engine's \\p{L} and \\p{Lu},",
+ "// and its `toLowerCase()` for the R0.4 dedup key (`str::to_lowercase` follows the compiler's",
+ "// Unicode version, so it cannot be used).",
+ UNICODE_HEADER,
+ "",
+ table("LETTER", "General category L (Lu, Ll, Lt, Lm, Lo), inclusive ranges.", ranges(/^\p{L}$/u)),
+ table("UPPERCASE_LETTER", "General category Lu, inclusive ranges.", ranges(/^\p{Lu}$/u)),
+ table("CASED", "Property Cased (the final-sigma rule), inclusive ranges.", ranges(/^\p{Cased}$/u)),
+ table("CASE_IGNORABLE", "Property Case_Ignorable (the final-sigma rule), inclusive ranges.", ranges(/^\p{Case_Ignorable}$/u)),
+ "/// JS `toLowerCase()` of one code point: `(first, last, step, delta)`. Every code point",
+ "/// `first + k * step <= last` maps to itself plus `delta`. Sorted by `first`, no overlaps.",
+ `pub static LOWERCASE: &[(u32, u32, u8, i32)] = &[\n${runs.map((r) => ` (${hex(r.first)}, ${hex(r.last)}, ${r.step}, ${r.delta}),\n`).join("")}];`,
+ "",
+ "/// Code points whose lowercase is several code points. Sorted.",
+ `pub static LOWERCASE_MULTI: &[(u32, &[u32])] = &[\n${multi.map(([cp, to]) => ` (${hex(cp)}, &[${to.map(hex).join(", ")}]),\n`).join("")}];`,
+ "",
+ ].join("\n");
+}
+
+const check = process.argv.includes("--check");
+let stale = false;
+function emit(file, content, sameHeader) {
+ const path = resolve(here, "../src", file);
+ let current = "";
+ try {
+ current = readFileSync(path, "utf8");
+ } catch {}
+ if (check) {
+ // The Unicode tables depend on the Node version: only compare like with like.
+ if (sameHeader && !current.includes(sameHeader)) return console.log(`${file}: skipped (${sameHeader.slice(3)} here)`);
+ if (current !== content) {
+ console.error(`${file} is stale: run node scripts/gen_data.mjs`);
+ stale = true;
+ }
+ } else if (current !== content) {
+ writeFileSync(path, content);
+ console.log(`wrote ${path}`);
+ }
+}
+emit("data.rs", renderData());
+emit("unicode_tables.rs", renderUnicode(), UNICODE_HEADER);
+if (stale) process.exit(1);
diff --git a/rust/src/artists.rs b/rust/src/artists.rs
new file mode 100644
index 0000000..c2258e0
--- /dev/null
+++ b/rust/src/artists.rs
@@ -0,0 +1,127 @@
+//! R7: the artist side.
+
+use std::collections::HashSet;
+
+use crate::classify::{classify, Classification, Flag, Site};
+use crate::context::Ctx;
+use crate::credits::{split_credits, Credit, ListOptions, PositionedYear};
+use crate::mode::PositionedJunk;
+use crate::scanner::{groups_of, remove_groups, slice_from, slice_skel, trim_skel, Skel, PH};
+use crate::types::{ArtistRole, ArtistSource};
+use crate::words::{at, before, span_texts, string, sub, word_spans};
+
+#[derive(Debug, Default)]
+pub(crate) struct ArtistSideResult {
+ pub credits: Vec,
+ pub junk: Vec,
+ pub years: Vec,
+ pub unknown_artist: bool,
+ /// R7.1: artist-side Flag groups.
+ pub explicit: bool,
+ pub clean: bool,
+}
+
+pub(crate) struct FeatMarker {
+ pub start: usize,
+ pub end: usize,
+ pub marker: String,
+}
+
+/// R7.2: leftmost unbracketed feat marker with a space (or placeholder) left and a space right.
+pub(crate) fn find_feat_marker(s: &Skel, ctx: &Ctx<'_>, from: usize) -> Option {
+ let spans = word_spans(&s.text);
+ let words = span_texts(&spans);
+ for (i, span) in spans.iter().enumerate() {
+ if span.start < from {
+ continue;
+ }
+ if !matches!(before(&s.text, span.start), Some(' ' | PH)) {
+ continue;
+ }
+ let Some(m) = ctx.t.feat_markers.match_at(&words, i) else { continue };
+ let Some(last) = spans.get(i + m.length - 1) else { continue };
+ if at(&s.text, last.end) != Some(' ') {
+ continue;
+ }
+ return Some(FeatMarker {
+ start: span.start,
+ end: last.end,
+ marker: string(sub(&s.text, span.start, last.end)),
+ });
+ }
+ None
+}
+
+/// R7.1–R7.5 over an artist-side skeleton.
+pub(crate) fn parse_artist_side(side: &Skel, ctx: &mut Ctx<'_>) -> ArtistSideResult {
+ let mut result = ArtistSideResult::default();
+ let mut removed: HashSet = HashSet::new();
+
+ // R7.1
+ for (_, group) in groups_of(side) {
+ let site = Site { source: ArtistSource::Artist, delimiter: group.open, pos: group.pos };
+ match classify(&group.inner, site, ctx) {
+ Classification::Feat(c) | Classification::Producer(c) => {
+ result.credits.extend(c.credits);
+ result.years.extend(c.years);
+ if c.unknown {
+ result.unknown_artist = true;
+ }
+ }
+ Classification::Flag(Flag::Explicit) => result.explicit = true,
+ Classification::Flag(Flag::Clean) => result.clean = true,
+ Classification::Year(year) => {
+ result.years.push(PositionedYear { year, pos: group.pos })
+ }
+ Classification::Junk(kind) => {
+ result.junk.push(PositionedJunk { raw: group.inner.clone(), kind, pos: group.pos });
+ }
+ Classification::Versions(_) | Classification::Unknown => continue,
+ }
+ removed.insert(group.pos);
+ }
+ let text = remove_groups(side, &removed);
+
+ // R7.2
+ let feat = find_feat_marker(&text, ctx, 0);
+ let main = match &feat {
+ Some(f) => trim_skel(&slice_skel(&text, 0, f.start)),
+ None => trim_skel(&text),
+ };
+ let main_list = split_credits(
+ &main,
+ &ListOptions {
+ role: ArtistRole::Primary,
+ source: ArtistSource::Artist,
+ lead: None,
+ split_with: true,
+ feat_markers_join: false,
+ },
+ ctx,
+ );
+ result.credits.extend(main_list.credits);
+ result.years.extend(main_list.years);
+ if main_list.unknown {
+ result.unknown_artist = true;
+ }
+ if let Some(f) = feat {
+ let featured = split_credits(
+ &trim_skel(&slice_from(&text, f.end)),
+ &ListOptions {
+ role: ArtistRole::Featured,
+ source: ArtistSource::Artist,
+ lead: Some(f.marker),
+ split_with: false,
+ feat_markers_join: true,
+ },
+ ctx,
+ );
+ result.credits.extend(featured.credits);
+ result.years.extend(featured.years);
+ if featured.unknown {
+ result.unknown_artist = true;
+ }
+ }
+ result.credits.sort_by_key(|c| c.pos); // stable, like the JS sort
+ result
+}
diff --git a/rust/src/assemble.rs b/rust/src/assemble.rs
new file mode 100644
index 0000000..49e66bf
--- /dev/null
+++ b/rust/src/assemble.rs
@@ -0,0 +1,234 @@
+//! R9: assembly and dedup.
+
+use std::collections::{BTreeSet, HashMap};
+
+use crate::classify::VersionDraft;
+use crate::credits::Credit;
+use crate::types::{Artist, ArtistRole, RawVersion, VersionDelimiter};
+use crate::words::dedup_key;
+
+fn precedence(role: ArtistRole) -> u8 {
+ match role {
+ ArtistRole::Primary => 2,
+ ArtistRole::Featured => 1,
+ ArtistRole::Producer | ArtistRole::Remixer => 0,
+ }
+}
+
+pub(crate) fn to_artist(c: Credit) -> Artist {
+ Artist { name: c.name, role: c.role, joiner: c.joiner, source: c.source }
+}
+
+struct Entry {
+ a: Artist,
+ list: usize,
+ alive: bool,
+}
+
+/// The remaining names of each credit list, as ascending entry indexes, so "the list's first
+/// remaining name" and "the next one" are lookups and dedup stays near-linear on inputs with
+/// thousands of duplicate credits.
+struct Lists(HashMap>);
+
+impl Lists {
+ fn new(entries: &[Entry]) -> Lists {
+ let mut lists: HashMap> = HashMap::new();
+ for (i, e) in entries.iter().enumerate() {
+ lists.entry(e.list).or_default().insert(i);
+ }
+ Lists(lists)
+ }
+
+ fn remove(&mut self, list: usize, e: usize) {
+ if let Some(members) = self.0.get_mut(&list) {
+ members.remove(&e);
+ }
+ }
+
+ fn insert(&mut self, list: usize, e: usize) {
+ self.0.entry(list).or_default().insert(e);
+ }
+
+ /// The entry that follows `e` in `list`, if `e` is the list's first remaining name.
+ fn heir(&self, list: usize, e: usize) -> Option {
+ let members = self.0.get(&list)?;
+ if members.first() != Some(&e) {
+ return None;
+ }
+ members.range(e + 1..).next().copied()
+ }
+}
+
+/// R7.6: entry `e` leaves its list. If it was the list's first remaining name, the next
+/// remaining name of that list takes `joiner`.
+fn pass_joiner(entries: &mut [Entry], lists: &Lists, e: usize, joiner: Option) {
+ let Some(list) = entries.get(e).map(|x| x.list) else { return };
+ if let Some(next) = lists.heir(list, e).and_then(|i| entries.get_mut(i)) {
+ next.a.joiner = joiner;
+ }
+}
+
+/// R9.2: keep the first occurrence. A later lower/equal-precedence duplicate is removed (R7.6
+/// joiner inheritance); a later higher-precedence duplicate (role upgrade) gives the kept
+/// entry its role, joiner and source, and the kept entry moves into that occurrence's list.
+pub(crate) fn dedup_artists(credits: Vec) -> Vec {
+ let mut entries: Vec = credits
+ .into_iter()
+ .map(|c| {
+ let list = c.list;
+ Entry { a: to_artist(c), list, alive: true }
+ })
+ .collect();
+ let mut lists = Lists::new(&entries);
+ let mut index: HashMap = HashMap::new();
+ for i in 0..entries.len() {
+ let Some(e) = entries.get(i) else { continue };
+ // R9.2: producers are a separate credit class, deduped only among themselves.
+ let class = if e.a.role == ArtistRole::Producer { "p" } else { "c" };
+ let key = format!("{class}:{}", dedup_key(&e.a.name));
+ let (e_role, e_joiner, e_source, e_list) =
+ (e.a.role, e.a.joiner.clone(), e.a.source, e.list);
+ let Some(&k) = index.get(&key) else {
+ index.insert(key, i);
+ continue;
+ };
+ let Some((kept_role, kept_joiner, kept_list)) =
+ entries.get(k).map(|x| (x.a.role, x.a.joiner.clone(), x.list))
+ else {
+ continue;
+ };
+ if precedence(e_role) > precedence(kept_role) {
+ pass_joiner(&mut entries, &lists, k, kept_joiner);
+ if let Some(kept) = entries.get_mut(k) {
+ kept.a.role = e_role;
+ kept.a.joiner = e_joiner;
+ kept.a.source = e_source;
+ kept.list = e_list;
+ }
+ lists.remove(kept_list, k);
+ lists.insert(e_list, k);
+ } else {
+ pass_joiner(&mut entries, &lists, i, e_joiner);
+ }
+ if let Some(e) = entries.get_mut(i) {
+ e.alive = false;
+ }
+ lists.remove(e_list, i);
+ }
+ entries.into_iter().filter(|e| e.alive).map(|e| e.a).collect()
+}
+
+pub(crate) fn to_version(v: VersionDraft) -> RawVersion {
+ RawVersion {
+ vtype: v.vtype,
+ raw: v.raw,
+ artists: v.artists.into_iter().map(to_artist).collect(),
+ modifiers: v.modifiers,
+ descriptor: v.descriptor,
+ year: v.year,
+ unknown_artist: v.unknown_artist,
+ delimiter: v.delimiter,
+ }
+}
+
+/// R9.4: a version rendered with its delimiter.
+pub(crate) fn render_version(raw: &str, delimiter: VersionDelimiter) -> String {
+ match delimiter {
+ VersionDelimiter::Paren => format!("({raw})"),
+ VersionDelimiter::Square => format!("[{raw}]"),
+ VersionDelimiter::Curly => format!("{{{raw}}}"),
+ VersionDelimiter::Dash => format!("- {raw}"),
+ }
+}
+
+pub(crate) fn full_title_of(title: &str, versions: &[RawVersion]) -> String {
+ std::iter::once(title.to_string())
+ .chain(versions.iter().map(|v| render_version(&v.raw, v.delimiter)))
+ .filter(|s| !s.is_empty())
+ .collect::>()
+ .join(" ")
+}
+
+#[cfg(test)]
+#[allow(clippy::unwrap_used, clippy::indexing_slicing)]
+mod tests {
+ use super::*;
+ use crate::types::ArtistSource;
+
+ /// R9.2 / R7.6 written the plain way: every "first remaining name of the list" is a scan.
+ /// `dedup_artists` must give exactly this.
+ fn reference(credits: Vec) -> Vec {
+ fn pass(entries: &mut [Entry], e: usize, joiner: Option) {
+ let list = entries[e].list;
+ let mut members =
+ entries.iter_mut().enumerate().filter(|(_, x)| x.alive && x.list == list);
+ if members.next().map(|(i, _)| i) != Some(e) {
+ return;
+ }
+ if let Some((_, next)) = members.next() {
+ next.a.joiner = joiner;
+ }
+ }
+ let mut entries: Vec = credits
+ .into_iter()
+ .map(|c| {
+ let list = c.list;
+ Entry { a: to_artist(c), list, alive: true }
+ })
+ .collect();
+ let mut index: HashMap = HashMap::new();
+ for i in 0..entries.len() {
+ let e = &entries[i];
+ let class = if e.a.role == ArtistRole::Producer { "p" } else { "c" };
+ let key = format!("{class}:{}", dedup_key(&e.a.name));
+ let (role, joiner, source, list) = (e.a.role, e.a.joiner.clone(), e.a.source, e.list);
+ let Some(&k) = index.get(&key) else {
+ index.insert(key, i);
+ continue;
+ };
+ if precedence(role) > precedence(entries[k].a.role) {
+ let kept_joiner = entries[k].a.joiner.clone();
+ pass(&mut entries, k, kept_joiner);
+ let kept = &mut entries[k];
+ kept.a.role = role;
+ kept.a.joiner = joiner;
+ kept.a.source = source;
+ kept.list = list;
+ } else {
+ pass(&mut entries, i, joiner);
+ }
+ entries[i].alive = false;
+ }
+ entries.into_iter().filter(|e| e.alive).map(|e| e.a).collect()
+ }
+
+ #[test]
+ fn dedup_matches_the_plain_algorithm() {
+ let mut state = 0x2545_f491_u32;
+ let mut below = |n: u32| {
+ // xorshift32
+ state ^= state << 13;
+ state ^= state >> 17;
+ state ^= state << 5;
+ (state % n) as usize
+ };
+ let roles =
+ [ArtistRole::Primary, ArtistRole::Featured, ArtistRole::Producer, ArtistRole::Remixer];
+ let sources = [ArtistSource::Artist, ArtistSource::Title, ArtistSource::Version];
+ let names = ["a", "A", "b", "c", "é", "d"];
+ for _ in 0..20_000 {
+ let lists = 1 + below(4);
+ let credits: Vec = (0..below(14))
+ .map(|i| Credit {
+ name: names[below(names.len() as u32)].to_string(),
+ role: roles[below(4)],
+ joiner: [None, Some("&".to_string()), Some(format!("j{i}"))][below(3)].clone(),
+ source: sources[below(3)],
+ pos: i as i64,
+ list: below(lists as u32),
+ })
+ .collect();
+ assert_eq!(dedup_artists(credits.clone()), reference(credits.clone()), "{credits:?}");
+ }
+ }
+}
diff --git a/rust/src/classify.rs b/rust/src/classify.rs
new file mode 100644
index 0000000..c57ba75
--- /dev/null
+++ b/rust/src/classify.rs
@@ -0,0 +1,461 @@
+//! R5: classification of a group's inner text (also used for dash suffixes and pipe segments).
+
+use std::collections::HashSet;
+
+use crate::context::Ctx;
+use crate::credits::{split_credits, Credit, ListOptions, ListResult};
+use crate::scanner::scan;
+use crate::tables::{is_unknown_token, RunInfo};
+use crate::types::{ArtistRole, ArtistSource, VersionDelimiter};
+use crate::words::{
+ ascii_lower, at, before, chars, dedup_key, in_vocab, is_all_digits, js_trim, span_texts,
+ split_words, string, sub, tail, utf16_off, word_key, word_spans, year_of, WordSpan,
+};
+
+#[derive(Debug, Clone)]
+pub(crate) struct VersionDraft {
+ /// A version type name; `keywords.versionHeads` values pass through as given.
+ pub vtype: String,
+ pub raw: String,
+ pub artists: Vec,
+ pub modifiers: Vec,
+ pub descriptor: Option,
+ pub year: Option,
+ pub unknown_artist: bool,
+ pub delimiter: VersionDelimiter,
+ pub pos: i64,
+ /// R5.7.2 ambiguousMixCredit; emitted only when the version is used.
+ pub ambiguous_mix: bool,
+ /// Recognised by the R5.7.3 prefix form (R6.2 condition (ii) does not apply).
+ pub prefix_form: bool,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum Flag {
+ Explicit,
+ Clean,
+}
+
+#[derive(Debug, Clone)]
+pub(crate) enum Classification {
+ Junk(String),
+ Feat(ListResult),
+ Producer(ListResult),
+ Flag(Flag),
+ Year(u32),
+ Versions(Vec),
+ Unknown,
+}
+
+/// Where the classified text sits: credits' source, versions' delimiter, absolute offset.
+#[derive(Debug, Clone, Copy)]
+pub(crate) struct Site {
+ pub source: ArtistSource,
+ pub delimiter: VersionDelimiter,
+ pub pos: i64,
+}
+
+const EXPLICIT_FLAGS: [&str; 4] = ["explicit", "explicit version", "dirty", "dirty version"];
+const CLEAN_FLAGS: [&str; 3] = ["clean", "clean version", "radio clean"];
+
+/// R5: classify `inner` (already trimmed and whitespace-collapsed).
+pub(crate) fn classify(inner: &str, site: Site, ctx: &mut Ctx<'_>) -> Classification {
+ let words = split_words(inner);
+ let Some(first) = words.first() else { return Classification::Unknown };
+ if let Some(kind) = junk_kind_of(&words, ctx) {
+ return Classification::Junk(kind);
+ }
+ if let Some(credit) = feat_or_producer(inner, site, ctx) {
+ return credit;
+ }
+ if let Some(flag) = flag_of(&words) {
+ return Classification::Flag(flag);
+ }
+ if words.len() == 1 && is_all_digits(first) {
+ if let Some(year) = year_of(first) {
+ return Classification::Year(year);
+ }
+ }
+ match multi_version(inner, site, ctx).or_else(|| single_version(inner, site, ctx)) {
+ Some(versions) => Classification::Versions(versions),
+ None => Classification::Unknown,
+ }
+}
+
+// ---------------------------------------------------------------------------
+// R5.1 Junk
+
+/// R5.1: the junk kind if the whole word list is junk vocabulary, else `None`.
+pub(crate) fn junk_kind_of(words: &[String], ctx: &Ctx<'_>) -> Option {
+ let t = ctx.t;
+ let mut first_kind: Option<&String> = None;
+ let mut i = 0;
+ while let Some(w) = words.get(i) {
+ if let Some(m) = t.junk_or_genre.match_at(words, i) {
+ first_kind = first_kind.or(Some(m.value));
+ i += m.length;
+ continue;
+ }
+ // R5.1: connectors and year words may sit between junk phrases: `Official Video 2015`.
+ if t.junk_connectors.contains(w.as_str())
+ || t.junk_connectors.contains(word_key(w).as_str())
+ || year_of(w).is_some()
+ {
+ i += 1;
+ continue;
+ }
+ first_kind = None;
+ break;
+ }
+ // JS truthiness: an empty kind (possible through `keywords.junk`) does not count.
+ if let Some(kind) = first_kind.filter(|k| !k.is_empty()) {
+ return Some(kind.clone());
+ }
+ let last = words.last()?;
+ (words.len() >= 2 && in_vocab(last, &t.label_suffixes)).then(|| "label".to_string())
+}
+
+// ---------------------------------------------------------------------------
+// R5.2 Feat, R5.3 Producer
+
+fn feat_or_producer(inner: &str, site: Site, ctx: &mut Ctx<'_>) -> Option {
+ let t = ctx.t;
+ let text = chars(inner);
+ let spans = word_spans(&text);
+ let words = span_texts(&spans);
+ let feat = t.feat_markers.match_at(&words, 0).map(|m| m.length);
+ let bracket_only = if feat.is_some() {
+ None
+ } else {
+ t.bracket_only_feat.match_at(&words, 0).map(|m| m.length)
+ };
+ let feat_len = feat.or(bracket_only).unwrap_or(0);
+ if feat_len > 0 && words.len() > feat_len {
+ let stop = bracket_only.is_some()
+ && words.get(feat_len).is_some_and(|next| in_vocab(next, &t.stopwords));
+ if !stop {
+ let r = credits_after(&text, &spans, feat_len, ArtistRole::Featured, site, ctx);
+ return r.map(Classification::Feat);
+ }
+ }
+ let prod = t.producer_markers.match_at(&words, 0)?;
+ let mut len = prod.length;
+ if words.get(len).is_some_and(|w| word_key(w) == "by") {
+ len += 1;
+ }
+ if words.len() > len {
+ return credits_after(&text, &spans, len, ArtistRole::Producer, site, ctx)
+ .map(Classification::Producer);
+ }
+ None
+}
+
+fn credits_after(
+ inner: &[char],
+ spans: &[WordSpan],
+ marker_words: usize,
+ role: ArtistRole,
+ site: Site,
+ ctx: &mut Ctx<'_>,
+) -> Option {
+ let first = spans.first()?;
+ let last_marker = spans.get(marker_words.checked_sub(1)?)?;
+ let first_name = spans.get(marker_words)?;
+ let lead = string(sub(inner, first.start, last_marker.end));
+ // Offsets are UTF-16 units (see scanner.rs).
+ let base = site.pos + 1 + utf16_off(sub(inner, 0, first_name.start));
+ let opts = ListOptions {
+ role,
+ source: site.source,
+ lead: Some(lead),
+ split_with: false,
+ feat_markers_join: role == ArtistRole::Featured,
+ };
+ Some(list_from_text(tail(inner, first_name.start), base, ctx, &opts))
+}
+
+/// Split a plain string (nested brackets protected by a fresh scan) as a credit list.
+pub(crate) fn list_from_text(
+ text: &[char],
+ base: i64,
+ ctx: &mut Ctx<'_>,
+ opts: &ListOptions,
+) -> ListResult {
+ split_credits(&scan(text, base).0, opts, ctx)
+}
+
+// ---------------------------------------------------------------------------
+// R5.4 Flag
+
+fn flag_of(words: &[String]) -> Option {
+ let key = words.iter().map(|w| word_key(w)).collect::>().join(" ");
+ if EXPLICIT_FLAGS.contains(&key.as_str()) {
+ Some(Flag::Explicit)
+ } else if CLEAN_FLAGS.contains(&key.as_str()) {
+ Some(Flag::Clean)
+ } else {
+ None
+ }
+}
+
+// ---------------------------------------------------------------------------
+// R5.6 Multi-version
+
+/// Split at top-level ` / ` or `; ` (outside nested brackets).
+fn split_multi_parts(inner: &[char]) -> Vec {
+ let mut parts: Vec<&[char]> = Vec::new();
+ let mut depth = 0usize;
+ let mut start = 0usize;
+ for (i, &ch) in inner.iter().enumerate() {
+ if matches!(ch, '(' | '[' | '{') {
+ depth += 1;
+ } else if matches!(ch, ')' | ']' | '}') && depth > 0 {
+ depth -= 1;
+ } else if depth == 0
+ && ch == '/'
+ && before(inner, i) == Some(' ')
+ && at(inner, i + 1) == Some(' ')
+ {
+ parts.push(sub(inner, start, i - 1));
+ start = i + 2;
+ } else if depth == 0 && ch == ';' && at(inner, i + 1) == Some(' ') {
+ parts.push(sub(inner, start, i));
+ start = i + 2;
+ }
+ }
+ parts.push(tail(inner, start));
+ parts.into_iter().map(|p| js_trim(&string(p)).to_string()).collect()
+}
+
+fn multi_version(inner: &str, site: Site, ctx: &mut Ctx<'_>) -> Option> {
+ let parts = split_multi_parts(&chars(inner));
+ if parts.len() < 2 {
+ return None;
+ }
+ let mut out = Vec::new();
+ for part in &parts {
+ if part.is_empty() {
+ return None;
+ }
+ out.extend(single_version(part, site, ctx)?);
+ }
+ Some(out)
+}
+
+// ---------------------------------------------------------------------------
+// R5.7 Version
+
+fn single_version(raw: &str, site: Site, ctx: &mut Ctx<'_>) -> Option> {
+ let text = chars(raw);
+ let spans = word_spans(&text);
+ let words = span_texts(&spans);
+ if let Some(v) = head_by(raw, &text, &spans, &words, site, ctx) {
+ return Some(vec![v]);
+ }
+ if let Some(v) = head_scan(raw, &words, site, ctx) {
+ return Some(vec![v]);
+ }
+ prefix_form(raw, &words, site, ctx).map(|v| vec![v])
+}
+
+fn base_version(raw: &str, vtype: &str, site: Site) -> VersionDraft {
+ VersionDraft {
+ vtype: vtype.to_string(),
+ raw: raw.to_string(),
+ artists: Vec::new(),
+ modifiers: Vec::new(),
+ descriptor: None,
+ year: None,
+ unknown_artist: false,
+ delimiter: site.delimiter,
+ pos: site.pos,
+ ambiguous_mix: false,
+ prefix_form: false,
+ }
+}
+
+fn remixer_opts() -> ListOptions {
+ ListOptions {
+ role: ArtistRole::Remixer,
+ source: ArtistSource::Version,
+ lead: None,
+ split_with: false,
+ feat_markers_join: false,
+ }
+}
+
+/// R9.2: remixers are deduped within their own version only.
+fn dedup_remixers(credits: Vec) -> Vec {
+ let mut seen: HashSet = HashSet::new();
+ credits.into_iter().filter(|c| seen.insert(dedup_key(&c.name))).collect()
+}
+
+fn set_credits(v: &mut VersionDraft, text: &[char], site: Site, ctx: &mut Ctx<'_>) {
+ let r = list_from_text(text, site.pos, ctx, &remixer_opts());
+ v.artists = dedup_remixers(r.credits);
+ if r.unknown {
+ v.unknown_artist = true;
+ }
+ // R7.5: a dropped year-only name sets the version's year if it is still null.
+ if let Some(dropped) = r.years.first() {
+ v.year = v.year.or(Some(dropped.year));
+ }
+}
+
+/// R5.7.1: `Remix by Skrillex`.
+fn head_by(
+ raw: &str,
+ text: &[char],
+ spans: &[WordSpan],
+ words: &[String],
+ site: Site,
+ ctx: &mut Ctx<'_>,
+) -> Option {
+ let t = ctx.t;
+ let head = t.heads.match_at(words, 0)?;
+ let by = words.get(head.length)?;
+ let rest = spans.get(head.length + 1)?;
+ if word_key(by) != "by" {
+ return None;
+ }
+ let mut v = base_version(raw, head.value, site);
+ set_credits(&mut v, tail(text, rest.start), site, ctx);
+ Some(v)
+}
+
+struct RunItem {
+ start: usize,
+ end: usize,
+ info: RunInfo,
+ year: Option,
+}
+
+/// Walk left from `end` collecting the modifier run (R5.7.2).
+fn collect_run(words: &[String], end: usize, ctx: &Ctx<'_>) -> Vec {
+ let mut items: Vec = Vec::new();
+ let mut j = end;
+ while j > 0 {
+ if let Some(m) = ctx.t.run_words.match_ending(words, j) {
+ items.push(RunItem { start: j - m.length, end: j, info: m.value.clone(), year: None });
+ j -= m.length;
+ continue;
+ }
+ let Some(year) = words.get(j - 1).and_then(|w| year_of(w)) else { break };
+ items.push(RunItem { start: j - 1, end: j, info: RunInfo::default(), year: Some(year) });
+ j -= 1;
+ }
+ items.reverse();
+ items
+}
+
+/// R5.7.2: `Extended VIP Mix`, `Skrillex Remix`, `Taylor's Version`.
+fn head_scan(raw: &str, words: &[String], site: Site, ctx: &mut Ctx<'_>) -> Option {
+ let t = ctx.t;
+ let head = t.heads.match_ending(words, words.len())?;
+ let head_type: &str = head.value;
+ let head_start = words.len() - head.length;
+ let run = collect_run(words, head_start, ctx);
+ let credit_end = run.first().map_or(head_start, |r| r.start);
+ let credit_words = words.get(..credit_end).unwrap_or(&[]);
+ let left = run.len().checked_sub(1);
+
+ // R5.7.2 type resolution. Generic = canonical type mix/edit/version, any spelling.
+ let generic = t.generic_head_types.contains(head_type);
+ let mut vtype: String = head_type.to_string();
+ let mut type_item: Option = None;
+ let mut via_mix = false;
+ let nearest_head = if generic { nearest_non_generic_head(&run, ctx) } else { None };
+ // JS truthiness: an empty type name does not count.
+ let truthy = |s: Option<&String>| s.filter(|s| !s.is_empty()).cloned();
+ let left_capable =
+ left.and_then(|i| run.get(i)).and_then(|r| truthy(r.info.type_capable.as_ref()));
+ let nearest_type =
+ nearest_head.and_then(|i| run.get(i)).and_then(|r| truthy(r.info.head.as_ref()));
+ if let (true, Some(capable)) = (generic, left_capable) {
+ vtype = capable;
+ type_item = left;
+ } else if let Some(head) = nearest_type {
+ // `2011 Remastered Version` → remaster
+ vtype = head;
+ type_item = nearest_head;
+ } else if head_type == "mix" && !credit_words.is_empty() {
+ vtype = "remix".to_string();
+ via_mix = true;
+ }
+ let mut v = base_version(raw, &vtype, site);
+
+ let mut descriptors: Vec = Vec::new();
+ for (i, item) in run.iter().enumerate() {
+ if let Some(year) = item.year {
+ v.year = v.year.or(Some(year));
+ continue;
+ }
+ let modifier = item.info.type_capable.as_ref().or(item.info.descriptor.as_ref());
+ if let Some(modifier) = modifier {
+ if Some(i) != type_item && !v.modifiers.contains(modifier) {
+ v.modifiers.push(modifier.clone());
+ }
+ } else if item.info.genre {
+ descriptors.push(words.get(item.start..item.end).unwrap_or(&[]).join(" "));
+ }
+ }
+
+ if let Some(last_credit_word) = credit_words.last() {
+ let credit = credit_words.join(" ");
+ let last_word = ascii_lower(last_credit_word);
+ if is_unknown_token(&credit, t) {
+ v.unknown_artist = true;
+ } else if vtype == "version" || vtype == "cover" || is_all_junk_phrases(credit_words, ctx) {
+ // R5.7.2: `Japanese Version`, `Taylor's Version`, `Adele Cover`, `Video Edit`.
+ descriptors.insert(0, credit);
+ } else {
+ let mut name = chars(&credit);
+ if last_word.ends_with("'s") {
+ name.truncate(name.len().saturating_sub(2));
+ }
+ set_credits(&mut v, &name, site, ctx);
+ if via_mix && v.artists.last().is_some_and(|a| split_words(&a.name).len() >= 3) {
+ v.ambiguous_mix = true;
+ }
+ }
+ }
+ v.descriptor = if descriptors.is_empty() { None } else { Some(descriptors.join(" ")) };
+ Some(v)
+}
+
+/// R5.7.2 type rule 2: the non-generic head in the run nearest the (generic) head.
+fn nearest_non_generic_head(run: &[RunItem], ctx: &Ctx<'_>) -> Option {
+ (0..run.len()).rev().find(|&i| {
+ run.get(i)
+ .and_then(|r| r.info.head.as_ref())
+ .is_some_and(|head| !ctx.t.generic_head_types.contains(head.as_str()))
+ })
+}
+
+/// R5.7.2: the credit span is made entirely of junk phrases (`Video` in `Video Edit`).
+fn is_all_junk_phrases(words: &[String], ctx: &Ctx<'_>) -> bool {
+ let mut i = 0;
+ while i < words.len() {
+ match ctx.t.junk_phrases.match_at(words, i) {
+ Some(m) => i += m.length,
+ None => return false,
+ }
+ }
+ !words.is_empty()
+}
+
+/// R5.7.3: `Live at Wembley 1986`, `Remastered 2015`, `Sped Up`.
+fn prefix_form(raw: &str, words: &[String], site: Site, ctx: &Ctx<'_>) -> Option {
+ let m = ctx.t.prefix_forms.match_at(words, 0)?;
+ let mut v = base_version(raw, m.value, site);
+ v.prefix_form = true;
+ let mut rest: Vec<&str> = Vec::new();
+ for w in words.get(m.length..).unwrap_or(&[]) {
+ match if v.year.is_none() { year_of(w) } else { None } {
+ Some(year) => v.year = Some(year),
+ None => rest.push(w),
+ }
+ }
+ v.descriptor = if rest.is_empty() { None } else { Some(rest.join(" ")) };
+ Some(v)
+}
diff --git a/rust/src/context.rs b/rust/src/context.rs
new file mode 100644
index 0000000..665eba6
--- /dev/null
+++ b/rust/src/context.rs
@@ -0,0 +1,77 @@
+//! Per-call parse context: resolved options + vocabulary tables.
+
+use std::collections::HashSet;
+
+use crate::options::SplitAndMode;
+use crate::tables::Tables;
+use crate::types::Warning;
+use crate::words::{at, dedup_key, is_whitespace, string, sub};
+
+pub(crate) struct Ctx<'a> {
+ pub t: &'a Tables,
+ pub known_keys: &'a HashSet,
+ /// Longest knownArtists entry, in UTF-16 units (bounds the R7.3a search).
+ pub known_max_len: usize,
+ pub split_and: SplitAndMode,
+ pub warnings: Vec,
+ /// Counter giving every split credit list an id (R7.6 joiner inheritance across R9.2).
+ pub list_seq: usize,
+}
+
+/// The `knownArtists` part of a context, computed once per parser.
+pub(crate) fn known_keys(known: &[String]) -> (HashSet, usize) {
+ let keys = known.iter().map(|k| dedup_key(k)).filter(|k| !k.is_empty()).collect();
+ let max_len = known.iter().map(|k| k.encode_utf16().count()).max().unwrap_or(0);
+ (keys, max_len)
+}
+
+pub(crate) fn warn(ctx: &mut Ctx<'_>, w: Warning) {
+ if !ctx.warnings.contains(&w) {
+ ctx.warnings.push(w);
+ }
+}
+
+/// R7.3a: length of the longest knownArtists entry matching `text` at `start` (dedup-key
+/// comparison), followed by end, whitespace, `,` or `;` (or `extra_boundary`: R4.2 also accepts
+/// `-`, so `3 Doors Down-Kryptonite` is protected). 0 when none matches.
+///
+/// The search window is `2 * longest + 8` UTF-16 units, exactly as in the JS reference.
+pub(crate) fn match_known_at(
+ text: &[char],
+ start: usize,
+ ctx: &Ctx<'_>,
+ extra_boundary: Option,
+) -> usize {
+ if ctx.known_keys.is_empty() {
+ return 0;
+ }
+ let budget = ctx.known_max_len.saturating_mul(2).saturating_add(8);
+ let mut limit = start;
+ let mut used = 0usize;
+ while let Some(ch) = at(text, limit) {
+ let w = ch.len_utf16();
+ if used + w > budget {
+ break;
+ }
+ used += w;
+ limit += 1;
+ }
+ let mut end = limit;
+ while end > start {
+ let next = at(text, end);
+ let boundary = end == text.len()
+ || next == Some(',')
+ || next == Some(';')
+ || is_whitespace(next)
+ || (extra_boundary.is_some() && next == extra_boundary);
+ if boundary && ctx.known_keys.contains(&dedup_key(&string(sub(text, start, end)))) {
+ return end - start;
+ }
+ end -= 1;
+ }
+ 0
+}
+
+pub(crate) fn is_known_artist(text: &str, ctx: &Ctx<'_>) -> bool {
+ !ctx.known_keys.is_empty() && ctx.known_keys.contains(&dedup_key(text))
+}
diff --git a/rust/src/credits.rs b/rust/src/credits.rs
new file mode 100644
index 0000000..2e74952
--- /dev/null
+++ b/rust/src/credits.rs
@@ -0,0 +1,260 @@
+//! R7.3–R7.5: splitting a credit list into names.
+
+use crate::context::{match_known_at, Ctx};
+use crate::options::SplitAndMode;
+use crate::scanner::{render_skel, slice_skel, trim_skel, Skel};
+use crate::tables::is_unknown_token;
+use crate::types::{ArtistRole, ArtistSource};
+use crate::words::{
+ at, before, chars, collapse_chars, collapse_spaces, in_vocab, is_all_digits, is_digit,
+ is_whitespace, js_trim_end, string, sub, tail, word_key, word_matches, year_of,
+};
+
+/// An artist credit plus its absolute offset, used for ordering (R9.1).
+#[derive(Debug, Clone)]
+pub(crate) struct Credit {
+ pub name: String,
+ pub role: ArtistRole,
+ pub joiner: Option,
+ pub source: ArtistSource,
+ pub pos: i64,
+ /// Id of the credit list it came from (R7.6 joiner inheritance in R9.2).
+ pub list: usize,
+}
+
+/// A year with its absolute offset (R9.6: the track year is the first in text order).
+#[derive(Debug, Clone, Copy)]
+pub(crate) struct PositionedYear {
+ pub year: u32,
+ pub pos: i64,
+}
+
+#[derive(Debug, Clone)]
+pub(crate) struct ListOptions {
+ pub role: ArtistRole,
+ pub source: ArtistSource,
+ /// Joiner of the first name: `None`, or the feat / producer marker as written.
+ pub lead: Option,
+ /// R7.3: `with` splits only in the main list of the artist side.
+ pub split_with: bool,
+ /// R7.2: later feat markers act as joiners inside a featured list.
+ pub feat_markers_join: bool,
+}
+
+#[derive(Debug, Clone, Default)]
+pub(crate) struct ListResult {
+ pub credits: Vec,
+ /// R7.5: an unknown token was dropped.
+ pub unknown: bool,
+ /// R7.5: dropped year-only names.
+ pub years: Vec,
+}
+
+struct JoinerHit {
+ start: usize,
+ end: usize,
+ raw: String,
+}
+
+const AND_LIKE: [&str; 3] = ["&", "and", "+"];
+
+fn word_at(text: &[char], start: usize) -> usize {
+ let mut end = start;
+ while end < text.len() && !is_whitespace(at(text, end)) {
+ end += 1;
+ }
+ end
+}
+
+/// The word after a joiner; a tight joiner (`,` `;`) ends it, since the name ends there.
+fn next_word(text: &[char], from: usize) -> String {
+ let mut a = from;
+ while a < text.len() && is_whitespace(at(text, a)) {
+ a += 1;
+ }
+ let mut b = a;
+ while b < text.len() && !is_whitespace(at(text, b)) && !matches!(at(text, b), Some(',' | ';')) {
+ b += 1;
+ }
+ string(sub(text, a, b))
+}
+
+/// R7.3b: the leftmost joiner occurrence at or after `from`, honouring the guards.
+fn find_joiner(
+ text: &[char],
+ from: usize,
+ split_at_comma: bool,
+ opts: &ListOptions,
+ ctx: &Ctx<'_>,
+) -> Option {
+ let mut p = from;
+ while let Some(ch) = at(text, p) {
+ if ch == ',' || ch == ';' {
+ if ch == ',' && is_digit(before(text, p)) && is_digit(at(text, p + 1)) {
+ p += 1;
+ continue; // `1,000`
+ }
+ return Some(JoinerHit { start: p, end: p + 1, raw: ch.to_string() });
+ }
+ if p == 0 || before(text, p) != Some(' ') || is_whitespace(Some(ch)) {
+ p += 1;
+ continue;
+ }
+ let end = word_at(text, p);
+ if end >= text.len() || at(text, end) != Some(' ') {
+ p += 1;
+ continue; // spaced joiners need a space after
+ }
+ let word = string(sub(text, p, end));
+ if spaced_joiner(&word, text, end, split_at_comma, opts, ctx) {
+ return Some(JoinerHit { start: p, end, raw: word });
+ }
+ p += 1;
+ }
+ None
+}
+
+fn spaced_joiner(
+ word: &str,
+ text: &[char],
+ end: usize,
+ split_at_comma: bool,
+ opts: &ListOptions,
+ ctx: &Ctx<'_>,
+) -> bool {
+ if opts.feat_markers_join && ctx.t.feat_markers.match_at(&[word], 0).is_some() {
+ return true;
+ }
+ for j in &ctx.t.spaced_joiners {
+ let matches = if j.case_sensitive { word == j.raw } else { word_matches(word, j.raw) };
+ if !matches {
+ continue;
+ }
+ if j.raw == "with" && !opts.split_with {
+ return false;
+ }
+ if j.is_and {
+ if ctx.split_and == SplitAndMode::Never {
+ return false;
+ }
+ if ctx.split_and == SplitAndMode::Auto && !split_at_comma {
+ return false;
+ }
+ }
+ if AND_LIKE.contains(&j.raw) && in_vocab(&next_word(text, end), &ctx.t.no_split_before) {
+ return false;
+ }
+ return true;
+ }
+ false
+}
+
+/// R7.4: clean one raw name.
+pub(crate) fn clean_name(raw: &str) -> String {
+ let mut name = chars(&collapse_spaces(raw));
+ if let (Some(&first), Some(&last)) = (name.first(), name.last()) {
+ if name.len() >= 2 && (first == '"' || first == '\'') && last == first {
+ name = chars(&collapse_chars(sub(&name, 1, name.len() - 1)));
+ }
+ }
+ let mut name: String = string(&name);
+ while name.ends_with(',') || name.ends_with(';') {
+ name.pop();
+ name.truncate(js_trim_end(&name).len());
+ }
+ if let Some(space) = name.find(' ') {
+ let head = name.get(..space).unwrap_or("");
+ if space > 0 && word_key(head) == "by" {
+ name = name.get(space + 1..).unwrap_or("").to_string();
+ }
+ }
+ collapse_spaces(&name)
+}
+
+struct RawName {
+ name: String,
+ joiner: Option,
+ pos: i64,
+}
+
+/// R7.4: strip one pair of wrapping quotes from the whole list (no other such quote inside).
+fn unwrap_list(list: &Skel) -> Skel {
+ let t = trim_skel(list);
+ let n = t.text.len();
+ let Some(q) = at(&t.text, 0) else { return t };
+ if n < 2 || (q != '"' && q != '\'') || at(&t.text, n - 1) != Some(q) {
+ return t;
+ }
+ // `indexOf(q, 1)`: the next such quote must be the last character.
+ let next = tail(&t.text, 1).iter().position(|&c| c == q).map(|i| i + 1);
+ if next != Some(n - 1) {
+ return t;
+ }
+ trim_skel(&slice_skel(&t, 1, n - 1))
+}
+
+/// R7.3: split `input` into credits.
+pub(crate) fn split_credits(input: &Skel, opts: &ListOptions, ctx: &mut Ctx<'_>) -> ListResult {
+ let list = unwrap_list(input); // R7.4: `"Camo & Krooked"`
+ let text = &list.text;
+ let mut raw: Vec = Vec::new();
+ let mut joiner: Option = opts.lead.clone();
+ let mut split_at_comma = false;
+ let mut start = 0usize;
+ while start <= text.len() {
+ while start < text.len() && is_whitespace(at(text, start)) {
+ start += 1;
+ }
+ let known = match_known_at(text, start, ctx, Some('-')); // R7.3a
+ let hit = find_joiner(text, start + known, split_at_comma, opts, ctx);
+ let end = hit.as_ref().map_or(text.len(), |h| h.start);
+ raw.push(RawName {
+ name: clean_name(&render_skel(&slice_skel(&list, start, end))),
+ joiner: joiner.take(),
+ pos: list.pos.get(start).or(list.pos.last()).copied().unwrap_or(0),
+ });
+ let Some(hit) = hit else { break };
+ if hit.raw == "," || hit.raw == ";" {
+ split_at_comma = true; // R7.3: `and` after a tight joiner
+ }
+ start = hit.end;
+ joiner = Some(hit.raw);
+ }
+ finish_names(raw, opts, ctx)
+}
+
+/// R7.4 empty drops, R7.5 year/unknown drops. R7.6: the first survivor takes the lead joiner
+/// (`None`, or the feat/producer marker).
+fn finish_names(raw: Vec, opts: &ListOptions, ctx: &mut Ctx<'_>) -> ListResult {
+ let named: Vec = raw.into_iter().filter(|r| !r.name.is_empty()).collect();
+ let count = named.len();
+ let mut unknown = false;
+ let mut years: Vec = Vec::new();
+ let mut kept: Vec = Vec::new();
+ for r in named {
+ if is_unknown_token(&r.name, ctx.t) {
+ unknown = true;
+ continue;
+ }
+ let year = if is_all_digits(&r.name) { year_of(&r.name) } else { None };
+ match year {
+ Some(year) if count > 1 => years.push(PositionedYear { year, pos: r.pos }),
+ _ => kept.push(r),
+ }
+ }
+ let list = ctx.list_seq;
+ ctx.list_seq += 1;
+ let credits = kept
+ .into_iter()
+ .enumerate()
+ .map(|(i, r)| Credit {
+ name: r.name,
+ role: opts.role,
+ joiner: if i == 0 { opts.lead.clone() } else { r.joiner },
+ source: opts.source,
+ pos: r.pos,
+ list,
+ })
+ .collect();
+ ListResult { credits, unknown, years }
+}
diff --git a/rust/src/data.rs b/rust/src/data.rs
new file mode 100644
index 0000000..274fadf
--- /dev/null
+++ b/rust/src/data.rs
@@ -0,0 +1,563 @@
+// GENERATED from spec/data — do not edit. Run `node scripts/gen_data.mjs` to regenerate.
+#![allow(clippy::all)]
+
+use crate::value::V;
+
+/// The version of the spec this crate implements.
+pub const SPEC_VERSION: &str = "0.4.0"; // x-release-please-version
+
+/// spec/data/descriptors.json
+pub static DESCRIPTORS_DATA: V = V::Obj(&[
+ ("descriptors", V::Arr(&[
+ V::Str("radio"),
+ V::Str("extended"),
+ V::Str("club"),
+ V::Str("original"),
+ V::Str("instrumental"),
+ V::Str("dub"),
+ V::Str("vip"),
+ V::Str("acoustic"),
+ V::Str("live"),
+ V::Str("demo"),
+ V::Str("vocal"),
+ V::Str("clean"),
+ V::Str("dirty"),
+ V::Str("explicit"),
+ V::Str("short"),
+ V::Str("long"),
+ V::Str("full"),
+ V::Str("album"),
+ V::Str("single"),
+ V::Str("alternate"),
+ V::Str("alt"),
+ V::Str("alternative"),
+ V::Str("main"),
+ V::Str("special"),
+ V::Str("bonus"),
+ V::Str("deluxe"),
+ V::Str("mono"),
+ V::Str("stereo"),
+ V::Str("new"),
+ V::Str("official"),
+ V::Str("orchestral"),
+ V::Str("piano"),
+ V::Str("unplugged"),
+ V::Str("12\""),
+ V::Str("7\""),
+ V::Str("12''"),
+ V::Str("7''"),
+ V::Str("12 inch"),
+ V::Str("7 inch"),
+ V::Str("re"),
+ V::Str("final"),
+ V::Str("second"),
+ V::Str("2nd"),
+ V::Str("3rd"),
+ ])),
+]);
+
+/// spec/data/extensions.json
+pub static EXTENSIONS_DATA: V = V::Obj(&[
+ ("extensions", V::Arr(&[
+ V::Str("mp3"),
+ V::Str("flac"),
+ V::Str("wav"),
+ V::Str("m4a"),
+ V::Str("ogg"),
+ V::Str("opus"),
+ V::Str("aac"),
+ V::Str("aiff"),
+ V::Str("aif"),
+ V::Str("wma"),
+ V::Str("alac"),
+ V::Str("mp4"),
+ V::Str("webm"),
+ V::Str("mkv"),
+ ])),
+]);
+
+/// spec/data/feat-markers.json
+pub static FEAT_MARKERS_DATA: V = V::Obj(&[
+ ("markers", V::Arr(&[
+ V::Str("feat."),
+ V::Str("feat"),
+ V::Str("ft."),
+ V::Str("ft"),
+ V::Str("featuring"),
+ V::Str("feat:"),
+ V::Str("ft:"),
+ ])),
+ ("bracketOnly", V::Arr(&[
+ V::Str("with"),
+ V::Str("w/"),
+ ])),
+ ("producer", V::Arr(&[
+ V::Str("prod."),
+ V::Str("prod"),
+ V::Str("produced"),
+ V::Str("prod.by"),
+ V::Str("prod:"),
+ ])),
+ ("titleMarkers", V::Arr(&[
+ V::Str("feat."),
+ V::Str("ft."),
+ V::Str("featuring"),
+ ])),
+ ("titleProducer", V::Arr(&[
+ V::Str("prod."),
+ V::Str("prod. by"),
+ V::Str("produced by"),
+ V::Str("prod.by"),
+ ])),
+ ("producerBy", V::Str("by")),
+]);
+
+/// spec/data/genres.json
+pub static GENRES_DATA: V = V::Obj(&[
+ ("genres", V::Arr(&[
+ V::Str("d'n'b"),
+ V::Str("dnb"),
+ V::Str("d&b"),
+ V::Str("d & b"),
+ V::Str("drum & bass"),
+ V::Str("drum&bass"),
+ V::Str("drum and bass"),
+ V::Str("drum n bass"),
+ V::Str("drum 'n' bass"),
+ V::Str("drum'n'bass"),
+ V::Str("neurofunk"),
+ V::Str("neuro"),
+ V::Str("liquid"),
+ V::Str("liquid funk"),
+ V::Str("jump up"),
+ V::Str("jump-up"),
+ V::Str("jungle"),
+ V::Str("halftime"),
+ V::Str("dancefloor"),
+ V::Str("dubstep"),
+ V::Str("riddim"),
+ V::Str("brostep"),
+ V::Str("trap"),
+ V::Str("future bass"),
+ V::Str("house"),
+ V::Str("deep house"),
+ V::Str("tech house"),
+ V::Str("progressive house"),
+ V::Str("electro house"),
+ V::Str("techno"),
+ V::Str("trance"),
+ V::Str("psytrance"),
+ V::Str("psy"),
+ V::Str("hardstyle"),
+ V::Str("hardcore"),
+ V::Str("breaks"),
+ V::Str("breakbeat"),
+ V::Str("garage"),
+ V::Str("uk garage"),
+ V::Str("ukg"),
+ V::Str("2step"),
+ V::Str("2-step"),
+ V::Str("grime"),
+ V::Str("bass"),
+ V::Str("bass house"),
+ V::Str("edm"),
+ V::Str("electronic"),
+ V::Str("idm"),
+ V::Str("synthwave"),
+ V::Str("phonk"),
+ V::Str("hip hop"),
+ V::Str("hip-hop"),
+ V::Str("rap"),
+ V::Str("pop"),
+ V::Str("rock"),
+ V::Str("metal"),
+ V::Str("ambient"),
+ V::Str("chillout"),
+ V::Str("lofi"),
+ V::Str("lo-fi"),
+ ])),
+]);
+
+/// spec/data/header-words.json
+pub static HEADER_WORDS_DATA: V = V::Obj(&[
+ ("words", V::Arr(&[
+ V::Str("tracklist"),
+ V::Str("setlist"),
+ V::Str("playlist"),
+ V::Str("part"),
+ V::Str("hour"),
+ V::Str("cd"),
+ V::Str("disc"),
+ V::Str("side"),
+ V::Str("chapter"),
+ V::Str("segment"),
+ V::Str("set"),
+ ])),
+]);
+
+/// spec/data/joiners.json
+pub static JOINERS_DATA: V = V::Obj(&[
+ ("spaced", V::Arr(&[
+ V::Obj(&[
+ ("raw", V::Str("&")),
+ ("canonical", V::Str("&")),
+ ]),
+ V::Obj(&[
+ ("raw", V::Str("and")),
+ ("canonical", V::Str("&")),
+ ("kind", V::Str("and")),
+ ]),
+ V::Obj(&[
+ ("raw", V::Str("x")),
+ ("canonical", V::Str("x")),
+ ("caseSensitive", V::Bool(true)),
+ ]),
+ V::Obj(&[
+ ("raw", V::Str("\u{d7}")),
+ ("canonical", V::Str("x")),
+ ]),
+ V::Obj(&[
+ ("raw", V::Str("vs.")),
+ ("canonical", V::Str("vs.")),
+ ]),
+ V::Obj(&[
+ ("raw", V::Str("vs")),
+ ("canonical", V::Str("vs.")),
+ ]),
+ V::Obj(&[
+ ("raw", V::Str("versus")),
+ ("canonical", V::Str("vs.")),
+ ]),
+ V::Obj(&[
+ ("raw", V::Str("/")),
+ ("canonical", V::Str("/")),
+ ]),
+ V::Obj(&[
+ ("raw", V::Str("+")),
+ ("canonical", V::Str("+")),
+ ]),
+ V::Obj(&[
+ ("raw", V::Str("with")),
+ ("canonical", V::Str("with")),
+ ]),
+ V::Obj(&[
+ ("raw", V::Str("meets")),
+ ("canonical", V::Str("meets")),
+ ]),
+ V::Obj(&[
+ ("raw", V::Str("pres.")),
+ ("canonical", V::Str("pres.")),
+ ]),
+ V::Obj(&[
+ ("raw", V::Str("presents")),
+ ("canonical", V::Str("pres.")),
+ ]),
+ V::Obj(&[
+ ("raw", V::Str("b2b")),
+ ("canonical", V::Str("b2b")),
+ ]),
+ ])),
+ ("tight", V::Arr(&[
+ V::Obj(&[
+ ("raw", V::Str(",")),
+ ("canonical", V::Str(",")),
+ ]),
+ V::Obj(&[
+ ("raw", V::Str(";")),
+ ("canonical", V::Str(",")),
+ ]),
+ ])),
+ ("featCanonical", V::Str("feat.")),
+]);
+
+/// spec/data/junk.json
+pub static JUNK_DATA: V = V::Obj(&[
+ ("phrases", V::Obj(&[
+ ("official video", V::Str("video")),
+ ("official music video", V::Str("video")),
+ ("music video", V::Str("video")),
+ ("official video clip", V::Str("video")),
+ ("video clip", V::Str("video")),
+ ("official clip", V::Str("video")),
+ ("clip officiel", V::Str("video")),
+ ("official hd video", V::Str("video")),
+ ("official 4k video", V::Str("video")),
+ ("official mv", V::Str("video")),
+ ("mv", V::Str("video")),
+ ("m/v", V::Str("video")),
+ ("video", V::Str("video")),
+ ("official visualizer", V::Str("video")),
+ ("official visualiser", V::Str("video")),
+ ("visualizer", V::Str("video")),
+ ("visualiser", V::Str("video")),
+ ("audio visualizer", V::Str("video")),
+ ("official animated video", V::Str("video")),
+ ("animated video", V::Str("video")),
+ ("live video", V::Str("video")),
+ ("official live video", V::Str("video")),
+ ("performance video", V::Str("video")),
+ ("official performance video", V::Str("video")),
+ ("official audio", V::Str("audio")),
+ ("audio", V::Str("audio")),
+ ("audio only", V::Str("audio")),
+ ("full audio", V::Str("audio")),
+ ("official lyric video", V::Str("lyrics")),
+ ("official lyrics video", V::Str("lyrics")),
+ ("lyric video", V::Str("lyrics")),
+ ("lyrics video", V::Str("lyrics")),
+ ("lyrics", V::Str("lyrics")),
+ ("lyric", V::Str("lyrics")),
+ ("with lyrics", V::Str("lyrics")),
+ ("lyrics on screen", V::Str("lyrics")),
+ ("letra", V::Str("lyrics")),
+ ("hd", V::Str("quality")),
+ ("hq", V::Str("quality")),
+ ("uhd", V::Str("quality")),
+ ("4k", V::Str("quality")),
+ ("8k", V::Str("quality")),
+ ("1080p", V::Str("quality")),
+ ("720p", V::Str("quality")),
+ ("480p", V::Str("quality")),
+ ("high quality", V::Str("quality")),
+ ("full hd", V::Str("quality")),
+ ("free download", V::Str("promo")),
+ ("free dl", V::Str("promo")),
+ ("out now", V::Str("promo")),
+ ("premiere", V::Str("promo")),
+ ("exclusive", V::Str("promo")),
+ ("preview", V::Str("promo")),
+ ("teaser", V::Str("promo")),
+ ("snippet", V::Str("promo")),
+ ("new song", V::Str("promo")),
+ ("available now", V::Str("promo")),
+ ("ncs release", V::Str("label")),
+ ("monstercat release", V::Str("label")),
+ ("official", V::Str("other")),
+ ])),
+ ("connectors", V::Arr(&[
+ V::Str("-"),
+ V::Str("|"),
+ V::Str("/"),
+ V::Str("&"),
+ V::Str("+"),
+ V::Str(","),
+ ])),
+ ("labelSuffixes", V::Arr(&[
+ V::Str("release"),
+ V::Str("records"),
+ V::Str("recordings"),
+ ])),
+]);
+
+/// spec/data/layered-words.json
+pub static LAYERED_WORDS_DATA: V = V::Obj(&[
+ ("words", V::Arr(&[
+ V::Str("w/"),
+ ])),
+]);
+
+/// spec/data/marker-words.json
+pub static MARKER_WORDS_DATA: V = V::Obj(&[
+ ("words", V::Arr(&[
+ V::Str("intro"),
+ V::Str("outro"),
+ V::Str("break"),
+ V::Str("interlude"),
+ V::Str("intermission"),
+ V::Str("jingle"),
+ V::Str("ad"),
+ V::Str("advert"),
+ V::Str("advertisement"),
+ V::Str("talk"),
+ V::Str("interview"),
+ V::Str("speech"),
+ V::Str("announcement"),
+ V::Str("shoutout"),
+ V::Str("shout-out"),
+ V::Str("pause"),
+ V::Str("start"),
+ V::Str("end"),
+ V::Str("silence"),
+ V::Str("applause"),
+ V::Str("skit"),
+ ])),
+]);
+
+/// spec/data/no-split-before.json
+pub static NO_SPLIT_BEFORE_DATA: V = V::Obj(&[
+ ("words", V::Arr(&[
+ V::Str("sons"),
+ V::Str("daughters"),
+ V::Str("friends"),
+ V::Str("co"),
+ V::Str("co."),
+ V::Str("company"),
+ V::Str("his"),
+ V::Str("her"),
+ V::Str("their"),
+ V::Str("orchestra"),
+ ])),
+]);
+
+/// spec/data/platform-suffixes.json
+pub static PLATFORM_SUFFIXES_DATA: V = V::Obj(&[
+ ("suffixes", V::Arr(&[
+ V::Str(" - YouTube Music"),
+ V::Str(" - YouTube"),
+ V::Str(" | Free Listening on SoundCloud"),
+ V::Str(" - SoundCloud"),
+ V::Str(" | SoundCloud"),
+ V::Str(" - Topic"),
+ V::Str(" | Bandcamp"),
+ V::Str(" - Bandcamp"),
+ ])),
+]);
+
+/// spec/data/stopwords.json
+pub static STOPWORDS_DATA: V = V::Obj(&[
+ ("words", V::Arr(&[
+ V::Str("you"),
+ V::Str("me"),
+ V::Str("him"),
+ V::Str("her"),
+ V::Str("us"),
+ V::Str("them"),
+ V::Str("it"),
+ V::Str("i"),
+ V::Str("love"),
+ V::Str("my"),
+ V::Str("your"),
+ V::Str("our"),
+ V::Str("the"),
+ V::Str("a"),
+ V::Str("an"),
+ V::Str("this"),
+ V::Str("that"),
+ V::Str("myself"),
+ V::Str("yourself"),
+ V::Str("everyone"),
+ V::Str("everybody"),
+ V::Str("somebody"),
+ V::Str("someone"),
+ V::Str("nobody"),
+ V::Str("nothing"),
+ V::Str("all"),
+ V::Str("night"),
+ V::Str("side"),
+ V::Str("day"),
+ ])),
+]);
+
+/// spec/data/unknown-tokens.json
+pub static UNKNOWN_TOKENS_DATA: V = V::Obj(&[
+ ("caseSensitive", V::Arr(&[
+ V::Str("ID"),
+ V::Str("IDs"),
+ V::Str("ID?"),
+ ])),
+ ("caseInsensitive", V::Arr(&[
+ V::Str("unknown"),
+ V::Str("unknown artist"),
+ V::Str("unknown title"),
+ V::Str("untitled"),
+ V::Str("?"),
+ V::Str("??"),
+ V::Str("???"),
+ ])),
+]);
+
+/// spec/data/version-keywords.json
+pub static VERSION_KEYWORDS_DATA: V = V::Obj(&[
+ ("heads", V::Obj(&[
+ ("remix", V::Str("remix")),
+ ("rmx", V::Str("remix")),
+ ("mix", V::Str("mix")),
+ ("bootleg", V::Str("bootleg")),
+ ("vip", V::Str("vip")),
+ ("edit", V::Str("edit")),
+ ("re-edit", V::Str("edit")),
+ ("reedit", V::Str("edit")),
+ ("flip", V::Str("flip")),
+ ("refix", V::Str("refix")),
+ ("rework", V::Str("rework")),
+ ("re-work", V::Str("rework")),
+ ("mashup", V::Str("mashup")),
+ ("mash-up", V::Str("mashup")),
+ ("mash up", V::Str("mashup")),
+ ("blend", V::Str("blend")),
+ ("dub", V::Str("dub")),
+ ("version", V::Str("version")),
+ ("ver", V::Str("version")),
+ ("remaster", V::Str("remaster")),
+ ("remastered", V::Str("remaster")),
+ ("cover", V::Str("cover")),
+ ("reprise", V::Str("reprise")),
+ ])),
+ ("genericHeads", V::Arr(&[
+ V::Str("mix"),
+ V::Str("edit"),
+ V::Str("version"),
+ ])),
+ ("typeCapableModifiers", V::Obj(&[
+ ("radio", V::Str("radio")),
+ ("extended", V::Str("extended")),
+ ("club", V::Str("club")),
+ ("original", V::Str("original")),
+ ("instrumental", V::Str("instrumental")),
+ ("dub", V::Str("dub")),
+ ("vip", V::Str("vip")),
+ ("acoustic", V::Str("acoustic")),
+ ("live", V::Str("live")),
+ ("acapella", V::Str("acapella")),
+ ("a cappella", V::Str("acapella")),
+ ("a capella", V::Str("acapella")),
+ ("acappella", V::Str("acapella")),
+ ("demo", V::Str("demo")),
+ ])),
+ ("prefixForms", V::Obj(&[
+ ("live", V::Str("live")),
+ ("remastered", V::Str("remaster")),
+ ("remaster", V::Str("remaster")),
+ ("acoustic", V::Str("acoustic")),
+ ("instrumental", V::Str("instrumental")),
+ ("acapella", V::Str("acapella")),
+ ("a cappella", V::Str("acapella")),
+ ("demo", V::Str("demo")),
+ ("sped up", V::Str("spedUp")),
+ ("speed up", V::Str("spedUp")),
+ ("slowed + reverb", V::Str("slowed")),
+ ("slowed & reverb", V::Str("slowed")),
+ ("slowed and reverb", V::Str("slowed")),
+ ("slowed", V::Str("slowed")),
+ ("nightcore", V::Str("nightcore")),
+ ])),
+ ("types", V::Arr(&[
+ V::Str("remix"),
+ V::Str("bootleg"),
+ V::Str("vip"),
+ V::Str("edit"),
+ V::Str("flip"),
+ V::Str("refix"),
+ V::Str("rework"),
+ V::Str("mashup"),
+ V::Str("blend"),
+ V::Str("dub"),
+ V::Str("mix"),
+ V::Str("extended"),
+ V::Str("radio"),
+ V::Str("club"),
+ V::Str("original"),
+ V::Str("instrumental"),
+ V::Str("acapella"),
+ V::Str("live"),
+ V::Str("acoustic"),
+ V::Str("remaster"),
+ V::Str("demo"),
+ V::Str("reprise"),
+ V::Str("cover"),
+ V::Str("version"),
+ V::Str("spedUp"),
+ V::Str("slowed"),
+ V::Str("nightcore"),
+ ])),
+]);
diff --git a/rust/src/digits.rs b/rust/src/digits.rs
new file mode 100644
index 0000000..64fe871
--- /dev/null
+++ b/rust/src/digits.rs
@@ -0,0 +1,26 @@
+//! ASCII digit scanning shared by R4.1 (prefix.rs) and the tracklist time scanner (R13.2).
+
+use crate::words::{at, is_digit, sub};
+
+/// Length of the run of ASCII digits starting at `from`.
+pub(crate) fn digit_run(s: &[char], from: usize) -> usize {
+ let mut i = from;
+ while is_digit(at(s, i)) {
+ i += 1;
+ }
+ i - from
+}
+
+/// The value of a short run of ASCII digits (saturating; callers pass at most a few digits).
+pub(crate) fn digits_value(s: &[char]) -> u32 {
+ s.iter().fold(0u32, |n, c| n.saturating_mul(10).saturating_add(c.to_digit(10).unwrap_or(0)))
+}
+
+/// Exactly two digits (not followed by a third) with a value of at most 59, else `None`.
+pub(crate) fn two_digits_up_to_59(s: &[char], at_: usize) -> Option {
+ if !is_digit(at(s, at_)) || !is_digit(at(s, at_ + 1)) || is_digit(at(s, at_ + 2)) {
+ return None;
+ }
+ let n = digits_value(sub(s, at_, at_ + 2));
+ (n <= 59).then_some(n)
+}
diff --git a/rust/src/format.rs b/rust/src/format.rs
new file mode 100644
index 0000000..ab95d2d
--- /dev/null
+++ b/rust/src/format.rs
@@ -0,0 +1,148 @@
+//! R11: render a parsed track back to a string.
+
+use std::collections::HashSet;
+
+use crate::assemble::render_version;
+use crate::options::{FeatMode, ResolvedFormat};
+use crate::tables::{default_tables, Tables};
+use crate::types::{Artist, ArtistRole, ArtistSource, VersionDelimiter};
+use crate::words::{dedup_key, word_matches};
+
+/// The parts of a track R11 reads.
+pub(crate) struct FormatInput<'a> {
+ pub artists: &'a [Artist],
+ pub title: &'a str,
+ pub versions: Vec<(&'a str, VersionDelimiter)>,
+ pub position_raw: Option<&'a str>,
+}
+
+fn is_feat_marker(raw: &str, t: &Tables) -> bool {
+ t.feat_markers.match_at(&[raw], 0).is_some()
+ || t.bracket_only_feat.match_at(&[raw], 0).is_some()
+}
+
+/// R11.5: map a raw joiner to its canonical form through data/joiners.json; feat markers become
+/// `featCanonical`. A featured list's lead marker is always a feat marker (`with` → `feat.`),
+/// while between names the joiner table wins (`Sigala with Ella Eyre` keeps `with`).
+fn canonical_joiner(raw: &str, t: &Tables, feat_lead: bool) -> String {
+ if feat_lead && is_feat_marker(raw, t) {
+ return t.feat_canonical.to_string();
+ }
+ if let Some(tight) = t.tight_joiners.get(raw) {
+ return (*tight).to_string();
+ }
+ for j in &t.spaced_joiners {
+ if if j.case_sensitive { raw == j.raw } else { word_matches(raw, j.raw) } {
+ return j.canonical.to_string();
+ }
+ }
+ if is_feat_marker(raw, t) {
+ t.feat_canonical.to_string()
+ } else {
+ raw.to_string()
+ }
+}
+
+/// R11.1: `" " + joiner + " "`; tight joiners as the raw char + `" "`; a missing joiner as `&`.
+fn join_sep(joiner: Option<&str>, o: &ResolvedFormat, t: &Tables) -> String {
+ let j = match joiner {
+ None => "&".to_string(),
+ Some(j) if o.canonical => canonical_joiner(j, t, false),
+ Some(j) => j.to_string(),
+ };
+ if t.tight_joiners.contains_key(j.as_str()) {
+ format!("{j} ")
+ } else {
+ format!(" {j} ")
+ }
+}
+
+/// Names of one credit list joined by their own joiners (the first joiner is not rendered).
+fn join_names(list: &[&Artist], o: &ResolvedFormat, t: &Tables) -> String {
+ let mut out = String::new();
+ for (i, a) in list.iter().enumerate() {
+ if i > 0 {
+ out.push_str(&join_sep(a.joiner.as_deref(), o, t));
+ }
+ out.push_str(&a.name);
+ }
+ out
+}
+
+/// The marker in front of a featured list.
+fn lead_marker(first: &Artist, o: &ResolvedFormat, t: &Tables, fallback: &str) -> String {
+ if let Some(marker) = &o.feat_marker {
+ return marker.clone();
+ }
+ let raw = first.joiner.as_deref().unwrap_or(fallback);
+ if o.canonical {
+ canonical_joiner(raw, t, true)
+ } else {
+ raw.to_string()
+ }
+}
+
+pub(crate) fn format(track: &FormatInput<'_>, o: &ResolvedFormat) -> String {
+ let tables = default_tables();
+ let t: &Tables = &tables;
+ let with_role = |role: ArtistRole| {
+ track.artists.iter().filter(|a| a.role == role).collect::>()
+ };
+ let primaries = with_role(ArtistRole::Primary);
+ let featured = with_role(ArtistRole::Featured);
+ let producers = with_role(ArtistRole::Producer);
+
+ let (artist_feat, title_feat): (Vec<&Artist>, Vec<&Artist>) = match o.feat {
+ FeatMode::Source => {
+ featured.iter().copied().partition(|a| a.source == ArtistSource::Artist)
+ }
+ FeatMode::Artist => (featured, Vec::new()),
+ FeatMode::Title => (Vec::new(), featured),
+ FeatMode::Omit => (Vec::new(), Vec::new()),
+ };
+
+ // R11.1 / R11.2
+ let mut artist_part = join_names(&primaries, o, t);
+ if let Some(first) = artist_feat.first() {
+ let lead = lead_marker(first, o, t, t.feat_canonical);
+ let names = join_names(&artist_feat, o, t);
+ artist_part = if artist_part.is_empty() {
+ format!("{lead} {names}")
+ } else {
+ format!("{artist_part} {lead} {names}")
+ };
+ }
+
+ // R11.3
+ let mut pieces: Vec = Vec::new();
+ if !track.title.is_empty() {
+ pieces.push(track.title.to_string());
+ }
+ if let Some(first) = title_feat.first() {
+ let lead = lead_marker(first, o, t, t.feat_canonical);
+ pieces.push(format!("({lead} {})", join_names(&title_feat, o, t)));
+ }
+ if o.versions {
+ pieces
+ .extend(track.versions.iter().map(|(raw, delimiter)| render_version(raw, *delimiter)));
+ }
+ if let (true, Some(first)) = (o.producers, producers.first()) {
+ let marker = first.joiner.as_deref().unwrap_or("prod.");
+ pieces.push(format!("({marker} {})", join_names(&producers, o, t)));
+ }
+ let title_part = pieces.join(" ");
+
+ // R11.4
+ let mut result =
+ if artist_part.is_empty() { title_part } else { format!("{artist_part} - {title_part}") };
+ if let (true, Some(raw)) = (o.position, track.position_raw) {
+ result = format!("{raw}. {result}");
+ }
+ result
+}
+
+/// All credited names: track artists plus every version's remixers, deduped by R0.4 key.
+pub(crate) fn all_artists<'a>(all: impl Iterator- ) -> Vec {
+ let mut seen: HashSet = HashSet::new();
+ all.filter(|a| seen.insert(dedup_key(&a.name))).cloned().collect()
+}
diff --git a/rust/src/json.rs b/rust/src/json.rs
new file mode 100644
index 0000000..6853fcd
--- /dev/null
+++ b/rust/src/json.rs
@@ -0,0 +1,374 @@
+//! A small JSON value with a reader and a writer. The crate has no JSON dependency: this is what
+//! `to_json()` writes with, and what the fixtures and the cross-port diff read.
+
+/// An owned JSON value. Objects keep insertion order (like JS objects with string keys).
+///
+/// ```
+/// use trackparse::json::Json;
+///
+/// let value = Json::parse(r#"{"title":"Stigma","year":2015,"tags":["dnb",null]}"#).unwrap();
+/// assert_eq!(value.get("title").and_then(Json::as_str), Some("Stigma"));
+/// assert_eq!(value.get("year"), Some(&Json::Num(2015.0)));
+/// assert_eq!(value.get("tags").and_then(Json::as_array).map(|t| t.len()), Some(2));
+/// assert_eq!(value.write(), r#"{"title":"Stigma","year":2015,"tags":["dnb",null]}"#);
+/// assert_eq!(Json::parse("{oops"), None);
+/// ```
+///
+/// The enum is `#[non_exhaustive]`: a `match` on it outside this crate needs a `_` arm.
+#[derive(Debug, Clone, PartialEq)]
+#[non_exhaustive]
+pub enum Json {
+ /// `null`.
+ Null,
+ /// `true` or `false`.
+ Bool(bool),
+ /// A number. Written as JS writes it: `3167`, `7.5`; a non-finite value is `null`.
+ Num(f64),
+ /// A string.
+ Str(String),
+ /// An array.
+ Arr(Vec),
+ /// An object: its members in order.
+ Obj(Vec<(String, Json)>),
+}
+
+impl std::fmt::Display for Json {
+ /// The compact JSON text of [`Json::write`].
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(&self.write())
+ }
+}
+
+impl Json {
+ /// A string value.
+ pub fn str(s: &str) -> Json {
+ Json::Str(s.to_string())
+ }
+
+ /// A string value, or `null` for `None`.
+ pub fn opt_str(s: Option<&str>) -> Json {
+ s.map_or(Json::Null, Json::str)
+ }
+
+ /// The member `key` of an object.
+ pub fn get(&self, key: &str) -> Option<&Json> {
+ match self {
+ Json::Obj(entries) => entries.iter().find(|(k, _)| k == key).map(|(_, v)| v),
+ _ => None,
+ }
+ }
+
+ /// The string, if the value is one.
+ pub fn as_str(&self) -> Option<&str> {
+ match self {
+ Json::Str(s) => Some(s),
+ _ => None,
+ }
+ }
+
+ /// The items, if the value is an array.
+ pub fn as_array(&self) -> Option<&[Json]> {
+ match self {
+ Json::Arr(items) => Some(items),
+ _ => None,
+ }
+ }
+
+ /// The members in order, if the value is an object.
+ pub fn as_object(&self) -> Option<&[(String, Json)]> {
+ match self {
+ Json::Obj(entries) => Some(entries),
+ _ => None,
+ }
+ }
+
+ /// Compact JSON text, written the way `JSON.stringify` writes it.
+ pub fn write(&self) -> String {
+ let mut out = String::new();
+ self.write_into(&mut out);
+ out
+ }
+
+ fn write_into(&self, out: &mut String) {
+ match self {
+ Json::Null => out.push_str("null"),
+ Json::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
+ Json::Num(n) => write_number(*n, out),
+ Json::Str(s) => write_string(s, out),
+ Json::Arr(items) => {
+ out.push('[');
+ for (i, item) in items.iter().enumerate() {
+ if i > 0 {
+ out.push(',');
+ }
+ item.write_into(out);
+ }
+ out.push(']');
+ }
+ Json::Obj(entries) => {
+ out.push('{');
+ for (i, (k, v)) in entries.iter().enumerate() {
+ if i > 0 {
+ out.push(',');
+ }
+ write_string(k, out);
+ out.push(':');
+ v.write_into(out);
+ }
+ out.push('}');
+ }
+ }
+ }
+
+ /// Parse JSON text. `None` on malformed input (never panics). `1e999` reads as infinity, as
+ /// in JS, so fixtures can carry non-finite numbers.
+ pub fn parse(text: &str) -> Option {
+ let chars: Vec = text.chars().collect();
+ let mut p = Reader { chars: &chars, at: 0, depth: 0 };
+ p.ws();
+ let v = p.value()?;
+ p.ws();
+ if p.at == chars.len() {
+ Some(v)
+ } else {
+ None
+ }
+ }
+}
+
+/// JS `Number::toString` (what `JSON.stringify` writes): the shortest digits that round-trip,
+/// laid out without an exponent from 1e-6 up to 1e21 and as `1e+21` / `1.5e-7` outside it.
+/// Non-finite values are `null`; `-0` is `0`.
+#[cfg(feature = "serde")]
+pub(crate) fn number_text(n: f64) -> String {
+ let mut out = String::new();
+ write_number(n, &mut out);
+ out
+}
+
+fn write_number(n: f64, out: &mut String) {
+ if !n.is_finite() {
+ out.push_str("null");
+ return;
+ }
+ if n == 0.0 {
+ out.push('0');
+ return;
+ }
+ if n < 0.0 {
+ out.push('-');
+ }
+ // `{:e}` gives the shortest round-trip digits as `d[.ddd]e`.
+ let sci = format!("{:e}", n.abs());
+ let (mantissa, exp) = sci.split_once('e').unwrap_or((&sci, "0"));
+ let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect();
+ let k = digits.len() as i32;
+ // The value is 0.digits × 10^point.
+ let point = exp.parse::().unwrap_or(0) + 1;
+ if k <= point && point <= 21 {
+ out.push_str(&digits);
+ out.extend(std::iter::repeat('0').take((point - k) as usize));
+ } else if 0 < point && point <= 21 {
+ let (int, frac) = digits.split_at(point as usize);
+ out.push_str(int);
+ out.push('.');
+ out.push_str(frac);
+ } else if -6 < point && point <= 0 {
+ out.push_str("0.");
+ out.extend(std::iter::repeat('0').take((-point) as usize));
+ out.push_str(&digits);
+ } else {
+ let (first, rest) = digits.split_at(1.min(digits.len()));
+ out.push_str(first);
+ if !rest.is_empty() {
+ out.push('.');
+ out.push_str(rest);
+ }
+ out.push('e');
+ out.push(if point > 0 { '+' } else { '-' });
+ out.push_str(&(point - 1).abs().to_string());
+ }
+}
+
+fn write_string(s: &str, out: &mut String) {
+ out.push('"');
+ for ch in s.chars() {
+ match ch {
+ '"' => out.push_str("\\\""),
+ '\\' => out.push_str("\\\\"),
+ '\n' => out.push_str("\\n"),
+ '\r' => out.push_str("\\r"),
+ '\t' => out.push_str("\\t"),
+ '\u{8}' => out.push_str("\\b"),
+ '\u{c}' => out.push_str("\\f"),
+ c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
+ c => out.push(c),
+ }
+ }
+ out.push('"');
+}
+
+struct Reader<'a> {
+ chars: &'a [char],
+ at: usize,
+ depth: usize,
+}
+
+impl Reader<'_> {
+ fn peek(&self) -> Option {
+ self.chars.get(self.at).copied()
+ }
+
+ fn ws(&mut self) {
+ while matches!(self.peek(), Some(' ' | '\t' | '\n' | '\r')) {
+ self.at += 1;
+ }
+ }
+
+ fn eat(&mut self, word: &str) -> bool {
+ let n = word.chars().count();
+ let ok = self
+ .chars
+ .get(self.at..self.at + n)
+ .is_some_and(|s| s.iter().copied().eq(word.chars()));
+ if ok {
+ self.at += n;
+ }
+ ok
+ }
+
+ fn value(&mut self) -> Option {
+ if self.depth > 200 {
+ return None;
+ }
+ match self.peek()? {
+ 'n' => self.eat("null").then_some(Json::Null),
+ 't' => self.eat("true").then_some(Json::Bool(true)),
+ 'f' => self.eat("false").then_some(Json::Bool(false)),
+ '"' => self.string().map(Json::Str),
+ '[' => {
+ self.at += 1;
+ self.depth += 1;
+ let mut items = Vec::new();
+ self.ws();
+ if self.peek() == Some(']') {
+ self.at += 1;
+ } else {
+ loop {
+ self.ws();
+ items.push(self.value()?);
+ self.ws();
+ match self.peek()? {
+ ',' => self.at += 1,
+ ']' => {
+ self.at += 1;
+ break;
+ }
+ _ => return None,
+ }
+ }
+ }
+ self.depth -= 1;
+ Some(Json::Arr(items))
+ }
+ '{' => {
+ self.at += 1;
+ self.depth += 1;
+ let mut entries: Vec<(String, Json)> = Vec::new();
+ self.ws();
+ if self.peek() == Some('}') {
+ self.at += 1;
+ } else {
+ loop {
+ self.ws();
+ let key = self.string()?;
+ self.ws();
+ if self.peek()? != ':' {
+ return None;
+ }
+ self.at += 1;
+ self.ws();
+ let v = self.value()?;
+ // A repeated key keeps its first position and takes the last value (JS).
+ match entries.iter_mut().find(|(k, _)| *k == key) {
+ Some(slot) => slot.1 = v,
+ None => entries.push((key, v)),
+ }
+ self.ws();
+ match self.peek()? {
+ ',' => self.at += 1,
+ '}' => {
+ self.at += 1;
+ break;
+ }
+ _ => return None,
+ }
+ }
+ }
+ self.depth -= 1;
+ Some(Json::Obj(entries))
+ }
+ _ => self.number(),
+ }
+ }
+
+ fn number(&mut self) -> Option {
+ let start = self.at;
+ while matches!(self.peek(), Some('0'..='9' | '-' | '+' | '.' | 'e' | 'E')) {
+ self.at += 1;
+ }
+ let text: String = self.chars.get(start..self.at)?.iter().collect();
+ text.parse::().ok().map(Json::Num)
+ }
+
+ fn hex4(&mut self) -> Option {
+ let s: String = self.chars.get(self.at..self.at + 4)?.iter().collect();
+ self.at += 4;
+ u32::from_str_radix(&s, 16).ok()
+ }
+
+ fn string(&mut self) -> Option {
+ if self.peek()? != '"' {
+ return None;
+ }
+ self.at += 1;
+ let mut out = String::new();
+ loop {
+ let ch = self.peek()?;
+ self.at += 1;
+ match ch {
+ '"' => return Some(out),
+ '\\' => {
+ let e = self.peek()?;
+ self.at += 1;
+ match e {
+ 'n' => out.push('\n'),
+ 'r' => out.push('\r'),
+ 't' => out.push('\t'),
+ 'b' => out.push('\u{8}'),
+ 'f' => out.push('\u{c}'),
+ 'u' => {
+ let hi = self.hex4()?;
+ let cp = if (0xd800..0xdc00).contains(&hi) && self.eat("\\u") {
+ let lo = self.hex4()?;
+ if (0xdc00..0xe000).contains(&lo) {
+ 0x10000 + ((hi - 0xd800) << 10) + (lo - 0xdc00)
+ } else {
+ // Two units that do not pair: both become U+FFFD.
+ out.push('\u{fffd}');
+ lo
+ }
+ } else {
+ hi
+ };
+ // A lone surrogate cannot live in a Rust string.
+ out.push(char::from_u32(cp).unwrap_or('\u{fffd}'));
+ }
+ other => out.push(other),
+ }
+ }
+ c => out.push(c),
+ }
+ }
+ }
+}
diff --git a/rust/src/lib.rs b/rust/src/lib.rs
new file mode 100644
index 0000000..73ebe92
--- /dev/null
+++ b/rust/src/lib.rs
@@ -0,0 +1,326 @@
+//! Turn messy track names into structured data: artists with roles, remixes and versions,
+//! junk, and whole tracklists.
+//!
+//! trackparse is driven by a written spec. Behaviour is defined by [`SPEC.md`] and its shared
+//! fixtures. This crate passes every shared fixture, and for every fixture input its output is
+//! byte-identical to the JavaScript (npm `trackparse`) and Python (PyPI `trackparse`) packages.
+//! Rule IDs such as `R6.2` in these docs refer to the spec.
+//!
+//! - User documentation:
+//! - The spec:
+//!
+//! [`SPEC.md`]: https://github.com/4matic/trackparse/blob/main/spec/SPEC.md
+//!
+//! # Single tracks
+//!
+//! [`parse`] takes any string and returns a [`ParsedTrack`]. It never panics and never returns
+//! an error: what it recognises goes into a field, what it does not stays in the title.
+//!
+//! ```
+//! use trackparse::{parse, ArtistRole, JunkKind, VersionType};
+//!
+//! let track = parse("Noisia feat. Foreign Beggars - Shellshock (Rockwell Remix) [Official Video]");
+//!
+//! assert_eq!(track.artists[0].name, "Noisia");
+//! assert_eq!(track.artists[1].name, "Foreign Beggars");
+//! assert_eq!(track.artists[1].role, ArtistRole::Featured);
+//! assert_eq!(track.title, "Shellshock");
+//! assert_eq!(track.full_title, "Shellshock (Rockwell Remix)");
+//! assert_eq!(track.versions[0].version_type, VersionType::Remix);
+//! assert_eq!(track.versions[0].artists[0].name, "Rockwell");
+//! assert_eq!(track.junk[0].kind, JunkKind::Video);
+//! ```
+//!
+//! [`parse_with`] takes [`ParseOptions`]; a [`Parser`] keeps resolved options for many calls.
+//! [`parse_artists`] splits a credit string, [`format_track`] writes a track back as a string,
+//! [`normalize()`] cleans a string without parsing it, and [`all_artists`] lists every credited
+//! name, remixers included.
+//!
+//! ```
+//! use trackparse::{format_track_with, parse_with, FeatPlacement, FormatOptions, ParseOptions};
+//!
+//! let options = ParseOptions::new().known_artists(["Chase & Status"]);
+//! let track = parse_with("Chase & Status - Blind Faith ft. Liam Bailey", &options);
+//! assert_eq!(track.artists.len(), 2);
+//!
+//! let format = FormatOptions::new().feat(FeatPlacement::Artist);
+//! assert_eq!(format_track_with(&track, &format), "Chase & Status ft. Liam Bailey - Blind Faith");
+//! ```
+//!
+//! # Tracklists
+//!
+//! The [`tracklist`] module reads a whole pasted tracklist: one entry per line, with its time,
+//! its kind and the parsed track, plus warnings about the times. [`tracklist::apply_edits`]
+//! rewrites times and lines without touching anything else.
+//!
+//! ```
+//! use trackparse::tracklist::{apply_edits, parse_tracklist, Edit, WarningCode};
+//!
+//! let text = "00:00 Noisia - Stigma\n03:45 Phace & Misanthrop - Desert Orgy\n02:10 Mefjus - Suicide Bassline";
+//! let list = parse_tracklist(text);
+//! assert_eq!(list.stats.tracks, 3);
+//! assert_eq!(list.entries[1].time.as_ref().unwrap().seconds, 225.0);
+//! assert_eq!(list.entries[1].track.as_ref().unwrap().title, "Desert Orgy");
+//! assert_eq!(list.warnings[0].code, WarningCode::TimeOutOfOrder);
+//!
+//! let fixed = apply_edits(text, &[Edit::sort_by_time()]);
+//! assert_eq!(
+//! fixed.text,
+//! "00:00 Noisia - Stigma\n02:10 Mefjus - Suicide Bassline\n03:45 Phace & Misanthrop - Desert Orgy"
+//! );
+//! ```
+//!
+//! # JSON
+//!
+//! Fields are snake_case in Rust. `to_json()` on every output type writes the spec's JSON form:
+//! camelCase keys (`fullTitle`, `unknownArtist`), every key present, in the schema's order. It is
+//! the same text the JavaScript and Python packages produce, and needs no dependency.
+//!
+//! ```
+//! let artists = trackparse::parse_artists("Noisia & Phace");
+//! assert_eq!(
+//! artists[1].to_json(),
+//! r#"{"name":"Phace","role":"primary","joiner":"&","source":"artist"}"#
+//! );
+//! ```
+//!
+//! With the `serde` feature the output types implement `Serialize` and `Deserialize` with the
+//! same keys, so `serde_json::to_string(&track)` gives the text of `track.to_json()`. The
+//! options and [`tracklist::Edit`] implement both traits too. Numbers are written as
+//! `to_json()` writes them. The exceptions are numbers no parse result contains: seconds from
+//! 0.000001 up to 0.00001 (and, with older `serde_json` releases, of 1e21 and more) in an
+//! `Edit` or an option built by hand, which `serde_json` writes in its own float notation
+//! (`1e-6` for `0.000001`). Non-finite seconds are written as `null`, as by `to_json()`, and
+//! `null` reads back as NaN. Keyword maps are written without repeated keys (the last value
+//! wins, as in a JS object).
+//!
+//! # Guarantees
+//!
+//! - Total: any `&str` gives a result. No panics, no `Result` (R0.8).
+//! - No regular expressions and no backtracking: the scanners make a bounded number of passes
+//! over the input. A 10,000-code-point string parses in a few milliseconds, and the test suite
+//! checks that repeated hostile fragments scale far below quadratic.
+//! - No `unsafe`. One dependency (`unicode-normalization`); `serde` only with the feature.
+//! - The Unicode tables the rules depend on (letters, uppercase letters, lowercase mapping) are
+//! compiled in, so the output does not change with the compiler version.
+//! - NFC and NFD (R1, R0.4) come from `unicode-normalization` and follow that crate's Unicode
+//! version: 0.1.26, the minimum this crate accepts, has the Unicode 18 tables. The JavaScript
+//! reference normalizes with its runtime's tables (Unicode 17 on Node 24), so a string with
+//! one of the 32 combining marks added in Unicode 18 can come out in another mark order than
+//! it does there. Text without those marks is not affected.
+
+#![warn(missing_docs)]
+#![cfg_attr(docsrs, feature(doc_cfg))]
+
+pub mod json;
+pub mod tracklist;
+#[doc(hidden)]
+pub mod wire;
+
+mod artists;
+mod assemble;
+mod classify;
+mod context;
+mod credits;
+#[rustfmt::skip]
+mod data;
+mod digits;
+mod format;
+mod mode;
+mod normalize;
+mod options;
+mod parser;
+mod prefix;
+mod scanner;
+mod separator;
+#[cfg(feature = "serde")]
+mod serde_support;
+mod tables;
+mod title;
+mod types;
+#[rustfmt::skip]
+mod unicode_tables;
+mod value;
+mod words;
+
+pub use data::SPEC_VERSION;
+pub use options::{
+ FeatPlacement, FormatOptions, JoinerStyle, KeywordOptions, ModeOption, ParseOptions, SplitAnd,
+ VersionsOption,
+};
+pub use types::{
+ Artist, ArtistRole, ArtistSource, Flags, Junk, JunkKind, Mode, ParsedTrack, Position,
+ Timestamp, ToJson, UnknownName, Version, VersionDelimiter, VersionType, Warning,
+};
+
+use options::{Resolved, ResolvedFormat};
+use parser::Engine;
+
+/// The examples of the README, run as doc tests (they use the `serde` feature).
+#[cfg(all(doctest, feature = "serde"))]
+#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
+#[doc = include_str!("../README.md")]
+pub struct ReadmeDoctests;
+
+/// Parse one track string with the default options (mode `auto`).
+///
+/// Never panics: any string gives a [`ParsedTrack`] (SPEC R0.8).
+///
+/// ```
+/// let track = trackparse::parse("Sub Focus - Out the Blue ft. Alice Gold (2015)");
+/// assert_eq!(track.title, "Out the Blue");
+/// assert_eq!(track.year, Some(2015));
+/// assert_eq!(track.artists.len(), 2);
+/// ```
+pub fn parse(input: &str) -> ParsedTrack {
+ Engine::shared().run(input, false).into_track()
+}
+
+/// Parse one track string with options (R12).
+///
+/// To parse many strings with the same options, build a [`Parser`] once instead.
+///
+/// ```
+/// use trackparse::{parse_with, Mode, ModeOption, ParseOptions};
+///
+/// let options = ParseOptions::new().mode(ModeOption::Youtube);
+/// let track = parse_with("Noisia - Stigma (Official Video)", &options);
+/// assert_eq!(track.mode, Mode::Youtube);
+/// assert_eq!(track.title, "Stigma");
+/// assert_eq!(track.junk[0].raw, "Official Video");
+/// ```
+pub fn parse_with(input: &str, options: &ParseOptions) -> ParsedTrack {
+ Parser::new(options).parse(input)
+}
+
+/// Split a credit string into artists (R10).
+///
+/// ```
+/// let artists = trackparse::parse_artists("Noisia & The Upbeats feat. Foreign Beggars");
+/// let names: Vec<&str> = artists.iter().map(|a| a.name.as_str()).collect();
+/// assert_eq!(names, ["Noisia", "The Upbeats", "Foreign Beggars"]);
+/// ```
+pub fn parse_artists(input: &str) -> Vec {
+ Engine::shared().run_artists(input)
+}
+
+/// [`parse_artists`] with options (`known_artists`, `split_and`, `keywords`).
+///
+/// ```
+/// use trackparse::{parse_artists_with, ParseOptions};
+///
+/// let options = ParseOptions::new().known_artists(["Above & Beyond"]);
+/// let artists = parse_artists_with("Above & Beyond & Zoë Johnston", &options);
+/// let names: Vec<&str> = artists.iter().map(|a| a.name.as_str()).collect();
+/// assert_eq!(names, ["Above & Beyond", "Zoë Johnston"]);
+/// ```
+pub fn parse_artists_with(input: &str, options: &ParseOptions) -> Vec {
+ Parser::new(options).parse_artists(input)
+}
+
+/// Render a parsed track back to a string (R11) with the default format options.
+///
+/// ```
+/// use trackparse::{format_track, parse};
+///
+/// let track = parse("Sub Focus - Out the Blue ft. Alice Gold");
+/// assert_eq!(format_track(&track), "Sub Focus - Out the Blue (ft. Alice Gold)");
+/// ```
+pub fn format_track(track: &ParsedTrack) -> String {
+ format_track_with(track, &FormatOptions::default())
+}
+
+/// Render a parsed track back to a string (R11).
+///
+/// ```
+/// use trackparse::{format_track_with, parse, FeatPlacement, FormatOptions};
+///
+/// let track = parse("Sub Focus - Out the Blue ft. Alice Gold");
+/// let options = FormatOptions::new().feat(FeatPlacement::Artist);
+/// assert_eq!(format_track_with(&track, &options), "Sub Focus ft. Alice Gold - Out the Blue");
+/// ```
+pub fn format_track_with(track: &ParsedTrack, options: &FormatOptions) -> String {
+ let input = format::FormatInput {
+ artists: &track.artists,
+ title: &track.title,
+ versions: track.versions.iter().map(|v| (v.raw.as_str(), v.delimiter)).collect(),
+ position_raw: track.position.as_ref().map(|p| p.raw.as_str()),
+ };
+ format::format(&input, &ResolvedFormat::from_typed(options))
+}
+
+/// Normalize a track string (R1): NFC, ASCII brackets, quotes and dashes, invisible characters
+/// removed, whitespace collapsed. Idempotent.
+///
+/// ```
+/// assert_eq!(trackparse::normalize(" Noisia – Stigma\u{200b} "), "Noisia - Stigma");
+/// ```
+pub fn normalize(input: &str) -> String {
+ normalize::normalize(input)
+}
+
+/// All credited names: the track's artists plus every version's remixers, deduped (R0.4 key).
+///
+/// ```
+/// let track = trackparse::parse("Fox Stevenson - Bruises (Magnetude Remix)");
+/// let names: Vec = trackparse::all_artists(&track).into_iter().map(|a| a.name).collect();
+/// assert_eq!(names, ["Fox Stevenson", "Magnetude"]);
+/// ```
+pub fn all_artists(track: &ParsedTrack) -> Vec {
+ format::all_artists(
+ track.artists.iter().chain(track.versions.iter().flat_map(|v| v.artists.iter())),
+ )
+}
+
+/// A parser with its options resolved and its vocabulary tables built once (`createParser` in
+/// JavaScript, `create_parser` in Python). Use it to parse many strings with the same options.
+/// It is `Send + Sync`, and cloning it is cheap (the tables are shared).
+///
+/// ```
+/// use trackparse::{ParseOptions, Parser};
+///
+/// let parser = Parser::new(&ParseOptions::new().known_artists(["Chase & Status"]));
+/// let track = parser.parse("Chase & Status - Blind Faith");
+/// assert_eq!(track.artists.len(), 1);
+/// assert_eq!(track.artists[0].name, "Chase & Status");
+/// ```
+#[derive(Clone)]
+pub struct Parser {
+ engine: Engine,
+}
+
+impl Parser {
+ /// Resolve `options` and build the vocabulary tables.
+ pub fn new(options: &ParseOptions) -> Parser {
+ Parser { engine: Engine::new(Resolved::from_typed(options)) }
+ }
+
+ /// [`parse`] with this parser's options.
+ pub fn parse(&self, input: &str) -> ParsedTrack {
+ self.engine.run(input, false).into_track()
+ }
+
+ /// [`parse_artists`] with this parser's options.
+ ///
+ /// ```
+ /// use trackparse::{ParseOptions, Parser, SplitAnd};
+ ///
+ /// let parser = Parser::new(&ParseOptions::new().split_and(SplitAnd::Always));
+ /// assert_eq!(parser.parse_artists("Above and Beyond").len(), 2);
+ /// ```
+ pub fn parse_artists(&self, input: &str) -> Vec {
+ self.engine.run_artists(input)
+ }
+}
+
+impl Default for Parser {
+ fn default() -> Self {
+ Parser::new(&ParseOptions::default())
+ }
+}
+
+impl std::fmt::Debug for Parser {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Parser").finish_non_exhaustive()
+ }
+}
diff --git a/rust/src/mode.rs b/rust/src/mode.rs
new file mode 100644
index 0000000..7760405
--- /dev/null
+++ b/rust/src/mode.rs
@@ -0,0 +1,245 @@
+//! R2: mode resolution, platform suffixes, filename handling and youtube pipes.
+
+use crate::classify::junk_kind_of;
+use crate::context::{warn, Ctx};
+use crate::options::Requested;
+use crate::scanner::{
+ groups_of, has_spaced_dash, render_skel, scan, slice_skel, start_pos, Segment, Skel,
+};
+use crate::types::{Mode, Warning};
+use crate::words::{
+ ascii_lower, at, before, chars, collapse_spaces, js_trim_chars, span_texts, split_words,
+ string, sub, tail, utf16_off, word_spans,
+};
+
+#[derive(Debug, Clone)]
+pub(crate) struct PositionedJunk {
+ pub raw: String,
+ /// A junk kind name; `keywords.junk` values pass through as given.
+ pub kind: String,
+ pub pos: i64,
+}
+
+/// A contiguous piece of the normalized string and its absolute offset.
+#[derive(Debug, Clone)]
+pub(crate) struct Piece {
+ pub text: Vec,
+ pub base: i64,
+}
+
+pub(crate) struct Prelude {
+ pub mode: Mode,
+ /// The working string (R2.4 step 2/4), or the artist piece in the `artist | title` case.
+ pub working: Piece,
+ /// R2.4 step 3: the title piece when two dash-less pipe segments remain.
+ pub pipe_title: Option,
+ pub junk: Vec,
+}
+
+fn ascii_lower_chars(t: &[char]) -> Vec {
+ t.iter().map(|c| c.to_ascii_lowercase()).collect()
+}
+
+/// R2.2: strip trailing platform suffixes (longest first, repeatedly).
+fn strip_platform_suffixes(s: &[char], ctx: &Ctx<'_>, junk: &mut Vec) -> Vec {
+ let mut text = s.to_vec();
+ let mut stripped = true;
+ while stripped {
+ stripped = false;
+ let lower = ascii_lower_chars(&text);
+ for suffix in &ctx.t.platform_suffixes {
+ let suffix_lower = chars(&ascii_lower(suffix));
+ if !lower.ends_with(&suffix_lower) {
+ continue;
+ }
+ let start = text.len() - suffix_lower.len().min(text.len());
+ junk.push(PositionedJunk {
+ raw: string(tail(&text, start + 3)),
+ kind: "platform".to_string(),
+ pos: utf16_off(sub(&text, 0, start)) + 3,
+ });
+ text.truncate(start);
+ stripped = true;
+ break;
+ }
+ }
+ text
+}
+
+fn last_dot(s: &[char]) -> Option {
+ s.iter().rposition(|&c| c == '.')
+}
+
+fn has_extension(s: &[char], ctx: &Ctx<'_>) -> bool {
+ last_dot(s).is_some_and(|dot| {
+ let ext = ascii_lower(&string(tail(s, dot + 1)));
+ ctx.t.extensions.contains(ext.as_str())
+ })
+}
+
+/// Top-level ` | ` / ` || ` separators on a skeleton → trimmed segment ranges.
+pub(crate) fn split_pipes(skel: &Skel) -> Vec {
+ let t = &skel.text;
+ let mut cuts: Vec<(usize, usize)> = Vec::new();
+ let mut i = 1;
+ while i < t.len() {
+ if before(t, i) == Some(' ') && at(t, i) == Some('|') {
+ let bars = if at(t, i + 1) == Some('|') { 2 } else { 1 };
+ if at(t, i + bars) == Some(' ') {
+ cuts.push((i - 1, i + bars + 1));
+ i += bars;
+ }
+ }
+ i += 1;
+ }
+ cuts.push((t.len(), t.len()));
+ let mut segments = Vec::with_capacity(cuts.len());
+ let mut start = 0usize;
+ for (a, b) in cuts {
+ let mut s = start;
+ let mut e = a;
+ while s < e && at(t, s) == Some(' ') {
+ s += 1;
+ }
+ while e > s && before(t, e) == Some(' ') {
+ e -= 1;
+ }
+ segments.push(Segment { skel: slice_skel(skel, s, e), start: s, end: e });
+ start = b;
+ }
+ segments
+}
+
+/// R8.4 test: the skeleton ends with an unbracketed junk phrase (genres excluded). Returns the
+/// code-point index where the phrase starts, and its kind.
+pub(crate) fn trailing_junk_phrase(text: &[char], ctx: &Ctx<'_>) -> Option<(usize, String)> {
+ let spans = word_spans(text);
+ let words = span_texts(&spans);
+ let m = ctx.t.junk_phrases.match_ending(&words, spans.len())?;
+ let first = spans.get(spans.len().checked_sub(m.length)?)?;
+ Some((first.start, m.value.clone()))
+}
+
+fn junk_text_kind(text: &str, ctx: &Ctx<'_>) -> Option {
+ let words = split_words(text);
+ if words.is_empty() {
+ None
+ } else {
+ junk_kind_of(&words, ctx)
+ }
+}
+
+/// R2.1 youtube signals (besides platform suffixes).
+fn looks_like_youtube(skel: &Skel, ctx: &Ctx<'_>) -> bool {
+ if split_pipes(skel).len() > 1 {
+ return true;
+ }
+ for (_, group) in groups_of(skel) {
+ if junk_text_kind(&group.inner, ctx).is_some_and(|kind| kind != "genre") {
+ return true;
+ }
+ }
+ trailing_junk_phrase(&skel.text, ctx).is_some()
+}
+
+pub(crate) fn prelude(normalized: &str, requested: Requested, ctx: &mut Ctx<'_>) -> Prelude {
+ let mut junk: Vec = Vec::new();
+ let mut text = strip_platform_suffixes(&chars(normalized), ctx, &mut junk);
+ let had_platform = !junk.is_empty();
+
+ let mut mode = match requested {
+ Requested::Mode(m) => m, // R13.6: tracklist is explicit only; R2.3/R2.4 do not run.
+ _ if has_extension(&text, ctx) => Mode::Filename,
+ _ => Mode::Clean,
+ };
+
+ if mode == Mode::Filename {
+ // R2.3: strip the extension, trim, then `_` → space when there is no space.
+ if has_extension(&text, ctx) {
+ text.truncate(last_dot(&text).unwrap_or(text.len()));
+ }
+ text = js_trim_chars(&text).to_vec();
+ if !text.contains(&' ') && text.contains(&'_') {
+ let spaced: Vec = text.iter().map(|&c| if c == '_' { ' ' } else { c }).collect();
+ text = js_trim_chars(&spaced).to_vec();
+ }
+ }
+
+ let (skel, unbalanced) = scan(&text, 0);
+ if unbalanced {
+ warn(ctx, Warning::UnbalancedBrackets);
+ }
+ if requested == Requested::Auto
+ && mode == Mode::Clean
+ && (had_platform || looks_like_youtube(&skel, ctx))
+ {
+ mode = Mode::Youtube;
+ }
+
+ if mode != Mode::Youtube {
+ return Prelude { mode, working: Piece { text, base: 0 }, pipe_title: None, junk };
+ }
+ let (working, pipe_title) = split_youtube_pipes(&skel, ctx, &mut junk);
+ Prelude { mode, working, pipe_title, junk }
+}
+
+fn piece_of(seg: &Segment) -> Piece {
+ Piece { text: chars(&render_skel(&seg.skel)), base: start_pos(&seg.skel, 0) }
+}
+
+/// R2.4
+fn split_youtube_pipes(
+ skel: &Skel,
+ ctx: &mut Ctx<'_>,
+ junk: &mut Vec,
+) -> (Piece, Option) {
+ let segments = split_pipes(skel);
+ if segments.len() <= 1 {
+ return (Piece { text: chars(&render_skel(skel)), base: 0 }, None);
+ }
+
+ let mut remaining: Vec<&Segment> = Vec::new();
+ for seg in &segments {
+ let text = collapse_spaces(&render_skel(&seg.skel));
+ // R2.4 step 1: a segment with a spaced dash is an artist/title candidate, never junk.
+ let kind = if has_spaced_dash(&seg.skel.text) { None } else { junk_text_kind(&text, ctx) };
+ match kind {
+ Some(kind) if !kind.is_empty() => {
+ junk.push(PositionedJunk { raw: text, kind, pos: start_pos(&seg.skel, 0) });
+ }
+ _ if !text.is_empty() => remaining.push(seg),
+ _ => {}
+ }
+ }
+ let push_other = |keep: usize, junk: &mut Vec| {
+ for (i, seg) in remaining.iter().enumerate() {
+ if i == keep {
+ continue;
+ }
+ junk.push(PositionedJunk {
+ raw: collapse_spaces(&render_skel(&seg.skel)),
+ kind: "other".to_string(),
+ pos: start_pos(&seg.skel, 0),
+ });
+ }
+ };
+
+ if let Some(i) = remaining.iter().position(|seg| has_spaced_dash(&seg.skel.text)) {
+ push_other(i, junk);
+ return (remaining.get(i).map_or_else(empty_piece, |s| piece_of(s)), None);
+ }
+ if let [first, second] = remaining.as_slice() {
+ warn(ctx, Warning::AmbiguousSeparator);
+ return (piece_of(first), Some(piece_of(second)));
+ }
+ if let Some(first) = remaining.first() {
+ push_other(0, junk);
+ return (piece_of(first), None);
+ }
+ // Every segment was junk: nothing left to parse.
+ (empty_piece(), None)
+}
+
+fn empty_piece() -> Piece {
+ Piece { text: Vec::new(), base: 0 }
+}
diff --git a/rust/src/normalize.rs b/rust/src/normalize.rs
new file mode 100644
index 0000000..8bfe9fb
--- /dev/null
+++ b/rust/src/normalize.rs
@@ -0,0 +1,75 @@
+//! R1: normalization.
+
+use unicode_normalization::UnicodeNormalization;
+
+use crate::words::{at, before, is_ws};
+
+/// R1.2 invisible characters removed outright. ZWNJ/ZWJ (U+200C/U+200D) are kept (ZWJ emoji).
+/// U+E000 is reserved as the R3.4 group placeholder, so it can never occur in input.
+fn is_removed(cp: u32) -> bool {
+ matches!(cp, 0x200b | 0x2060 | 0xfeff | 0x00ad | 0xe000)
+}
+
+/// R1.3 brackets, R1.4 quotes, R1.5 dashes → ASCII. `None` for a removed character.
+fn map_char(ch: char) -> Option {
+ let cp = ch as u32;
+ if is_removed(cp) {
+ return None;
+ }
+ if (0x2010..=0x2015).contains(&cp) {
+ return Some('-'); // R1.5
+ }
+ Some(match cp {
+ 0xff08 => '(',
+ 0xff09 => ')',
+ 0xff3b | 0x3010 | 0x3014 => '[',
+ 0xff3d | 0x3011 | 0x3015 => ']',
+ 0xff5b => '{',
+ 0xff5d => '}',
+ 0x201c | 0x201d | 0x201e | 0x00ab | 0x00bb | 0x300c | 0x300d | 0x300e | 0x300f | 0xff02 => {
+ '"'
+ }
+ 0x2018 | 0x2019 | 0x201a | 0x0060 | 0x00b4 => '\'',
+ 0x2212 | 0xfe58 | 0xfe63 | 0xff0d => '-',
+ _ => ch,
+ })
+}
+
+/// R1.5 (second half): a run of 2+ `-` with whitespace on both sides becomes one `-`.
+fn collapse_spaced_dash_runs(chars: &[char]) -> Vec {
+ let mut out = Vec::with_capacity(chars.len());
+ let mut i = 0;
+ while let Some(ch) = at(chars, i) {
+ if ch != '-' {
+ out.push(ch);
+ i += 1;
+ continue;
+ }
+ let mut j = i;
+ while at(chars, j) == Some('-') {
+ j += 1;
+ }
+ let spaced =
+ j - i >= 2 && before(chars, i).is_some_and(is_ws) && at(chars, j).is_some_and(is_ws);
+ if spaced {
+ out.push('-');
+ } else {
+ out.extend(std::iter::repeat('-').take(j - i));
+ }
+ i = j;
+ }
+ out
+}
+
+/// R1.6: every whitespace code point → one space, runs collapsed, trimmed.
+fn collapse_whitespace(chars: &[char]) -> String {
+ crate::words::collapse_chars(chars)
+}
+
+/// R1: normalize a track string. Idempotent.
+pub(crate) fn normalize(input: &str) -> String {
+ let chars: Vec = input.nfc().filter_map(map_char).collect();
+ // R1.8: removing invisibles can leave a decomposed sequence behind; re-compose so that
+ // normalize() stays idempotent.
+ collapse_whitespace(&collapse_spaced_dash_runs(&chars)).nfc().collect()
+}
diff --git a/rust/src/options.rs b/rust/src/options.rs
new file mode 100644
index 0000000..a36b201
--- /dev/null
+++ b/rust/src/options.rs
@@ -0,0 +1,660 @@
+//! R12 options: the typed public options and the resolved form the pipeline reads.
+//!
+//! Two doors lead to the resolved form: the typed structs below, and loose JSON (`wire`), which
+//! is resolved with exactly the fallbacks of the JS reference (a bad value means the default,
+//! R0.8).
+
+use crate::json::Json;
+use crate::types::{string_enum, JunkKind, Mode, VersionType};
+
+string_enum! {
+ /// The mode to parse in (R2). `Auto` picks clean, youtube or filename from the string
+ /// itself, never tracklist.
+ ///
+ /// ```
+ /// use trackparse::{parse_with, Mode, ModeOption, ParseOptions};
+ ///
+ /// let input = "Noisia - Stigma (Official Video)";
+ /// assert_eq!(parse_with(input, &ParseOptions::new()).mode, Mode::Youtube);
+ /// let clean = ParseOptions::new().mode(ModeOption::Clean);
+ /// assert_eq!(parse_with(input, &clean).mode, Mode::Clean);
+ /// assert_eq!(ModeOption::default(), ModeOption::Auto);
+ /// ```
+ #[non_exhaustive]
+ ModeOption {
+ Auto => "auto", Clean => "clean", Youtube => "youtube", Filename => "filename",
+ Tracklist => "tracklist",
+ }
+}
+
+string_enum! {
+ /// When the word `and` splits a credit list (R7.3). `&` and the other joiners always split.
+ ///
+ /// ```
+ /// use trackparse::{parse_artists_with, ParseOptions, SplitAnd};
+ ///
+ /// let count = |split_and| {
+ /// let options = ParseOptions::new().split_and(split_and);
+ /// parse_artists_with("Above and Beyond", &options).len()
+ /// };
+ /// assert_eq!(count(SplitAnd::Auto), 1);
+ /// assert_eq!(count(SplitAnd::Always), 2);
+ /// assert_eq!(count(SplitAnd::Never), 1);
+ /// ```
+ #[non_exhaustive]
+ SplitAnd { Auto => "auto", Always => "always", Never => "never" }
+}
+
+string_enum! {
+ /// Where [`format_track_with`](crate::format_track_with) writes featured artists (R11.2).
+ ///
+ /// ```
+ /// use trackparse::{format_track_with, parse, FeatPlacement, FormatOptions};
+ ///
+ /// let track = parse("Sub Focus - Out the Blue ft. Alice Gold");
+ /// let with = |feat| format_track_with(&track, &FormatOptions::new().feat(feat));
+ /// assert_eq!(with(FeatPlacement::Source), "Sub Focus - Out the Blue (ft. Alice Gold)");
+ /// assert_eq!(with(FeatPlacement::Artist), "Sub Focus ft. Alice Gold - Out the Blue");
+ /// assert_eq!(with(FeatPlacement::Title), "Sub Focus - Out the Blue (ft. Alice Gold)");
+ /// assert_eq!(with(FeatPlacement::Omit), "Sub Focus - Out the Blue");
+ /// ```
+ #[non_exhaustive]
+ FeatPlacement { Source => "source", Artist => "artist", Title => "title", Omit => "omit" }
+}
+
+string_enum! {
+ /// Joiners as written, or mapped to their canonical form (R11.5).
+ ///
+ /// ```
+ /// use trackparse::{format_track_with, parse, FormatOptions, JoinerStyle};
+ ///
+ /// let track = parse("Noisia & The Upbeats ft Tasha Baxter - Dead Limit");
+/// assert_eq!(format_track_with(&track, &FormatOptions::new()), track.input);
+ /// let options = FormatOptions::new().joiners(JoinerStyle::Canonical);
+ /// assert_eq!(
+ /// format_track_with(&track, &options),
+ /// "Noisia & The Upbeats feat. Tasha Baxter - Dead Limit"
+ /// );
+ /// ```
+ #[non_exhaustive]
+ JoinerStyle { Original => "original", Canonical => "canonical" }
+}
+
+string_enum! {
+ /// Whether [`format_track_with`](crate::format_track_with) writes the versions (R11.3).
+ ///
+ /// ```
+ /// use trackparse::{format_track_with, parse, FormatOptions, VersionsOption};
+ ///
+ /// let track = parse("Fox Stevenson - Bruises (Magnetude Remix)");
+ /// let options = FormatOptions::new().versions(VersionsOption::None);
+ /// assert_eq!(format_track_with(&track, &options), "Fox Stevenson - Bruises");
+ /// ```
+ #[non_exhaustive]
+ VersionsOption { All => "all", None => "none" }
+}
+
+#[allow(clippy::derivable_impls)] // the enum comes from a macro
+impl Default for ModeOption {
+ fn default() -> Self {
+ ModeOption::Auto
+ }
+}
+
+#[allow(clippy::derivable_impls)] // the enum comes from a macro
+impl Default for SplitAnd {
+ fn default() -> Self {
+ SplitAnd::Auto
+ }
+}
+
+#[allow(clippy::derivable_impls)] // the enum comes from a macro
+impl Default for FeatPlacement {
+ fn default() -> Self {
+ FeatPlacement::Source
+ }
+}
+
+#[allow(clippy::derivable_impls)] // the enum comes from a macro
+impl Default for JoinerStyle {
+ fn default() -> Self {
+ JoinerStyle::Original
+ }
+}
+
+#[allow(clippy::derivable_impls)] // the enum comes from a macro
+impl Default for VersionsOption {
+ fn default() -> Self {
+ VersionsOption::All
+ }
+}
+
+/// Extra vocabulary, added to the built-in word lists (R12). Keys are matched with ASCII
+/// lowercasing.
+///
+/// ```
+/// use trackparse::{parse_with, JunkKind, KeywordOptions, ParseOptions, VersionType};
+///
+/// let keywords = KeywordOptions::new()
+/// .version_head("rerub", VersionType::Remix)
+/// .junk("out now", JunkKind::Promo);
+/// let options = ParseOptions::new().keywords(keywords);
+/// let track = parse_with("Noisia - Stigma (Phace Rerub) [Out Now]", &options);
+/// assert_eq!(track.versions[0].version_type, VersionType::Remix);
+/// assert_eq!(track.versions[0].artists[0].name, "Phace");
+/// assert_eq!(track.junk[0].kind, JunkKind::Promo);
+/// ```
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
+#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
+#[cfg_attr(feature = "serde", serde(default, rename_all = "camelCase"))]
+#[non_exhaustive]
+pub struct KeywordOptions {
+ /// Extra version heads: word and the version type it means. A JSON object (`versionHeads`).
+ #[cfg_attr(feature = "serde", serde(with = "crate::serde_support::pairs"))]
+ pub version_heads: Vec<(String, VersionType)>,
+ /// Extra descriptor words (`Extended`, `Deluxe`).
+ pub descriptors: Vec,
+ /// Extra genre names.
+ pub genres: Vec,
+ /// Extra junk phrases: phrase and its kind. A JSON object.
+ #[cfg_attr(feature = "serde", serde(with = "crate::serde_support::pairs"))]
+ pub junk: Vec<(String, JunkKind)>,
+ /// Extra markers that introduce featured artists (`featMarkers` in JSON).
+ pub feat_markers: Vec,
+}
+
+impl KeywordOptions {
+ /// No extra words.
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Add a version head (`"rerub"` means [`VersionType::Remix`]).
+ pub fn version_head(mut self, key: impl Into, version_type: VersionType) -> Self {
+ self.version_heads.push((key.into(), version_type));
+ self
+ }
+
+ /// Add a descriptor word.
+ pub fn descriptor(mut self, word: impl Into) -> Self {
+ self.descriptors.push(word.into());
+ self
+ }
+
+ /// Add a genre name.
+ pub fn genre(mut self, word: impl Into) -> Self {
+ self.genres.push(word.into());
+ self
+ }
+
+ /// Add a junk phrase (`"free download"` is [`JunkKind::Promo`]).
+ pub fn junk(mut self, phrase: impl Into, kind: JunkKind) -> Self {
+ self.junk.push((phrase.into(), kind));
+ self
+ }
+
+ /// Add a marker that introduces featured artists.
+ pub fn feat_marker(mut self, marker: impl Into) -> Self {
+ self.feat_markers.push(marker.into());
+ self
+ }
+}
+
+/// Options of [`parse_with`](crate::parse_with), [`parse_artists_with`](crate::parse_artists_with)
+/// and [`Parser`](crate::Parser) (R12). The default is what [`parse`](crate::parse) uses.
+///
+/// Build one with the chained setters, or set the public fields on a default value.
+///
+/// ```
+/// use trackparse::{parse_with, ModeOption, ParseOptions, SplitAnd};
+///
+/// let options = ParseOptions::new()
+/// .mode(ModeOption::Youtube)
+/// .uploader("Noisia")
+/// .known_artists(["Chase & Status"])
+/// .split_and(SplitAnd::Never);
+/// let track = parse_with("Stigma (Official Video)", &options);
+/// assert_eq!(track.artists[0].name, "Noisia");
+/// assert_eq!(track.title, "Stigma");
+///
+/// let mut same = ParseOptions::default();
+/// same.mode = ModeOption::Youtube;
+/// same.uploader = Some("Noisia".into());
+/// same.known_artists = vec!["Chase & Status".into()];
+/// same.split_and = SplitAnd::Never;
+/// assert_eq!(same, options);
+/// ```
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
+#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
+#[cfg_attr(feature = "serde", serde(default, rename_all = "camelCase"))]
+#[non_exhaustive]
+pub struct ParseOptions {
+ /// The mode; default [`ModeOption::Auto`].
+ pub mode: ModeOption,
+ /// youtube mode: the channel name, used as the artist when the title has no separator
+ /// (R6.8).
+ #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
+ pub uploader: Option,
+ /// Names that must never be split (R7.3a): `Chase & Status`, `Above & Beyond`.
+ pub known_artists: Vec,
+ /// When `and` splits a credit list; default [`SplitAnd::Auto`].
+ pub split_and: SplitAnd,
+ /// Extra vocabulary.
+ #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
+ pub keywords: Option,
+}
+
+impl ParseOptions {
+ /// The default options.
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Set the mode.
+ pub fn mode(mut self, mode: ModeOption) -> Self {
+ self.mode = mode;
+ self
+ }
+
+ /// Set the uploader (the channel name, for youtube mode).
+ pub fn uploader(mut self, uploader: impl Into) -> Self {
+ self.uploader = Some(uploader.into());
+ self
+ }
+
+ /// Set the names that must never be split.
+ pub fn known_artists(mut self, names: I) -> Self
+ where
+ I: IntoIterator
- ,
+ S: Into,
+ {
+ self.known_artists = names.into_iter().map(Into::into).collect();
+ self
+ }
+
+ /// Set when `and` splits a credit list.
+ pub fn split_and(mut self, split_and: SplitAnd) -> Self {
+ self.split_and = split_and;
+ self
+ }
+
+ /// Set the extra vocabulary.
+ pub fn keywords(mut self, keywords: KeywordOptions) -> Self {
+ self.keywords = Some(keywords);
+ self
+ }
+}
+
+/// Options of [`format_track_with`](crate::format_track_with) (R11).
+///
+/// ```
+/// use trackparse::{format_track_with, parse, FeatPlacement, FormatOptions};
+///
+/// let track = parse("03. Sub Focus - Out the Blue ft. Alice Gold (Wilkinson Remix)");
+/// let options = FormatOptions::new()
+/// .feat(FeatPlacement::Artist)
+/// .feat_marker("feat.")
+/// .position(true);
+/// assert_eq!(
+/// format_track_with(&track, &options),
+/// "03. Sub Focus feat. Alice Gold - Out the Blue (Wilkinson Remix)"
+/// );
+/// ```
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
+#[cfg_attr(feature = "serde", serde(default, rename_all = "camelCase"))]
+#[non_exhaustive]
+pub struct FormatOptions {
+ /// Where featured artists go; default [`FeatPlacement::Source`] (where they were found).
+ pub feat: FeatPlacement,
+ /// Marker written in front of featured lists instead of the one in the input.
+ #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
+ pub feat_marker: Option,
+ /// Joiners as written or canonical; default [`JoinerStyle::Original`].
+ pub joiners: JoinerStyle,
+ /// Write the versions or not; default [`VersionsOption::All`].
+ pub versions: VersionsOption,
+ /// Write `prod.` credits; default `true`.
+ pub producers: bool,
+ /// Write the position in front; default `false`.
+ pub position: bool,
+}
+
+impl Default for FormatOptions {
+ fn default() -> Self {
+ FormatOptions {
+ feat: FeatPlacement::Source,
+ feat_marker: None,
+ joiners: JoinerStyle::Original,
+ versions: VersionsOption::All,
+ producers: true,
+ position: false,
+ }
+ }
+}
+
+impl FormatOptions {
+ /// The default options.
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Set where featured artists go.
+ pub fn feat(mut self, feat: FeatPlacement) -> Self {
+ self.feat = feat;
+ self
+ }
+
+ /// Set the marker written in front of featured lists.
+ pub fn feat_marker(mut self, marker: impl Into) -> Self {
+ self.feat_marker = Some(marker.into());
+ self
+ }
+
+ /// Set the joiner style.
+ pub fn joiners(mut self, joiners: JoinerStyle) -> Self {
+ self.joiners = joiners;
+ self
+ }
+
+ /// Set whether versions are written.
+ pub fn versions(mut self, versions: VersionsOption) -> Self {
+ self.versions = versions;
+ self
+ }
+
+ /// Set whether `prod.` credits are written.
+ pub fn producers(mut self, producers: bool) -> Self {
+ self.producers = producers;
+ self
+ }
+
+ /// Set whether the position is written in front.
+ pub fn position(mut self, position: bool) -> Self {
+ self.position = position;
+ self
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Resolved forms
+
+/// `options.mode` as the pipeline sees it. `Other` is any value that is neither missing nor one
+/// of the five names: JS then skips the R2.1 youtube detection but still detects filenames.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum Requested {
+ Auto,
+ Mode(Mode),
+ Other,
+}
+
+/// `options.splitAnd`: anything but `auto` / `never` (or missing) behaves as `always` in JS.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum SplitAndMode {
+ Auto,
+ Always,
+ Never,
+}
+
+/// `options.keywords` with the maps in JS `Object.entries` order. Types and kinds stay strings:
+/// JS passes any string value through to the output.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub(crate) struct Keywords {
+ pub version_heads: Vec<(String, String)>,
+ pub descriptors: Vec,
+ pub genres: Vec,
+ pub junk: Vec<(String, String)>,
+ pub feat_markers: Vec,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct Resolved {
+ pub mode: Requested,
+ pub uploader: Option,
+ pub known_artists: Vec,
+ pub split_and: SplitAndMode,
+ /// `None`: the default tables.
+ pub keywords: Option,
+}
+
+impl Default for Resolved {
+ fn default() -> Self {
+ Resolved {
+ mode: Requested::Auto,
+ uploader: None,
+ known_artists: Vec::new(),
+ split_and: SplitAndMode::Auto,
+ keywords: None,
+ }
+ }
+}
+
+/// A canonical array index (`"0"`, `"17"`; not `"01"`): JS lists such keys first, ascending.
+fn array_index(key: &str) -> Option {
+ if key.is_empty() || key.len() > 10 || !key.bytes().all(|b| b.is_ascii_digit()) {
+ return None;
+ }
+ if key.len() > 1 && key.starts_with('0') {
+ return None;
+ }
+ key.parse::().ok().filter(|n| *n <= 0xffff_fffe)
+}
+
+/// `Object.entries` order of an object built from `pairs`: a repeated key keeps its first place
+/// and takes the last value; integer-like keys come first in ascending order, then the others in
+/// insertion order.
+pub(crate) fn js_entries(pairs: &[(String, V)]) -> Vec<(String, V)> {
+ let mut unique: Vec<(String, V)> = Vec::with_capacity(pairs.len());
+ let mut index: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
+ for (k, v) in pairs {
+ match index.get(k.as_str()).and_then(|&i| unique.get_mut(i)) {
+ Some(slot) => slot.1 = v.clone(),
+ None => {
+ index.insert(k.as_str(), unique.len());
+ unique.push((k.clone(), v.clone()));
+ }
+ }
+ }
+ let mut ints: Vec<(u64, (String, V))> = Vec::new();
+ let mut rest: Vec<(String, V)> = Vec::new();
+ for pair in unique {
+ match array_index(&pair.0) {
+ Some(n) => ints.push((n, pair)),
+ None => rest.push(pair),
+ }
+ }
+ ints.sort_by_key(|(n, _)| *n);
+ ints.into_iter().map(|(_, p)| p).chain(rest).collect()
+}
+
+/// R0.8: option lists may be anything at runtime; only arrays of strings count.
+pub(crate) fn string_list(value: Option<&Json>) -> Vec {
+ match value {
+ Some(Json::Arr(items)) => {
+ items.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()
+ }
+ _ => Vec::new(),
+ }
+}
+
+/// R0.8: option maps may be anything at runtime; only plain objects' string values count.
+pub(crate) fn string_entries(value: Option<&Json>) -> Vec<(String, String)> {
+ match value {
+ Some(Json::Obj(entries)) => js_entries(entries)
+ .into_iter()
+ .filter_map(|(k, v)| v.as_str().map(|s| (k, s.to_string())))
+ .collect(),
+ _ => Vec::new(),
+ }
+}
+
+impl Keywords {
+ fn from_json(value: &Json) -> Keywords {
+ Keywords {
+ version_heads: string_entries(value.get("versionHeads")),
+ descriptors: string_list(value.get("descriptors")),
+ genres: string_list(value.get("genres")),
+ junk: string_entries(value.get("junk")),
+ feat_markers: string_list(value.get("featMarkers")),
+ }
+ }
+
+ fn from_typed(k: &KeywordOptions) -> Keywords {
+ let heads: Vec<(String, String)> =
+ k.version_heads.iter().map(|(key, t)| (key.clone(), t.as_str().to_string())).collect();
+ let junk: Vec<(String, String)> =
+ k.junk.iter().map(|(key, kind)| (key.clone(), kind.as_str().to_string())).collect();
+ Keywords {
+ version_heads: js_entries(&heads),
+ descriptors: k.descriptors.clone(),
+ genres: k.genres.clone(),
+ junk: js_entries(&junk),
+ feat_markers: k.feat_markers.clone(),
+ }
+ }
+}
+
+impl Resolved {
+ /// Loose JSON options, with the JS fallbacks.
+ pub(crate) fn from_json(options: &Json) -> Resolved {
+ if options.as_object().is_none() {
+ return Resolved::default(); // safeOptions: not an object
+ }
+ let mode = match options.get("mode") {
+ None | Some(Json::Null) => Requested::Auto, // `options.mode ?? "auto"`
+ Some(Json::Str(s)) if s == "auto" => Requested::Auto,
+ Some(Json::Str(s)) => Mode::from_name(s).map_or(Requested::Other, Requested::Mode),
+ Some(_) => Requested::Other,
+ };
+ let split_and = match options.get("splitAnd") {
+ None | Some(Json::Null) => SplitAndMode::Auto, // `options?.splitAnd ?? "auto"`
+ Some(Json::Str(s)) if s == "auto" => SplitAndMode::Auto,
+ Some(Json::Str(s)) if s == "never" => SplitAndMode::Never,
+ Some(_) => SplitAndMode::Always,
+ };
+ // `options?.keywords ? … : baseTables`, then `isRecord`: only a plain object adds words.
+ let keywords = match options.get("keywords") {
+ Some(k @ Json::Obj(_)) => Some(Keywords::from_json(k)),
+ _ => None,
+ };
+ Resolved {
+ mode,
+ uploader: options.get("uploader").and_then(Json::as_str).map(str::to_string),
+ known_artists: string_list(options.get("knownArtists")),
+ split_and,
+ keywords,
+ }
+ }
+
+ pub(crate) fn from_typed(options: &ParseOptions) -> Resolved {
+ Resolved {
+ mode: match options.mode {
+ ModeOption::Auto => Requested::Auto,
+ ModeOption::Clean => Requested::Mode(Mode::Clean),
+ ModeOption::Youtube => Requested::Mode(Mode::Youtube),
+ ModeOption::Filename => Requested::Mode(Mode::Filename),
+ ModeOption::Tracklist => Requested::Mode(Mode::Tracklist),
+ },
+ uploader: options.uploader.clone(),
+ known_artists: options.known_artists.clone(),
+ split_and: match options.split_and {
+ SplitAnd::Auto => SplitAndMode::Auto,
+ SplitAnd::Always => SplitAndMode::Always,
+ SplitAnd::Never => SplitAndMode::Never,
+ },
+ keywords: options.keywords.as_ref().map(Keywords::from_typed),
+ }
+ }
+}
+
+/// `options.feat` as R11 reads it: an unknown value places featured artists nowhere.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum FeatMode {
+ Source,
+ Artist,
+ Title,
+ Omit,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct ResolvedFormat {
+ pub feat: FeatMode,
+ pub feat_marker: Option,
+ pub canonical: bool,
+ pub versions: bool,
+ pub producers: bool,
+ pub position: bool,
+}
+
+/// JS truthiness of a JSON value.
+fn truthy(v: &Json) -> bool {
+ match v {
+ Json::Null => false,
+ Json::Bool(b) => *b,
+ Json::Num(n) => *n != 0.0 && !n.is_nan(),
+ Json::Str(s) => !s.is_empty(),
+ Json::Arr(_) | Json::Obj(_) => true,
+ }
+}
+
+/// JS `String(value)` (what a template literal does with a non-string `featMarker`).
+fn js_string(v: &Json) -> String {
+ match v {
+ Json::Null => "null".to_string(),
+ Json::Bool(b) => b.to_string(),
+ Json::Num(n) if n.is_nan() => "NaN".to_string(),
+ Json::Num(n) if n.is_infinite() => {
+ (if *n > 0.0 { "Infinity" } else { "-Infinity" }).to_string()
+ }
+ Json::Num(_) => v.write(),
+ Json::Str(s) => s.clone(),
+ // Array.prototype.join: null elements are empty.
+ Json::Arr(items) => items
+ .iter()
+ .map(|i| if matches!(i, Json::Null) { String::new() } else { js_string(i) })
+ .collect::>()
+ .join(","),
+ Json::Obj(_) => "[object Object]".to_string(),
+ }
+}
+
+impl ResolvedFormat {
+ /// Loose JSON format options, with the JS fallbacks (`??` for missing and `null`).
+ pub(crate) fn from_json(o: &Json) -> ResolvedFormat {
+ let get = |key: &str| match o.get(key) {
+ Some(Json::Null) | None => None,
+ Some(v) => Some(v),
+ };
+ ResolvedFormat {
+ feat: match get("feat") {
+ None => FeatMode::Source,
+ Some(Json::Str(s)) if s == "source" => FeatMode::Source,
+ Some(Json::Str(s)) if s == "artist" => FeatMode::Artist,
+ Some(Json::Str(s)) if s == "title" => FeatMode::Title,
+ Some(_) => FeatMode::Omit,
+ },
+ // `o.featMarker !== undefined`: an explicit null is rendered as "null".
+ feat_marker: o.get("featMarker").map(js_string),
+ canonical: get("joiners").and_then(Json::as_str) == Some("canonical"),
+ versions: get("versions").map_or(true, |v| v.as_str() == Some("all")),
+ producers: get("producers").map_or(true, truthy),
+ position: get("position").is_some_and(truthy),
+ }
+ }
+
+ pub(crate) fn from_typed(o: &FormatOptions) -> ResolvedFormat {
+ ResolvedFormat {
+ feat: match o.feat {
+ FeatPlacement::Source => FeatMode::Source,
+ FeatPlacement::Artist => FeatMode::Artist,
+ FeatPlacement::Title => FeatMode::Title,
+ FeatPlacement::Omit => FeatMode::Omit,
+ },
+ feat_marker: o.feat_marker.clone(),
+ canonical: o.joiners == JoinerStyle::Canonical,
+ versions: o.versions == VersionsOption::All,
+ producers: o.producers,
+ position: o.position,
+ }
+ }
+}
diff --git a/rust/src/parser.rs b/rust/src/parser.rs
new file mode 100644
index 0000000..9761a9e
--- /dev/null
+++ b/rust/src/parser.rs
@@ -0,0 +1,243 @@
+//! Pipeline: R1 → R2 → R4 → R3/R6 → R7 → R8 → R9, plus R10 parse_artists.
+
+use std::collections::HashSet;
+use std::sync::{Arc, OnceLock};
+
+use crate::artists::parse_artist_side;
+use crate::assemble::{dedup_artists, full_title_of, to_version};
+use crate::context::{known_keys, warn, Ctx};
+use crate::mode::{prelude, Piece, Prelude};
+use crate::normalize::normalize;
+use crate::options::Resolved;
+use crate::prefix::strip_prefixes;
+use crate::scanner::{scan, split_at_spaced_dashes, trim_skel, Skel};
+use crate::separator::{find_separator, SeparatorInput};
+use crate::tables::{tables_for, Tables};
+use crate::title::{add_peeled, parse_title_side, Extracted};
+use crate::types::{Artist, ArtistSource, Flags, Mode, RawJunk, RawTrack, Warning};
+use crate::words::{chars, js_trim_end};
+
+/// Offset used for uploader text so it sorts before everything from the input.
+const UPLOADER_BASE: i64 = -1_000_000_000;
+
+fn skel_of(piece: &Piece, ctx: &mut Ctx<'_>) -> Skel {
+ let (skel, unbalanced) = scan(&piece.text, piece.base);
+ if unbalanced {
+ warn(ctx, Warning::UnbalancedBrackets);
+ }
+ trim_skel(&skel)
+}
+
+/// R6.8: uploader minus a trailing ` - Topic` and `VEVO`.
+fn uploader_skel(uploader: Option<&str>) -> Option {
+ let mut u = normalize(uploader?);
+ if let Some(rest) = u.strip_suffix(" - Topic") {
+ u = rest.to_string();
+ }
+ if let Some(rest) = u.strip_suffix("VEVO") {
+ u = js_trim_end(rest).to_string();
+ }
+ if u.is_empty() {
+ return None;
+ }
+ Some(scan(&chars(&u), UPLOADER_BASE).0)
+}
+
+/// Resolved options with the tables built once (JS `createParser` / `createListParser`).
+#[derive(Clone)]
+pub(crate) struct Engine {
+ options: Resolved,
+ tables: Arc,
+ known_keys: HashSet,
+ known_max_len: usize,
+}
+
+/// The R1, R2 and R4 stage of `run`, kept so the tracklist probe's work is not redone.
+struct Staged<'a> {
+ engine: &'a Engine,
+ ctx: Ctx<'a>,
+ pre: Prelude,
+ track: RawTrack,
+ /// The skeleton after R4; `None` when the input is empty after R1 (R9.5: `track` is final).
+ working: Option,
+}
+
+fn by_pos(mut items: Vec, pos: impl Fn(&T) -> i64) -> Vec {
+ items.sort_by_key(|item| pos(item)); // stable, like the JS sort
+ items
+}
+
+impl Engine {
+ pub(crate) fn new(options: Resolved) -> Engine {
+ let tables = tables_for(options.keywords.as_ref());
+ let (known_keys, known_max_len) = known_keys(&options.known_artists);
+ Engine { options, tables, known_keys, known_max_len }
+ }
+
+ /// The engine behind `parse` / `parse_artists` without options.
+ pub(crate) fn shared() -> &'static Engine {
+ static DEFAULT: OnceLock = OnceLock::new();
+ DEFAULT.get_or_init(|| Engine::new(Resolved::default()))
+ }
+
+ fn ctx(&self) -> Ctx<'_> {
+ Ctx {
+ t: &self.tables,
+ known_keys: &self.known_keys,
+ known_max_len: self.known_max_len,
+ split_and: self.options.split_and,
+ warnings: Vec::new(),
+ list_seq: 0,
+ }
+ }
+
+ fn stage(&self, input: &str) -> Staged<'_> {
+ let mut ctx = self.ctx();
+ let norm = normalize(input);
+ let pre = prelude(&norm, self.options.mode, &mut ctx);
+ let mut track = RawTrack::empty(input, pre.mode);
+ if norm.is_empty() {
+ return Staged { engine: self, ctx, pre, track, working: None }; // R9.5
+ }
+
+ // R4
+ let prefix = strip_prefixes(&pre.working.text, pre.working.base, pre.mode, &ctx);
+ track.timestamp = prefix.timestamp;
+ track.position = prefix.position;
+ let working = skel_of(&Piece { text: prefix.rest, base: prefix.base }, &mut ctx);
+ Staged { engine: self, ctx, pre, track, working: Some(working) }
+ }
+
+ pub(crate) fn run(&self, input: &str, list_context: bool) -> RawTrack {
+ finish(self.stage(input), list_context)
+ }
+
+ /// R10
+ pub(crate) fn run_artists(&self, input: &str) -> Vec {
+ let mut ctx = self.ctx();
+ let norm = normalize(input);
+ if norm.is_empty() {
+ return Vec::new();
+ }
+ let side = parse_artist_side(&scan(&chars(&norm), 0).0, &mut ctx);
+ let mut artists = dedup_artists(side.credits);
+ for a in &mut artists {
+ a.source = ArtistSource::Artist;
+ }
+ artists
+ }
+
+ /// R1, R2 and R4 only, as `run` does them: no artist/title parsing. `finish` completes the
+ /// parse from the same stage, so a probed line is not normalized twice.
+ pub(crate) fn probe(&self, input: &str) -> LineProbe<'_> {
+ let staged = self.stage(input);
+ LineProbe {
+ position: staged.track.position.is_some(),
+ spaced_dash: staged.pre.pipe_title.is_none()
+ && staged
+ .working
+ .as_ref()
+ .is_some_and(|w| split_at_spaced_dashes(w, true).len() >= 2),
+ empty: staged.working.is_none(),
+ staged,
+ }
+ }
+}
+
+/// R6–R9 on a staged input.
+fn finish(st: Staged<'_>, list_context: bool) -> RawTrack {
+ let Staged { engine, mut ctx, pre, mut track, working } = st;
+ let Some(working) = working else { return track };
+
+ let mut out = Extracted::default();
+ let artist_skel: Option;
+ let title_skel: Skel;
+ let relaxed: bool;
+ if let Some(pipe_title) = &pre.pipe_title {
+ // R2.4 step 3: `artist | title`, R6 skipped.
+ title_skel = skel_of(pipe_title, &mut ctx);
+ artist_skel = (!working.is_empty()).then_some(working);
+ relaxed = artist_skel.is_some();
+ } else {
+ let sep = find_separator(
+ SeparatorInput {
+ skel: &working,
+ mode: pre.mode,
+ uploader: uploader_skel(engine.options.uploader.as_deref()),
+ list_context,
+ },
+ &mut ctx,
+ );
+ add_peeled(&mut out, sep.peeled);
+ artist_skel = sep.artist;
+ title_skel = sep.title;
+ relaxed = sep.split;
+ }
+
+ let artist_side =
+ artist_skel.as_ref().map(|s| parse_artist_side(s, &mut ctx)).unwrap_or_default();
+ let title_side =
+ parse_title_side(&title_skel, relaxed, pre.mode == Mode::Youtube, &mut out, &mut ctx);
+
+ // R9
+ let versions = by_pos(out.versions, |v| v.pos);
+ if versions.iter().any(|v| v.ambiguous_mix) {
+ warn(&mut ctx, Warning::AmbiguousMixCredit);
+ }
+ let mut credits = artist_side.credits;
+ credits.extend(by_pos(out.credits, |c| c.pos));
+ track.artists = dedup_artists(credits);
+ track.title = title_side.title;
+ track.versions = versions.into_iter().map(to_version).collect();
+ track.full_title = full_title_of(&track.title, &track.versions);
+ // R9.6: the first year in text order.
+ let mut years = artist_side.years;
+ years.extend(out.years);
+ track.year = by_pos(years, |y| y.pos).first().map(|y| y.year);
+ track.flags = Flags {
+ explicit: out.explicit || artist_side.explicit,
+ clean: out.clean || artist_side.clean,
+ unknown_artist: artist_side.unknown_artist || out.unknown_artist,
+ unknown_title: title_side.unknown_title,
+ };
+ let mut junk = pre.junk;
+ junk.extend(artist_side.junk);
+ junk.extend(out.junk);
+ track.junk =
+ by_pos(junk, |j| j.pos).into_iter().map(|j| RawJunk { raw: j.raw, kind: j.kind }).collect();
+ track.warnings = ctx.warnings;
+ track
+}
+
+/// Facts about a line's prefix and separator search, for the tracklist module (R13.4.2, R13.5).
+pub(crate) struct LineProbe<'a> {
+ /// R4.2 took a position.
+ pub position: bool,
+ /// The skeleton R6 searches (after R2 and R4) has a spaced dash (R6.1).
+ pub spaced_dash: bool,
+ /// The input is empty after R1.
+ pub empty: bool,
+ staged: Staged<'a>,
+}
+
+impl LineProbe<'_> {
+ /// The parse of the probed input (R6–R9 only).
+ pub(crate) fn finish(self, list_context: bool) -> RawTrack {
+ finish(self.staged, list_context)
+ }
+}
+
+/// Internal: parsing hooks for the tracklist module, with the options compiled once.
+pub(crate) struct ListParser {
+ engine: Engine,
+}
+
+impl ListParser {
+ pub(crate) fn new(options: Resolved) -> ListParser {
+ ListParser { engine: Engine::new(options) }
+ }
+
+ pub(crate) fn probe(&self, input: &str) -> LineProbe<'_> {
+ self.engine.probe(input)
+ }
+}
diff --git a/rust/src/prefix.rs b/rust/src/prefix.rs
new file mode 100644
index 0000000..db8e608
--- /dev/null
+++ b/rust/src/prefix.rs
@@ -0,0 +1,146 @@
+//! R4: leading timestamp and track-position prefixes.
+
+use crate::context::{match_known_at, Ctx};
+use crate::digits::{digit_run, digits_value, two_digits_up_to_59};
+use crate::scanner::{has_spaced_dash, scan};
+use crate::types::{Mode, Position, Timestamp};
+use crate::words::{at, string, sub, tail, utf16_off};
+
+pub(crate) struct PrefixResult {
+ pub rest: Vec,
+ /// Absolute offset of `rest`.
+ pub base: i64,
+ pub timestamp: Option,
+ pub position: Option,
+}
+
+struct TimeMatch {
+ raw: String,
+ seconds: u64,
+ end: usize,
+}
+
+/// `H:MM:SS`, `HH:MM:SS`, `M:SS`, `MM:SS` starting at `at_`.
+fn match_time(s: &[char], at_: usize) -> Option {
+ let lead = digit_run(s, at_);
+ if !(1..=2).contains(&lead) || at(s, at_ + lead) != Some(':') {
+ return None;
+ }
+ let first = u64::from(digits_value(sub(s, at_, at_ + lead)));
+ let mid = u64::from(two_digits_up_to_59(s, at_ + lead + 1)?);
+ let after_mid = at_ + lead + 3;
+ if at(s, after_mid) == Some(':') {
+ if let Some(sec) = two_digits_up_to_59(s, after_mid + 1) {
+ let end = after_mid + 3;
+ return Some(TimeMatch {
+ raw: string(sub(s, at_, end)),
+ seconds: first * 3600 + mid * 60 + u64::from(sec),
+ end,
+ });
+ }
+ }
+ if lead == 2 && first > 59 {
+ return None; // MM is 00–59
+ }
+ Some(TimeMatch {
+ raw: string(sub(s, at_, after_mid)),
+ seconds: first * 60 + mid,
+ end: after_mid,
+ })
+}
+
+/// After a prefix: skip one space, then an optional `- ` (spaced dash).
+fn skip_space_and_dash(s: &[char], at_: usize) -> usize {
+ let mut i = at_;
+ if at(s, i) == Some(' ') {
+ i += 1;
+ }
+ if at(s, i) == Some('-') && at(s, i + 1) == Some(' ') {
+ i += 2;
+ }
+ i
+}
+
+/// R4.1
+fn match_timestamp(s: &[char]) -> Option<(Timestamp, usize)> {
+ let bracket = match at(s, 0) {
+ Some('[') => Some(']'),
+ Some('(') => Some(')'),
+ _ => None,
+ };
+ let t = match_time(s, usize::from(bracket.is_some()))?;
+ let mut end = t.end;
+ if bracket.is_some() {
+ if at(s, end) != bracket {
+ return None;
+ }
+ end += 1;
+ }
+ if end < s.len() && at(s, end) != Some(' ') {
+ return None;
+ }
+ Some((Timestamp { raw: t.raw, seconds: t.seconds }, skip_space_and_dash(s, end)))
+}
+
+fn contains_spaced_dash(s: &[char]) -> bool {
+ has_spaced_dash(&scan(s, 0).0.text)
+}
+
+/// R4.2: end offset of the position prefix, or `None`. Forms are tried (a), (b), (c), (d)/(e).
+fn match_position(s: &[char], mode: Mode) -> Option {
+ let n = digit_run(s, 0);
+ if !(1..=3).contains(&n) {
+ return None;
+ }
+ let c = at(s, n);
+ let zero_padded = at(s, 0) == Some('0') && n >= 2;
+ // (a) `01. `, `1) `
+ if (c == Some('.') || c == Some(')')) && (at(s, n + 1) == Some(' ') || n + 1 == s.len()) {
+ return Some(skip_space_and_dash(s, n + 1));
+ }
+ // (b) `01 `: a position in every mode.
+ if zero_padded && c == Some(' ') {
+ return Some(skip_space_and_dash(s, n));
+ }
+ // (c) `3 - Artist - Title`; in filename mode `N - ` is always a position (`311 - Amber.mp3`).
+ if c == Some(' ') && at(s, n + 1) == Some('-') && at(s, n + 2) == Some(' ') {
+ if mode == Mode::Filename || contains_spaced_dash(tail(s, n + 3)) {
+ return Some(n + 3);
+ }
+ return None;
+ }
+ if mode == Mode::Filename {
+ // (e) `01-Track`, `03_name`, `01.Track`
+ if matches!(c, Some('-' | '_' | '.')) && at(s, n + 1).is_some_and(|ch| ch != ' ') {
+ return Some(n + 1);
+ }
+ // (e) `3 My Song.mp3`: only when the remainder has no spaced dash.
+ if c == Some(' ') && !contains_spaced_dash(tail(s, n + 1)) {
+ return Some(skip_space_and_dash(s, n));
+ }
+ }
+ // (d) `2 Unlimited`, `50 Cent`: never a position outside filename mode.
+ None
+}
+
+pub(crate) fn strip_prefixes(text: &[char], base: i64, mode: Mode, ctx: &Ctx<'_>) -> PrefixResult {
+ let mut rest: &[char] = text;
+ let mut offset = base;
+ let mut timestamp = None;
+ let mut position = None;
+
+ if let Some((ts, end)) = match_timestamp(rest) {
+ timestamp = Some(ts);
+ offset += utf16_off(sub(rest, 0, end));
+ rest = tail(rest, end);
+ }
+ if match_known_at(rest, 0, ctx, Some('-')) == 0 {
+ if let Some(end) = match_position(rest, mode).filter(|&end| end < rest.len()) {
+ let digits = sub(rest, 0, digit_run(rest, 0));
+ position = Some(Position { raw: string(digits), number: digits_value(digits) });
+ offset += utf16_off(sub(rest, 0, end));
+ rest = tail(rest, end);
+ }
+ }
+ PrefixResult { rest: rest.to_vec(), base: offset, timestamp, position }
+}
diff --git a/rust/src/scanner.rs b/rust/src/scanner.rs
new file mode 100644
index 0000000..5a83873
--- /dev/null
+++ b/rust/src/scanner.rs
@@ -0,0 +1,274 @@
+//! R3: top-level group scanner and skeleton.
+//!
+//! A `Skel` is a skeleton (code points) plus, for every code point, its absolute offset in the
+//! normalized input. Offsets are in UTF-16 units, as in the JS reference, so that every
+//! "order of appearance" comparison gives the same answer. Groups are looked up by the offset of
+//! their placeholder, so any slice of a skeleton still knows which groups it contains.
+
+use std::collections::{HashMap, HashSet};
+use std::rc::Rc;
+
+use crate::types::VersionDelimiter;
+use crate::words::{at, before, collapse_chars, is_whitespace, string, sub};
+
+/// R3.4 placeholder code point.
+pub(crate) const PH: char = '\u{e000}';
+
+#[derive(Debug, Clone)]
+pub(crate) struct Group {
+ pub open: VersionDelimiter,
+ /// R3.5: inner text, trimmed and whitespace-collapsed.
+ pub inner: String,
+ /// The group exactly as written, brackets included.
+ pub raw: String,
+ /// Absolute offset of the opener.
+ pub pos: i64,
+}
+
+pub(crate) type Groups = Rc>;
+
+#[derive(Debug, Clone)]
+pub(crate) struct Skel {
+ pub text: Vec,
+ pub pos: Vec,
+ pub groups: Groups,
+}
+
+fn closer_of(ch: char) -> Option {
+ match ch {
+ '(' => Some(')'),
+ '[' => Some(']'),
+ '{' => Some('}'),
+ _ => None,
+ }
+}
+
+fn delimiter_of(ch: Option) -> VersionDelimiter {
+ match ch {
+ Some('[') => VersionDelimiter::Square,
+ Some('{') => VersionDelimiter::Curly,
+ _ => VersionDelimiter::Paren,
+ }
+}
+
+/// R3.1–R3.5: scan `s` (whose first unit sits at absolute offset `base`). The second value is
+/// "unbalanced" (R3.3).
+pub(crate) fn scan(s: &[char], base: i64) -> (Skel, bool) {
+ // Absolute offset of every code point, plus one entry for the end of the string.
+ let mut offsets: Vec = Vec::with_capacity(s.len() + 1);
+ let mut off = base;
+ for ch in s {
+ offsets.push(off);
+ off += ch.len_utf16() as i64;
+ }
+ offsets.push(off);
+ let offset_at = |i: usize| offsets.get(i).copied().unwrap_or(off);
+
+ let mut text: Vec = Vec::with_capacity(s.len());
+ let mut pos: Vec = Vec::with_capacity(s.len());
+ let mut groups: HashMap = HashMap::new();
+ let mut stack: Vec = Vec::new();
+ let mut group_start = 0usize;
+ for (i, &ch) in s.iter().enumerate() {
+ if stack.is_empty() {
+ if let Some(closer) = closer_of(ch) {
+ stack.push(closer);
+ group_start = i;
+ } else {
+ text.push(ch);
+ pos.push(offset_at(i));
+ }
+ continue;
+ }
+ if let Some(closer) = closer_of(ch) {
+ stack.push(closer);
+ } else if stack.last() == Some(&ch) {
+ stack.pop();
+ if stack.is_empty() {
+ add_group(s, group_start, i + 1, true, &offset_at, &mut groups);
+ text.push(PH);
+ pos.push(offset_at(group_start));
+ }
+ }
+ // R3.2: a non-matching closer is literal text inside the group.
+ }
+ let unbalanced = !stack.is_empty();
+ if unbalanced {
+ // R3.3: the group runs to the end of the string.
+ add_group(s, group_start, s.len(), false, &offset_at, &mut groups);
+ text.push(PH);
+ pos.push(offset_at(group_start));
+ }
+ (Skel { text, pos, groups: Rc::new(groups) }, unbalanced)
+}
+
+fn add_group(
+ s: &[char],
+ start: usize,
+ end: usize,
+ closed: bool,
+ offset_at: &dyn Fn(usize) -> i64,
+ groups: &mut HashMap,
+) {
+ let inner = sub(s, start + 1, if closed { end.saturating_sub(1) } else { end });
+ let pos = offset_at(start);
+ groups.insert(
+ pos,
+ Group {
+ open: delimiter_of(at(s, start)),
+ inner: collapse_chars(inner),
+ raw: string(sub(s, start, end)),
+ pos,
+ },
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Skeleton operations
+
+impl Skel {
+ pub fn len(&self) -> usize {
+ self.text.len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.text.is_empty()
+ }
+}
+
+pub(crate) fn slice_skel(s: &Skel, start: usize, end: usize) -> Skel {
+ let a = start.min(s.text.len());
+ let b = end.min(s.text.len()).max(a);
+ Skel {
+ text: sub(&s.text, a, b).to_vec(),
+ pos: s.pos.get(a..b.min(s.pos.len())).unwrap_or(&[]).to_vec(),
+ groups: Rc::clone(&s.groups),
+ }
+}
+
+/// `slice_skel(s, start)` to the end.
+pub(crate) fn slice_from(s: &Skel, start: usize) -> Skel {
+ slice_skel(s, start, s.text.len())
+}
+
+pub(crate) fn trim_skel(s: &Skel) -> Skel {
+ let mut a = 0;
+ let mut b = s.text.len();
+ while a < b && is_whitespace(at(&s.text, a)) {
+ a += 1;
+ }
+ while b > a && is_whitespace(before(&s.text, b)) {
+ b -= 1;
+ }
+ slice_skel(s, a, b)
+}
+
+pub(crate) fn concat_skel(a: &Skel, b: &Skel) -> Skel {
+ let mut text = a.text.clone();
+ text.extend_from_slice(&b.text);
+ let mut pos = a.pos.clone();
+ pos.extend_from_slice(&b.pos);
+ Skel { text, pos, groups: Rc::clone(&a.groups) }
+}
+
+/// The group behind the placeholder at `index`, if it is one.
+pub(crate) fn group_at(s: &Skel, index: usize) -> Option<&Group> {
+ if at(&s.text, index) != Some(PH) {
+ return None;
+ }
+ s.groups.get(s.pos.get(index)?)
+}
+
+/// Groups in the skeleton, left to right, with their unit index.
+pub(crate) fn groups_of(s: &Skel) -> Vec<(usize, &Group)> {
+ (0..s.text.len()).filter_map(|i| group_at(s, i).map(|g| (i, g))).collect()
+}
+
+pub(crate) fn has_group(s: &Skel) -> bool {
+ s.text.contains(&PH)
+}
+
+/// Substitute groups back (R3.4 reassembly). Whitespace is not touched.
+pub(crate) fn render_skel(s: &Skel) -> String {
+ let mut out = String::new();
+ for (i, &ch) in s.text.iter().enumerate() {
+ match group_at(s, i) {
+ Some(g) => out.push_str(&g.raw),
+ None => out.push(ch),
+ }
+ }
+ out
+}
+
+/// Absolute offset of the first unit (or `fallback` for an empty skeleton).
+pub(crate) fn start_pos(s: &Skel, fallback: i64) -> i64 {
+ s.pos.first().copied().unwrap_or(fallback)
+}
+
+/// Remove the placeholders of the given groups.
+pub(crate) fn remove_groups(s: &Skel, remove: &HashSet) -> Skel {
+ if remove.is_empty() {
+ return s.clone();
+ }
+ let mut text = Vec::with_capacity(s.text.len());
+ let mut pos = Vec::with_capacity(s.pos.len());
+ for (&ch, &p) in s.text.iter().zip(s.pos.iter()) {
+ if ch == PH && remove.contains(&p) {
+ continue;
+ }
+ text.push(ch);
+ pos.push(p);
+ }
+ Skel { text, pos, groups: Rc::clone(&s.groups) }
+}
+
+/// R6.1: `-` with a space immediately on both sides.
+pub(crate) fn is_spaced_dash_at(text: &[char], i: usize) -> bool {
+ at(text, i) == Some('-') && before(text, i) == Some(' ') && at(text, i + 1) == Some(' ')
+}
+
+pub(crate) fn has_spaced_dash(text: &[char]) -> bool {
+ (1..text.len().saturating_sub(1)).any(|i| is_spaced_dash_at(text, i))
+}
+
+#[derive(Debug, Clone)]
+pub(crate) struct Segment {
+ pub skel: Skel,
+ /// Trimmed range inside the parent skeleton.
+ pub start: usize,
+ pub end: usize,
+}
+
+fn trimmed_segment(s: &Skel, start: usize, end: usize) -> Segment {
+ let mut a = start;
+ let mut b = start.max(end);
+ while a < b && is_whitespace(at(&s.text, a)) {
+ a += 1;
+ }
+ while b > a && is_whitespace(before(&s.text, b)) {
+ b -= 1;
+ }
+ Segment { skel: slice_skel(s, a, b), start: a, end: b }
+}
+
+/// R6.1 / R8.2: split a skeleton at every spaced dash into trimmed segments. With
+/// `allow_leading`, a string starting with `- ` yields an empty first segment (R6.3).
+pub(crate) fn split_at_spaced_dashes(s: &Skel, allow_leading: bool) -> Vec {
+ let mut segments = Vec::new();
+ let t = &s.text;
+ let mut start = 0usize;
+ if allow_leading && at(t, 0) == Some('-') && at(t, 1) == Some(' ') {
+ segments.push(Segment { skel: slice_skel(s, 0, 0), start: 0, end: 0 });
+ start = 2;
+ }
+ let mut i = start.max(1);
+ while i + 1 < t.len() {
+ if is_spaced_dash_at(t, i) {
+ segments.push(trimmed_segment(s, start, i - 1));
+ start = i + 2;
+ }
+ i += 1;
+ }
+ segments.push(trimmed_segment(s, start, t.len()));
+ segments
+}
diff --git a/rust/src/separator.rs b/rust/src/separator.rs
new file mode 100644
index 0000000..c6125f3
--- /dev/null
+++ b/rust/src/separator.rs
@@ -0,0 +1,289 @@
+//! R6: artist/title separator, including R6.2 suffix peeling (shared with R8.2).
+
+use crate::classify::{classify, Classification, Flag, Site, VersionDraft};
+use crate::context::{is_known_artist, warn, Ctx};
+use crate::scanner::{
+ concat_skel, has_group, render_skel, slice_from, slice_skel, split_at_spaced_dashes, start_pos,
+ trim_skel, Segment, Skel, PH,
+};
+use crate::types::{ArtistSource, Mode, VersionDelimiter, Warning};
+use crate::words::{
+ at, before, collapse_chars, in_vocab, is_letter_at, is_letter_before, is_upper_at,
+ is_whitespace, split_words_chars, tail, year_of,
+};
+
+/// The classifications R6.2 / R8.2 can peel.
+#[derive(Debug, Clone)]
+pub(crate) enum Peelable {
+ Junk(String),
+ Flag(Flag),
+ Year(u32),
+ Versions(Vec),
+}
+
+#[derive(Debug, Clone)]
+pub(crate) struct Peeled {
+ pub cls: Peelable,
+ pub raw: String,
+ pub pos: i64,
+}
+
+/// R6.2 classification of a bare dash segment: placeholders make it Unknown.
+fn classify_segment(seg: &Skel, ctx: &mut Ctx<'_>) -> Classification {
+ if has_group(seg) {
+ return Classification::Unknown;
+ }
+ let text = collapse_chars(&seg.text);
+ let site = Site {
+ source: ArtistSource::Title,
+ delimiter: VersionDelimiter::Dash,
+ pos: start_pos(seg, 0),
+ };
+ classify(&text, site, ctx)
+}
+
+fn peelable(c: Classification) -> Option {
+ match c {
+ Classification::Junk(kind) => Some(Peelable::Junk(kind)),
+ Classification::Flag(flag) => Some(Peelable::Flag(flag)),
+ Classification::Year(year) => Some(Peelable::Year(year)),
+ Classification::Versions(versions) => Some(Peelable::Versions(versions)),
+ Classification::Feat(_) | Classification::Producer(_) | Classification::Unknown => None,
+ }
+}
+
+/// R6.2 / R8.2: peel classifiable suffixes off the right end. `relaxed` drops conditions
+/// (i)–(iv) (R8.2 with an artist side). Returns the remaining segments and the peeled
+/// suffixes, left to right.
+pub(crate) fn peel_suffixes(
+ segments: Vec,
+ relaxed: bool,
+ ctx: &mut Ctx<'_>,
+) -> (Vec, Vec) {
+ let mut remaining = segments;
+ let mut peeled: Vec = Vec::new();
+ while remaining.len() >= 2 {
+ let Some(last) = remaining.last() else { break };
+ let Some(cls) = peelable(classify_segment(&last.skel, ctx)) else { break };
+ let words = split_words_chars(&last.skel.text);
+ // (ii) does not apply to prefix-form versions (`Andy C b2b Hedex - Live at Printworks`).
+ let prefix_form =
+ matches!(&cls, Peelable::Versions(vs) if vs.iter().all(|v| v.prefix_form));
+ let ok = relaxed
+ || remaining.len() > 2
+ || (words.len() >= 2 && !prefix_form)
+ || words.iter().any(|w| year_of(w).is_some())
+ || matches!(cls, Peelable::Junk(_));
+ if !ok {
+ break;
+ }
+ peeled.push(Peeled {
+ cls,
+ raw: collapse_chars(&last.skel.text),
+ pos: start_pos(&last.skel, 0),
+ });
+ remaining.pop();
+ }
+ peeled.reverse();
+ (remaining, peeled)
+}
+
+pub(crate) struct SeparatorResult {
+ pub artist: Option,
+ pub title: Skel,
+ /// A separator split the string (R6.3–R6.7): R8.2 peels without conditions.
+ pub split: bool,
+ pub peeled: Vec,
+}
+
+pub(crate) struct SeparatorInput<'a> {
+ pub skel: &'a Skel,
+ pub mode: Mode,
+ pub uploader: Option,
+ /// R13.4.2 list context (internal, set only by the tracklist module): enables the R6.10
+ /// tight `letter-Uppercase` dash in tracklist mode.
+ pub list_context: bool,
+}
+
+fn non_empty(s: &Skel) -> Option {
+ let t = trim_skel(s);
+ (!t.is_empty()).then_some(t)
+}
+
+fn split_at(s: &Skel, cut_start: usize, cut_end: usize) -> (Option, Skel) {
+ (non_empty(&slice_skel(s, 0, cut_start)), trim_skel(&slice_from(s, cut_end)))
+}
+
+fn result(parts: (Option, Skel), peeled: Vec) -> SeparatorResult {
+ let split = parts.0.is_some();
+ SeparatorResult { artist: parts.0, title: parts.1, split, peeled }
+}
+
+/// R6.3: the first segment is the artist side, the rest (up to the last kept one) the title.
+fn first_dash_split(skel: &Skel, segments: &[Segment]) -> Option<(Option, Skel)> {
+ let [first, second, ..] = segments else { return None };
+ let last = segments.last()?;
+ let artist = (!first.skel.is_empty()).then(|| first.skel.clone());
+ Some((artist, slice_skel(skel, second.start, last.end)))
+}
+
+pub(crate) fn find_separator(input: SeparatorInput<'_>, ctx: &mut Ctx<'_>) -> SeparatorResult {
+ let skel = input.skel;
+ let mode = input.mode;
+ let segments = split_at_spaced_dashes(skel, true);
+ if mode == Mode::Tracklist {
+ return tracklist_separator(skel, &segments, input.list_context, ctx);
+ }
+ let (remaining, peeled) = peel_suffixes(segments, false, ctx);
+
+ // R6.3
+ if let Some(parts) = first_dash_split(skel, &remaining) {
+ return result(parts, peeled);
+ }
+
+ let rest = remaining.first().map_or_else(|| slice_skel(skel, 0, 0), |s| s.skel.clone());
+ if let Some(other) = split_without_spaced_dash(&rest, mode, ctx) {
+ return result(other, peeled);
+ }
+
+ // R6.8: the uploader fallback does not warn noSeparator.
+ let artist = if mode == Mode::Youtube { input.uploader } else { None };
+ if !rest.is_empty() && artist.is_none() {
+ warn(ctx, Warning::NoSeparator);
+ }
+ SeparatorResult { artist, title: rest, split: false, peeled }
+}
+
+/// R6.10: tracklist mode. The first spaced dash always separates (no R6.2 peeling; R8.2 still
+/// peels later suffixes on the title side). Without one: R6.4, then the first `_-_`, then (list
+/// context only) the last tight `letter-Uppercase` dash; both of these warn `unspacedDashSplit`.
+fn tracklist_separator(
+ skel: &Skel,
+ segments: &[Segment],
+ list_context: bool,
+ ctx: &mut Ctx<'_>,
+) -> SeparatorResult {
+ if let Some(parts) = first_dash_split(skel, segments) {
+ return result(parts, Vec::new());
+ }
+ let rest = segments.first().map_or_else(|| slice_skel(skel, 0, 0), |s| s.skel.clone());
+ if let Some(asym) = asymmetric_dash(&rest.text) {
+ warn(ctx, Warning::AsymmetricDashSplit);
+ return result(split_at(&rest, asym, asym + 1), Vec::new());
+ }
+ if let Some(underscore) = rest.text.windows(3).position(|w| w == ['_', '-', '_']) {
+ warn(ctx, Warning::UnspacedDashSplit);
+ return result(split_at(&rest, underscore, underscore + 3), Vec::new());
+ }
+ if list_context {
+ if let Some(tight) = tight_upper_dash(&rest.text) {
+ warn(ctx, Warning::UnspacedDashSplit);
+ return result(split_at(&rest, tight, tight + 1), Vec::new());
+ }
+ }
+ if !rest.is_empty() {
+ warn(ctx, Warning::NoSeparator);
+ }
+ SeparatorResult { artist: None, title: rest, split: false, peeled: Vec::new() }
+}
+
+/// R6.10: the last `-` with a letter (R0.6) on its left and an uppercase letter (Lu) on its
+/// right, as in R6.7 (`Jay-Z-Numb` → `Jay-Z` / `Numb`).
+fn tight_upper_dash(t: &[char]) -> Option {
+ (1..t.len().saturating_sub(1))
+ .rev()
+ .find(|&i| at(t, i) == Some('-') && is_letter_before(t, i) && is_upper_at(t, i + 1))
+}
+
+fn split_without_spaced_dash(
+ s: &Skel,
+ mode: Mode,
+ ctx: &mut Ctx<'_>,
+) -> Option<(Option, Skel)> {
+ if let Some(asym) = asymmetric_dash(&s.text) {
+ warn(ctx, Warning::AsymmetricDashSplit);
+ return Some(split_at(s, asym, asym + 1));
+ }
+ if mode == Mode::Youtube {
+ if let Some(quoted) = quoted_title(s) {
+ warn(ctx, Warning::QuotedTitleSplit);
+ return Some(quoted);
+ }
+ if let Some(by) = by_split(s, ctx) {
+ warn(ctx, Warning::BySplit);
+ let (left, right) = split_at(s, by, by + 4);
+ let artist = (!right.is_empty()).then_some(right);
+ return Some((artist, left.unwrap_or_else(|| s.clone())));
+ }
+ }
+ if mode == Mode::Youtube || mode == Mode::Filename {
+ if let Some(dash) = unspaced_dash(s, ctx) {
+ warn(ctx, Warning::UnspacedDashSplit);
+ return Some(split_at(s, dash, dash + 1));
+ }
+ }
+ None
+}
+
+/// R6.4: the first `-` with a space on exactly one side.
+fn asymmetric_dash(t: &[char]) -> Option {
+ (1..t.len().saturating_sub(1)).find(|&i| {
+ at(t, i) == Some('-') && is_whitespace(before(t, i)) != is_whitespace(at(t, i + 1))
+ })
+}
+
+/// R6.5: `Artist "Title" (extra)`.
+fn quoted_title(s: &Skel) -> Option<(Option, Skel)> {
+ let t = &s.text;
+ let open = t.iter().position(|&c| c == '"').filter(|&i| i > 0)?;
+ let close = tail(t, open + 1).iter().position(|&c| c == '"')? + open + 1;
+ let mut artist = trim_skel(&slice_skel(s, 0, open));
+ if matches!(artist.text.last(), Some(':' | '-')) {
+ artist = trim_skel(&slice_skel(&artist, 0, artist.len() - 1));
+ }
+ let title = trim_skel(&concat_skel(&slice_skel(s, open + 1, close), &slice_from(s, close + 1)));
+ Some(((!artist.is_empty()).then_some(artist), title))
+}
+
+/// R6.6: index of the space before the last usable ` by `. The right side must be non-empty and
+/// not a single stopword (`Stand by Me`).
+fn by_split(s: &Skel, ctx: &Ctx<'_>) -> Option {
+ let t = &s.text;
+ // Candidates right to left; index 0 is never one (`i > 0` in the JS loop).
+ let mut i = t.len().checked_sub(4)?;
+ while i > 0 {
+ if t.get(i..i + 4) == Some(&[' ', 'b', 'y', ' ']) {
+ // Placeholder-only words (groups such as `(Official Video)`) don't count here.
+ let right: Vec = split_words_chars(tail(t, i + 4))
+ .into_iter()
+ .filter(|w| !(w.chars().count() == 1 && w.starts_with(PH)))
+ .collect();
+ let single_stopword =
+ right.len() == 1 && right.first().is_some_and(|w| in_vocab(w, &ctx.t.stopwords));
+ if !right.is_empty() && !single_stopword {
+ return Some(i);
+ }
+ }
+ i -= 1;
+ }
+ None
+}
+
+/// R6.7: `Jay-Z-Numb` → the chosen unspaced dash index.
+fn unspaced_dash(s: &Skel, ctx: &Ctx<'_>) -> Option {
+ let t = &s.text;
+ let mut last_candidate = None;
+ for i in 1..t.len().saturating_sub(1) {
+ if at(t, i) != Some('-') || is_whitespace(before(t, i)) || is_whitespace(at(t, i + 1)) {
+ continue;
+ }
+ if !(at(t, i + 1) == Some('"') || is_letter_at(t, i + 1)) {
+ continue;
+ }
+ if !ctx.known_keys.is_empty() && is_known_artist(&render_skel(&slice_skel(s, 0, i)), ctx) {
+ return Some(i);
+ }
+ last_candidate = Some(i);
+ }
+ last_candidate
+}
diff --git a/rust/src/serde_support.rs b/rust/src/serde_support.rs
new file mode 100644
index 0000000..0bf9b99
--- /dev/null
+++ b/rust/src/serde_support.rs
@@ -0,0 +1,255 @@
+//! Helpers for the `serde` feature, so `serde_json::to_string(&x)` is the text of `x.to_json()`.
+//!
+//! Numbers share the writer of `to_json()` ([`number_text`]): a whole value is handed to the
+//! serializer as the integer with the digits JavaScript prints (`3167`, not `3167.0`;
+//! `1152921504606847000` for 2^60), so `serde_json` writes the same text.
+//!
+//! What is true for `serde_json`:
+//!
+//! - Every finite number is written as `to_json()` writes it, except where `serde_json`'s own
+//! float notation differs from JavaScript's: `1e-6 <= |x| < 1e-5` (`1e-6` for `0.000001`) and,
+//! in `serde_json` releases that write floats with ryu, `|x| >= 1e21` (`1e21` for `1e+21`).
+//! It is the same number and reads back the same. No time the parser produces is in those
+//! ranges; only an `Edit` or `audio_seconds` built by hand is. Whole values from 2^63 on are
+//! handed over as `u64` / `i128`, which `serde_json` writes; a format without 128-bit integers
+//! reports an error for whole seconds of 2^64 and more.
+//! - Non-finite seconds are written as `null`, as `to_json()` does, and `null` reads back as NaN
+//! (in an `Option`, as `None`). `apply_edits` treats every non-finite value as `edit-invalid`.
+//! - Line numbers above 2^53 are written as JavaScript writes the nearest double, and read back
+//! as that double saturated to `usize`.
+//! - Keyword maps are written as JSON objects without repeated keys: a repeated key keeps its
+//! first place and takes the last value, like a JS object. Reading does the same.
+//!
+//! Formats that are not human-readable get plain `f64` / `u64` values.
+
+use serde::de::{Error as DeError, MapAccess, Visitor};
+use serde::ser::SerializeMap;
+use serde::{Deserialize, Deserializer, Serialize, Serializer};
+
+use crate::json::number_text;
+
+/// 2^53: up to here every whole double is its own decimal text.
+const EXACT: f64 = 9_007_199_254_740_992.0;
+
+/// A double as JS writes numbers, for a human-readable format.
+fn js_number(value: f64, serializer: S) -> Result {
+ if !value.is_finite() {
+ return serializer.serialize_unit(); // `null`, like `JSON.stringify`
+ }
+ if value.fract() != 0.0 || value.abs() >= 1e21 {
+ return serializer.serialize_f64(value);
+ }
+ if value.abs() <= EXACT {
+ return serializer.serialize_i64(value as i64);
+ }
+ // A whole value JS prints without an exponent: the shortest digits that round-trip, then
+ // zeros. Those digits are an integer the serializer can write as they are.
+ let text = number_text(value);
+ if let Ok(n) = text.parse::() {
+ serializer.serialize_i64(n)
+ } else if let Ok(n) = text.parse::() {
+ serializer.serialize_u64(n)
+ } else if let Ok(n) = text.parse::() {
+ serializer.serialize_i128(n)
+ } else {
+ serializer.serialize_f64(value)
+ }
+}
+
+/// Seconds: a whole value is an integer, a non-finite one is `null` (read back as NaN).
+pub(crate) mod seconds {
+ use super::*;
+
+ pub(crate) fn serialize(value: &f64, serializer: S) -> Result {
+ if serializer.is_human_readable() {
+ js_number(*value, serializer)
+ } else {
+ serializer.serialize_f64(*value)
+ }
+ }
+
+ pub(crate) fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result {
+ if deserializer.is_human_readable() {
+ Ok(Option::::deserialize(deserializer)?.unwrap_or(f64::NAN))
+ } else {
+ f64::deserialize(deserializer)
+ }
+ }
+}
+
+pub(crate) fn opt_seconds(
+ value: &Option,
+ serializer: S,
+) -> Result {
+ struct Seconds(f64);
+ impl Serialize for Seconds {
+ fn serialize(&self, serializer: S) -> Result {
+ seconds::serialize(&self.0, serializer)
+ }
+ }
+ value.map(Seconds).serialize(serializer)
+}
+
+/// A line number of an edit. `to_json()` writes it as a JS number, so above 2^53 it is the
+/// nearest double; this writes the same digits and reads them back (saturating at `usize::MAX`).
+struct Line(usize);
+
+impl Serialize for Line {
+ fn serialize(&self, serializer: S) -> Result {
+ if serializer.is_human_readable() && self.0 as u64 > (1 << 53) {
+ js_number(self.0 as f64, serializer)
+ } else {
+ serializer.serialize_u64(self.0 as u64)
+ }
+ }
+}
+
+impl<'de> Deserialize<'de> for Line {
+ fn deserialize>(deserializer: D) -> Result {
+ struct LineVisitor;
+ impl Visitor<'_> for LineVisitor {
+ type Value = Line;
+
+ fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("a line number (a non-negative whole number)")
+ }
+
+ fn visit_u64(self, v: u64) -> Result {
+ Ok(Line(usize::try_from(v).unwrap_or(usize::MAX)))
+ }
+
+ fn visit_i64(self, v: i64) -> Result {
+ u64::try_from(v)
+ .map_err(|_| E::custom(format_args!("a line number cannot be negative: {v}")))
+ .and_then(|v| self.visit_u64(v))
+ }
+
+ fn visit_f64(self, v: f64) -> Result {
+ if v.is_finite() && v.fract() == 0.0 && v >= 0.0 {
+ Ok(Line(v as usize)) // saturates
+ } else {
+ Err(E::custom(format_args!("a line number must be a whole number: {v}")))
+ }
+ }
+ }
+ // A self-describing format may hold the number as a double (`18446744073709552000`), and
+ // an `Edit` is read through serde's buffer for tagged enums, which only hands a double
+ // to `deserialize_any`.
+ if deserializer.is_human_readable() {
+ deserializer.deserialize_any(LineVisitor)
+ } else {
+ deserializer.deserialize_u64(LineVisitor)
+ }
+ }
+}
+
+pub(crate) mod line {
+ use super::*;
+
+ pub(crate) fn serialize(v: &usize, serializer: S) -> Result {
+ Line(*v).serialize(serializer)
+ }
+
+ pub(crate) fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result {
+ Line::deserialize(d).map(|l| l.0)
+ }
+}
+
+pub(crate) mod opt_line {
+ use super::*;
+
+ pub(crate) fn serialize(
+ v: &Option,
+ serializer: S,
+ ) -> Result {
+ v.map(Line).serialize(serializer)
+ }
+
+ pub(crate) fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result