trackparse/lib.rs
1//! Turn messy track names into structured data: artists with roles, remixes and versions,
2//! junk, and whole tracklists.
3//!
4//! trackparse is driven by a written spec. Behaviour is defined by [`SPEC.md`] and its shared
5//! fixtures. This crate passes every shared fixture, and for every fixture input its output is
6//! byte-identical to the JavaScript (npm `trackparse`) and Python (PyPI `trackparse`) packages.
7//! Rule IDs such as `R6.2` in these docs refer to the spec.
8//!
9//! - User documentation: <https://4matic.github.io/trackparse/>
10//! - The spec: <https://4matic.github.io/trackparse/reference/spec/>
11//!
12//! [`SPEC.md`]: https://github.com/4matic/trackparse/blob/main/spec/SPEC.md
13//!
14//! # Single tracks
15//!
16//! [`parse`] takes any string and returns a [`ParsedTrack`]. It never panics and never returns
17//! an error: what it recognises goes into a field, what it does not stays in the title.
18//!
19//! ```
20//! use trackparse::{parse, ArtistRole, JunkKind, VersionType};
21//!
22//! let track = parse("Noisia feat. Foreign Beggars - Shellshock (Rockwell Remix) [Official Video]");
23//!
24//! assert_eq!(track.artists[0].name, "Noisia");
25//! assert_eq!(track.artists[1].name, "Foreign Beggars");
26//! assert_eq!(track.artists[1].role, ArtistRole::Featured);
27//! assert_eq!(track.title, "Shellshock");
28//! assert_eq!(track.full_title, "Shellshock (Rockwell Remix)");
29//! assert_eq!(track.versions[0].version_type, VersionType::Remix);
30//! assert_eq!(track.versions[0].artists[0].name, "Rockwell");
31//! assert_eq!(track.junk[0].kind, JunkKind::Video);
32//! ```
33//!
34//! [`parse_with`] takes [`ParseOptions`]; a [`Parser`] keeps resolved options for many calls.
35//! [`parse_artists`] splits a credit string, [`format_track`] writes a track back as a string,
36//! [`normalize()`] cleans a string without parsing it, and [`all_artists`] lists every credited
37//! name, remixers included.
38//!
39//! ```
40//! use trackparse::{format_track_with, parse_with, FeatPlacement, FormatOptions, ParseOptions};
41//!
42//! let options = ParseOptions::new().known_artists(["Chase & Status"]);
43//! let track = parse_with("Chase & Status - Blind Faith ft. Liam Bailey", &options);
44//! assert_eq!(track.artists.len(), 2);
45//!
46//! let format = FormatOptions::new().feat(FeatPlacement::Artist);
47//! assert_eq!(format_track_with(&track, &format), "Chase & Status ft. Liam Bailey - Blind Faith");
48//! ```
49//!
50//! # Tracklists
51//!
52//! The [`tracklist`] module reads a whole pasted tracklist: one entry per line, with its time,
53//! its kind and the parsed track, plus warnings about the times. [`tracklist::apply_edits`]
54//! rewrites times and lines without touching anything else.
55//!
56//! ```
57//! use trackparse::tracklist::{apply_edits, parse_tracklist, Edit, WarningCode};
58//!
59//! let text = "00:00 Noisia - Stigma\n03:45 Phace & Misanthrop - Desert Orgy\n02:10 Mefjus - Suicide Bassline";
60//! let list = parse_tracklist(text);
61//! assert_eq!(list.stats.tracks, 3);
62//! assert_eq!(list.entries[1].time.as_ref().unwrap().seconds, 225.0);
63//! assert_eq!(list.entries[1].track.as_ref().unwrap().title, "Desert Orgy");
64//! assert_eq!(list.warnings[0].code, WarningCode::TimeOutOfOrder);
65//!
66//! let fixed = apply_edits(text, &[Edit::sort_by_time()]);
67//! assert_eq!(
68//! fixed.text,
69//! "00:00 Noisia - Stigma\n02:10 Mefjus - Suicide Bassline\n03:45 Phace & Misanthrop - Desert Orgy"
70//! );
71//! ```
72//!
73//! # JSON
74//!
75//! Fields are snake_case in Rust. `to_json()` on every output type writes the spec's JSON form:
76//! camelCase keys (`fullTitle`, `unknownArtist`), every key present, in the schema's order. It is
77//! the same text the JavaScript and Python packages produce, and needs no dependency.
78//!
79//! ```
80//! let artists = trackparse::parse_artists("Noisia & Phace");
81//! assert_eq!(
82//! artists[1].to_json(),
83//! r#"{"name":"Phace","role":"primary","joiner":"&","source":"artist"}"#
84//! );
85//! ```
86//!
87//! With the `serde` feature the output types implement `Serialize` and `Deserialize` with the
88//! same keys, so `serde_json::to_string(&track)` gives the text of `track.to_json()`. The
89//! options and [`tracklist::Edit`] implement both traits too. Numbers are written as
90//! `to_json()` writes them. The exceptions are numbers no parse result contains: seconds from
91//! 0.000001 up to 0.00001 (and, with older `serde_json` releases, of 1e21 and more) in an
92//! `Edit` or an option built by hand, which `serde_json` writes in its own float notation
93//! (`1e-6` for `0.000001`). Non-finite seconds are written as `null`, as by `to_json()`, and
94//! `null` reads back as NaN. Keyword maps are written without repeated keys (the last value
95//! wins, as in a JS object).
96//!
97//! # Guarantees
98//!
99//! - Total: any `&str` gives a result. No panics, no `Result` (R0.8).
100//! - No regular expressions and no backtracking: the scanners make a bounded number of passes
101//! over the input. A 10,000-code-point string parses in a few milliseconds, and the test suite
102//! checks that repeated hostile fragments scale far below quadratic.
103//! - No `unsafe`. One dependency (`unicode-normalization`); `serde` only with the feature.
104//! - The Unicode tables the rules depend on (letters, uppercase letters, lowercase mapping) are
105//! compiled in, so the output does not change with the compiler version.
106//! - NFC and NFD (R1, R0.4) come from `unicode-normalization` and follow that crate's Unicode
107//! version: 0.1.26, the minimum this crate accepts, has the Unicode 18 tables. The JavaScript
108//! reference normalizes with its runtime's tables (Unicode 17 on Node 24), so a string with
109//! one of the 32 combining marks added in Unicode 18 can come out in another mark order than
110//! it does there. Text without those marks is not affected.
111
112#![warn(missing_docs)]
113#![cfg_attr(docsrs, feature(doc_cfg))]
114
115pub mod json;
116pub mod tracklist;
117#[doc(hidden)]
118pub mod wire;
119
120mod artists;
121mod assemble;
122mod classify;
123mod context;
124mod credits;
125#[rustfmt::skip]
126mod data;
127mod digits;
128mod format;
129mod mode;
130mod normalize;
131mod options;
132mod parser;
133mod prefix;
134mod scanner;
135mod separator;
136#[cfg(feature = "serde")]
137mod serde_support;
138mod tables;
139mod title;
140mod types;
141#[rustfmt::skip]
142mod unicode_tables;
143mod value;
144mod words;
145
146pub use data::SPEC_VERSION;
147pub use options::{
148 FeatPlacement, FormatOptions, JoinerStyle, KeywordOptions, ModeOption, ParseOptions, SplitAnd,
149 VersionsOption,
150};
151pub use types::{
152 Artist, ArtistRole, ArtistSource, Flags, Junk, JunkKind, Mode, ParsedTrack, Position,
153 Timestamp, ToJson, UnknownName, Version, VersionDelimiter, VersionType, Warning,
154};
155
156use options::{Resolved, ResolvedFormat};
157use parser::Engine;
158
159/// The examples of the README, run as doc tests (they use the `serde` feature).
160#[cfg(all(doctest, feature = "serde"))]
161#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
162#[doc = include_str!("../README.md")]
163pub struct ReadmeDoctests;
164
165/// Parse one track string with the default options (mode `auto`).
166///
167/// Never panics: any string gives a [`ParsedTrack`] (SPEC R0.8).
168///
169/// ```
170/// let track = trackparse::parse("Sub Focus - Out the Blue ft. Alice Gold (2015)");
171/// assert_eq!(track.title, "Out the Blue");
172/// assert_eq!(track.year, Some(2015));
173/// assert_eq!(track.artists.len(), 2);
174/// ```
175pub fn parse(input: &str) -> ParsedTrack {
176 Engine::shared().run(input, false).into_track()
177}
178
179/// Parse one track string with options (R12).
180///
181/// To parse many strings with the same options, build a [`Parser`] once instead.
182///
183/// ```
184/// use trackparse::{parse_with, Mode, ModeOption, ParseOptions};
185///
186/// let options = ParseOptions::new().mode(ModeOption::Youtube);
187/// let track = parse_with("Noisia - Stigma (Official Video)", &options);
188/// assert_eq!(track.mode, Mode::Youtube);
189/// assert_eq!(track.title, "Stigma");
190/// assert_eq!(track.junk[0].raw, "Official Video");
191/// ```
192pub fn parse_with(input: &str, options: &ParseOptions) -> ParsedTrack {
193 Parser::new(options).parse(input)
194}
195
196/// Split a credit string into artists (R10).
197///
198/// ```
199/// let artists = trackparse::parse_artists("Noisia & The Upbeats feat. Foreign Beggars");
200/// let names: Vec<&str> = artists.iter().map(|a| a.name.as_str()).collect();
201/// assert_eq!(names, ["Noisia", "The Upbeats", "Foreign Beggars"]);
202/// ```
203pub fn parse_artists(input: &str) -> Vec<Artist> {
204 Engine::shared().run_artists(input)
205}
206
207/// [`parse_artists`] with options (`known_artists`, `split_and`, `keywords`).
208///
209/// ```
210/// use trackparse::{parse_artists_with, ParseOptions};
211///
212/// let options = ParseOptions::new().known_artists(["Above & Beyond"]);
213/// let artists = parse_artists_with("Above & Beyond & Zoë Johnston", &options);
214/// let names: Vec<&str> = artists.iter().map(|a| a.name.as_str()).collect();
215/// assert_eq!(names, ["Above & Beyond", "Zoë Johnston"]);
216/// ```
217pub fn parse_artists_with(input: &str, options: &ParseOptions) -> Vec<Artist> {
218 Parser::new(options).parse_artists(input)
219}
220
221/// Render a parsed track back to a string (R11) with the default format options.
222///
223/// ```
224/// use trackparse::{format_track, parse};
225///
226/// let track = parse("Sub Focus - Out the Blue ft. Alice Gold");
227/// assert_eq!(format_track(&track), "Sub Focus - Out the Blue (ft. Alice Gold)");
228/// ```
229pub fn format_track(track: &ParsedTrack) -> String {
230 format_track_with(track, &FormatOptions::default())
231}
232
233/// Render a parsed track back to a string (R11).
234///
235/// ```
236/// use trackparse::{format_track_with, parse, FeatPlacement, FormatOptions};
237///
238/// let track = parse("Sub Focus - Out the Blue ft. Alice Gold");
239/// let options = FormatOptions::new().feat(FeatPlacement::Artist);
240/// assert_eq!(format_track_with(&track, &options), "Sub Focus ft. Alice Gold - Out the Blue");
241/// ```
242pub fn format_track_with(track: &ParsedTrack, options: &FormatOptions) -> String {
243 let input = format::FormatInput {
244 artists: &track.artists,
245 title: &track.title,
246 versions: track.versions.iter().map(|v| (v.raw.as_str(), v.delimiter)).collect(),
247 position_raw: track.position.as_ref().map(|p| p.raw.as_str()),
248 };
249 format::format(&input, &ResolvedFormat::from_typed(options))
250}
251
252/// Normalize a track string (R1): NFC, ASCII brackets, quotes and dashes, invisible characters
253/// removed, whitespace collapsed. Idempotent.
254///
255/// ```
256/// assert_eq!(trackparse::normalize(" Noisia – Stigma\u{200b} "), "Noisia - Stigma");
257/// ```
258pub fn normalize(input: &str) -> String {
259 normalize::normalize(input)
260}
261
262/// All credited names: the track's artists plus every version's remixers, deduped (R0.4 key).
263///
264/// ```
265/// let track = trackparse::parse("Fox Stevenson - Bruises (Magnetude Remix)");
266/// let names: Vec<String> = trackparse::all_artists(&track).into_iter().map(|a| a.name).collect();
267/// assert_eq!(names, ["Fox Stevenson", "Magnetude"]);
268/// ```
269pub fn all_artists(track: &ParsedTrack) -> Vec<Artist> {
270 format::all_artists(
271 track.artists.iter().chain(track.versions.iter().flat_map(|v| v.artists.iter())),
272 )
273}
274
275/// A parser with its options resolved and its vocabulary tables built once (`createParser` in
276/// JavaScript, `create_parser` in Python). Use it to parse many strings with the same options.
277/// It is `Send + Sync`, and cloning it is cheap (the tables are shared).
278///
279/// ```
280/// use trackparse::{ParseOptions, Parser};
281///
282/// let parser = Parser::new(&ParseOptions::new().known_artists(["Chase & Status"]));
283/// let track = parser.parse("Chase & Status - Blind Faith");
284/// assert_eq!(track.artists.len(), 1);
285/// assert_eq!(track.artists[0].name, "Chase & Status");
286/// ```
287#[derive(Clone)]
288pub struct Parser {
289 engine: Engine,
290}
291
292impl Parser {
293 /// Resolve `options` and build the vocabulary tables.
294 pub fn new(options: &ParseOptions) -> Parser {
295 Parser { engine: Engine::new(Resolved::from_typed(options)) }
296 }
297
298 /// [`parse`] with this parser's options.
299 pub fn parse(&self, input: &str) -> ParsedTrack {
300 self.engine.run(input, false).into_track()
301 }
302
303 /// [`parse_artists`] with this parser's options.
304 ///
305 /// ```
306 /// use trackparse::{ParseOptions, Parser, SplitAnd};
307 ///
308 /// let parser = Parser::new(&ParseOptions::new().split_and(SplitAnd::Always));
309 /// assert_eq!(parser.parse_artists("Above and Beyond").len(), 2);
310 /// ```
311 pub fn parse_artists(&self, input: &str) -> Vec<Artist> {
312 self.engine.run_artists(input)
313 }
314}
315
316impl Default for Parser {
317 fn default() -> Self {
318 Parser::new(&ParseOptions::default())
319 }
320}
321
322impl std::fmt::Debug for Parser {
323 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
324 f.debug_struct("Parser").finish_non_exhaustive()
325 }
326}