ltk_ritobin/lib.rs
1//! Ritobin text format parser and writer for League Toolkit.
2//!
3//! This crate provides functionality to parse and write the ritobin text format,
4//! which is a human-readable representation of League of Legends bin files.
5//!
6//! # Quick start
7//!
8//! Parse ritobin text, build a [`Bin`], and round-trip it back to text:
9//!
10//! ```rust
11//! use ltk_ritobin::{Cst, Print as _};
12//!
13//! let text = r#"
14//! #PROP_text
15//! type: string = "PROP"
16//! version: u32 = 3
17//! linked: list[string] = { }
18//! entries: map[hash, embed] = { }
19//! "#.trim();
20//!
21//! let cst = Cst::parse(text);
22//! assert!(cst.errors.is_empty());
23//!
24//! let partial = cst.build_bin(text);
25//! assert!(partial.diagnostics.is_empty());
26//!
27//! // Write back to text
28//! let output = partial.bin.print().unwrap();
29//!
30//! assert_eq!(text, output);
31//! ```
32//!
33//! # Converting `.bin` to ritobin
34//!
35//! `.bin` files identify fields and types by FNV-1a hashes. Supplying a [`HashProvider`]
36//! lets the printer emit the original names instead of `0xdeadbeef` literals:
37//!
38//! ```no_run
39//! use std::io::BufReader;
40//! use std::fs::File;
41//! use ltk_meta::Bin;
42//! use ltk_ritobin::{Print, print::PrintConfig, HashMapProvider};
43//!
44//! let mut reader = BufReader::new(File::open("data.bin")?);
45//! let bin = Bin::from_reader(&mut reader)?;
46//!
47//! let mut hashes = HashMapProvider::new();
48//! hashes.load_from_directory("hashes/"); // loads hashes.bin{entries,fields,hashes,types}.txt
49//!
50//! let text = bin.print_with_config(PrintConfig::default().with_hashes(hashes))?;
51//! std::fs::write("data.rito", text)?;
52//! # Ok::<(), Box<dyn std::error::Error>>(())
53//! ```
54//!
55//! # Error reporting
56//!
57//! For resilient parsing, errors exist as nodes into the concrete syntax tree (cst), which propagate into the [`Node`]s' `errors` field (depending on [`parse::ErrorPropagation`]). This
58//! allows for more versatile behaviour with things like pretty-printing technically invalid trees,
59//! since parsing will always result in a cst.
60//!
61//! The same handling of errors is done in the type-checker (when building a [`ltk_meta::Bin`]), to
62//! always provide a best effort construction.
63//!
64//! ```rust
65//! use ltk_ritobin::Cst;
66//!
67//! let text = "test: u32 = 4!!2";
68//!
69//! // by default uses ErrorPropagation::Move,
70//! // so all errors will end up in the root
71//! let cst = Cst::parse(text);
72//!
73//! assert_eq!(cst.errors.len(), 1); // the unexpected "!!" in the value
74//! ```
75//!
76//! `Cst::build_bin` follows the same philosophy: it returns a [`ast::PartialBin`], pairing a
77//! best-effort `Bin` with any diagnostics, so type errors don't prevent you from getting a
78//! `Bin` back. This matters for editor use cases: between keystrokes a buffer is almost always
79//! temporarily invalid, and tooling still needs to render it, navigate it, and report problems
80//! with precise spans. Use [`ast::PartialBin::into_result`] where you instead want a `Result` that
81//! only succeeds on a clean build.
82//!
83//! # Patch files
84//!
85//! A file whose `type` root is `"PTCH"` describes a patch bin. Its `patches` root holds one
86//! `patch` embed per record, and its optional `deleted` root lists the objects it deletes.
87//! [`Cst::build`] builds either kind of file as a [`ltk_meta::BinFile`], and [`Print`] is
88//! implemented for [`ltk_meta::BinOverride`] and [`ltk_meta::BinFile`]:
89//!
90//! ```rust
91//! use ltk_meta::BinFile;
92//! use ltk_ritobin::Cst;
93//!
94//! let text = r#"
95//! #PTCH_text
96//! type: string = "PTCH"
97//! version: u32 = 3
98//! linked: list[string] = {}
99//! entries: map[hash,embed] = {}
100//! patches: map[hash,embed] = {
101//! 0x4a47c414 = patch {
102//! path: string = "Position.Anchors.Anchor"
103//! value: vec2 = { 0, 1 }
104//! }
105//! }
106//! "#;
107//!
108//! let (file, diagnostics) = Cst::parse(text).build(text);
109//! assert!(diagnostics.is_empty());
110//!
111//! let BinFile::Override(patch) = file else { unreachable!() };
112//! assert_eq!(patch.patches.len(), 1);
113//! ```
114
115use std::{
116 fmt::{self, Display},
117 ops::{Deref, DerefMut},
118};
119
120#[allow(unused, reason = "for module level doc link")]
121use ltk_meta::Bin;
122
123// The `DebugSpans` derive emits `::ltk_ritobin::span` paths.
124extern crate self as ltk_ritobin;
125
126pub mod span;
127pub use span::Span;
128
129pub mod ast;
130pub mod cst;
131pub mod escaping;
132pub mod hashes;
133pub mod parse;
134pub mod print;
135pub mod types;
136
137pub use hashes::*;
138pub use types::*;
139
140pub use cst::Cst;
141
142/// Items that `rito!` names through `$crate`. Not part of the public API.
143#[doc(hidden)]
144pub mod __private {
145 pub use ltk_meta::PropertyKind;
146}
147pub use cst::Node;
148pub use print::Print;
149
150pub trait SpannedExt {
151 fn with_span(self, span: Span) -> Spanned<Self>
152 where
153 Self: Sized;
154}
155
156impl<T> SpannedExt for T {
157 fn with_span(self, span: Span) -> Spanned<Self> {
158 Spanned::new(span, self)
159 }
160}
161
162#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
163#[cfg_attr(feature = "span_print", derive(span::DebugSpans))]
164pub struct Spanned<T> {
165 pub span: Span,
166 pub value: T,
167}
168
169impl<T: Display> Display for Spanned<T> {
170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171 self.value.fmt(f)
172 }
173}
174
175impl<T> Spanned<T> {
176 pub fn new(span: Span, value: T) -> Self {
177 Self { span, value }
178 }
179}
180
181impl<T: Default> Spanned<T> {
182 pub fn spanned_default(span: Span) -> Self {
183 Self {
184 span,
185 value: T::default(),
186 }
187 }
188}
189
190impl<T> DerefMut for Spanned<T> {
191 fn deref_mut(&mut self) -> &mut Self::Target {
192 &mut self.value
193 }
194}
195
196impl<T> Deref for Spanned<T> {
197 type Target = T;
198 fn deref(&self) -> &Self::Target {
199 &self.value
200 }
201}
202
203impl<T> AsMut<T> for Spanned<T> {
204 fn as_mut(&mut self) -> &mut T {
205 &mut self.value
206 }
207}
208
209impl<T> AsRef<T> for Spanned<T> {
210 fn as_ref(&self) -> &T {
211 &self.value
212 }
213}
214
215impl AsRef<str> for Spanned<String> {
216 fn as_ref(&self) -> &str {
217 &self.value
218 }
219}